xref: /openbmc/bmcweb/http/parsing.hpp (revision a529a6aa)
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,
24                                 "application/json; charset=utf-8") ||
25            bmcweb::asciiIEquals(contentType, "application/json;charset=utf-8");
26 }
27 
28 inline JsonParseResult parseRequestAsJson(const crow::Request& req,
29                                           nlohmann::json& jsonOut)
30 {
31     if (!isJsonContentType(
32             req.getHeaderValue(boost::beast::http::field::content_type)))
33     {
34         BMCWEB_LOG_WARNING("Failed to parse content type on request");
35         if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
36         {
37             return JsonParseResult::BadContentType;
38         }
39     }
40     jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
41     if (jsonOut.is_discarded())
42     {
43         BMCWEB_LOG_WARNING("Failed to parse json in request");
44         return JsonParseResult::BadJsonData;
45     }
46 
47     return JsonParseResult::Success;
48 }
49