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