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