1 #pragma once 2 3 #include "common.hpp" 4 #include "sessions.hpp" 5 6 #include <boost/asio/io_context.hpp> 7 #include <boost/asio/ip/address.hpp> 8 #include <boost/beast/http/message.hpp> 9 #include <boost/beast/http/string_body.hpp> 10 #include <boost/beast/websocket.hpp> 11 #include <boost/url/url.hpp> 12 13 #include <string> 14 #include <string_view> 15 #include <system_error> 16 17 namespace crow 18 { 19 20 struct Request 21 { 22 boost::beast::http::request<boost::beast::http::string_body> req; 23 24 private: 25 boost::urls::url urlBase{}; 26 27 public: 28 bool isSecure{false}; 29 30 boost::asio::io_context* ioService{}; 31 boost::asio::ip::address ipAddress{}; 32 33 std::shared_ptr<persistent_data::UserSession> session; 34 35 std::string userRole{}; 36 Request(boost::beast::http::request<boost::beast::http::string_body> reqIn, 37 std::error_code& ec) : 38 req(std::move(reqIn)) 39 { 40 if (!setUrlInfo()) 41 { 42 ec = std::make_error_code(std::errc::invalid_argument); 43 } 44 } 45 46 Request(std::string_view bodyIn, std::error_code& ec) : req({}, bodyIn) 47 { 48 if (!setUrlInfo()) 49 { 50 ec = std::make_error_code(std::errc::invalid_argument); 51 } 52 } 53 54 Request(const Request& other) = default; 55 Request(Request&& other) = default; 56 57 Request& operator=(const Request&) = delete; 58 Request& operator=(const Request&&) = delete; 59 ~Request() = default; 60 61 boost::beast::http::verb method() const 62 { 63 return req.method(); 64 } 65 66 std::string_view getHeaderValue(std::string_view key) const 67 { 68 return req[key]; 69 } 70 71 std::string_view getHeaderValue(boost::beast::http::field key) const 72 { 73 return req[key]; 74 } 75 76 std::string_view methodString() const 77 { 78 return req.method_string(); 79 } 80 81 std::string_view target() const 82 { 83 return req.target(); 84 } 85 86 boost::urls::url_view url() const 87 { 88 return {urlBase}; 89 } 90 91 const boost::beast::http::fields& fields() const 92 { 93 return req.base(); 94 } 95 96 const std::string& body() const 97 { 98 return req.body(); 99 } 100 101 bool target(std::string_view target) 102 { 103 req.target(target); 104 return setUrlInfo(); 105 } 106 107 unsigned version() const 108 { 109 return req.version(); 110 } 111 112 bool isUpgrade() const 113 { 114 return boost::beast::websocket::is_upgrade(req); 115 } 116 117 bool keepAlive() const 118 { 119 return req.keep_alive(); 120 } 121 122 private: 123 bool setUrlInfo() 124 { 125 auto result = boost::urls::parse_relative_ref(target()); 126 127 if (!result) 128 { 129 return false; 130 } 131 urlBase = *result; 132 return true; 133 } 134 }; 135 136 } // namespace crow 137