xref: /openbmc/bmcweb/http/parsing.hpp (revision 08bbe119)
1 #pragma once
2 
3 #include "http/http_request.hpp"
4 #include "logging.hpp"
5 
6 #include <boost/algorithm/string/predicate.hpp>
7 #include <nlohmann/json.hpp>
8 
9 #include <string_view>
10 
11 enum class JsonParseResult
12 {
13     BadContentType,
14     BadJsonData,
15     Success,
16 };
17 
18 inline JsonParseResult parseRequestAsJson(const crow::Request& req,
19                                           nlohmann::json& jsonOut)
20 {
21     std::string_view contentType =
22         req.getHeaderValue(boost::beast::http::field::content_type);
23 
24     if (!boost::iequals(contentType, "application/json") &&
25         !boost::iequals(contentType, "application/json; charset=utf-8"))
26     {
27         BMCWEB_LOG_WARNING << "Failed to parse content type on request";
28 #ifndef BMCWEB_INSECURE_IGNORE_CONTENT_TYPE
29         return JsonParseResult::BadContentType;
30 #endif
31     }
32     jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
33     if (jsonOut.is_discarded())
34     {
35         BMCWEB_LOG_WARNING << "Failed to parse json in request";
36         return JsonParseResult::BadJsonData;
37     }
38 
39     return JsonParseResult::Success;
40 }
41