xref: /openbmc/bmcweb/http/http_request.hpp (revision 60c922df)
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     boost::urls::query_params_view urlParams{};
27     bool isSecure{false};
28 
29     const 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     boost::beast::http::verb method() const
49     {
50         return req.method();
51     }
52 
53     std::string_view getHeaderValue(std::string_view key) const
54     {
55         return req[key];
56     }
57 
58     std::string_view getHeaderValue(boost::beast::http::field key) const
59     {
60         return req[key];
61     }
62 
63     std::string_view methodString() const
64     {
65         return req.method_string();
66     }
67 
68     std::string_view target() const
69     {
70         return req.target();
71     }
72 
73     bool target(const std::string_view target)
74     {
75         req.target(target);
76         return setUrlInfo();
77     }
78 
79     unsigned version() const
80     {
81         return req.version();
82     }
83 
84     bool isUpgrade() const
85     {
86         return boost::beast::websocket::is_upgrade(req);
87     }
88 
89     bool keepAlive() const
90     {
91         return req.keep_alive();
92     }
93 
94   private:
95     bool setUrlInfo()
96     {
97         boost::urls::error_code ec;
98         urlView = boost::urls::parse_relative_ref(
99             boost::urls::string_view(target().data(), target().size()), ec);
100         if (ec)
101         {
102             return false;
103         }
104         url = std::string_view(urlView.encoded_path().data(),
105                                urlView.encoded_path().size());
106         urlParams = urlView.query_params();
107         return true;
108     }
109 };
110 
111 } // namespace crow
112