WebServer.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #pragma once
  2. #include <boost/beast/core.hpp>
  3. #include <boost/beast/http.hpp>
  4. #include <boost/beast/ssl.hpp>
  5. #include <boost/beast/version.hpp>
  6. #include <boost/asio/ip/tcp.hpp>
  7. #include <boost/asio/strand.hpp>
  8. #include <boost/config.hpp>
  9. #include <string>
  10. #include <thread>
  11. #include <functional>
  12. #include <unordered_map>
  13. #include "../types.h"
  14. namespace beast = boost::beast; // from <boost/beast.hpp>
  15. namespace http = beast::http; // from <boost/beast/http.hpp>
  16. namespace boost_net = boost::asio; // from <boost/asio.hpp>
  17. namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
  18. using tcp = boost_net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  19. class WebServer {
  20. public:
  21. WebServer(const std::string& address, unsigned short port, const std::string& cert_file, const std::string& key_file, const std::string& key_password, const std::string& hardcode_user, const std::string& hardcode_password);
  22. ~WebServer();
  23. void run();
  24. void start();
  25. void register_route(const std::string& uri, std::function<void(const http::request<http::string_body>&, http::response<http::string_body>&)> handler, bool auth_required = true);
  26. private:
  27. bool is_ssl;
  28. static std::string my_password_callback(std::size_t max_length, ssl::context::password_purpose purpose);
  29. void do_accept();
  30. void on_accept(beast::error_code ec, tcp::socket socket);
  31. void do_session_ssl(tcp::socket socket);
  32. void do_session(tcp::socket socket);
  33. template <class Body, class Allocator>
  34. void handle_request(http::request<Body, http::basic_fields<Allocator>>&& req, std::function<void(http::response<http::string_body>&&)> send);
  35. std::string authenticate(const http::request<http::string_body>& req, int32* user_status = 0);
  36. std::string generate_session_id();
  37. boost_net::io_context ioc_;
  38. ssl::context ssl_ctx_;
  39. tcp::acceptor acceptor_;
  40. std::unordered_map<std::string, std::string> sessions_; // session_id -> username
  41. std::unordered_map<std::string, int32> sessions_status_; // session_id -> status
  42. std::unordered_map<std::string, std::string> credentials_; // username -> password
  43. std::unordered_map<std::string, int32> route_required_status_; // route -> status
  44. std::unordered_map<std::string, std::function<void(const http::request<http::string_body>&, http::response<http::string_body>&)>> routes_;
  45. std::unordered_map<std::string, std::function<void(const http::request<http::string_body>&, http::response<http::string_body>&)>> noauth_routes_;
  46. };