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_view.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 boost::beast::http::fields& fields; 24 std::string_view url{}; 25 boost::urls::url_view urlView{}; 26 27 bool isSecure{false}; 28 29 std::string& body; 30 31 boost::asio::io_context* ioService{}; 32 boost::asio::ip::address ipAddress{}; 33 34 std::shared_ptr<persistent_data::UserSession> session; 35 36 std::string userRole{}; 37 Request(boost::beast::http::request<boost::beast::http::string_body> reqIn, 38 std::error_code& ec) : 39 req(std::move(reqIn)), 40 fields(req.base()), body(req.body()) 41 { 42 if (!setUrlInfo()) 43 { 44 ec = std::make_error_code(std::errc::invalid_argument); 45 } 46 } 47 48 Request(const Request&) = delete; 49 Request(const Request&&) = delete; 50 Request& operator=(const Request&) = delete; 51 Request& operator=(const Request&&) = delete; 52 ~Request() = default; 53 54 boost::beast::http::verb method() const 55 { 56 return req.method(); 57 } 58 59 std::string_view getHeaderValue(std::string_view key) const 60 { 61 return req[key]; 62 } 63 64 std::string_view getHeaderValue(boost::beast::http::field key) const 65 { 66 return req[key]; 67 } 68 69 std::string_view methodString() const 70 { 71 return req.method_string(); 72 } 73 74 std::string_view target() const 75 { 76 return req.target(); 77 } 78 79 bool target(const std::string_view target) 80 { 81 req.target(target); 82 return setUrlInfo(); 83 } 84 85 unsigned version() const 86 { 87 return req.version(); 88 } 89 90 bool isUpgrade() const 91 { 92 return boost::beast::websocket::is_upgrade(req); 93 } 94 95 bool keepAlive() const 96 { 97 return req.keep_alive(); 98 } 99 100 private: 101 bool setUrlInfo() 102 { 103 auto result = boost::urls::parse_relative_ref( 104 boost::urls::string_view(target().data(), target().size())); 105 106 if (!result) 107 { 108 return false; 109 } 110 urlView = *result; 111 url = std::string_view(urlView.encoded_path().data(), 112 urlView.encoded_path().size()); 113 return true; 114 } 115 }; 116 117 } // namespace crow 118