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