xref: /openbmc/bmcweb/http/parsing.hpp (revision 3577e44683a5ade8ad02a6418984b56f4ca2bcac)
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 <string_view>
15 
16 enum class JsonParseResult
17 {
18     BadContentType,
19     BadJsonData,
20     Success,
21 };
22 
isJsonContentType(std::string_view contentType)23 inline bool isJsonContentType(std::string_view contentType)
24 {
25     return http_helpers::getContentType(contentType) ==
26            http_helpers::ContentType::JSON;
27 }
28 
parseRequestAsJson(const crow::Request & req,nlohmann::json & jsonOut)29 inline JsonParseResult parseRequestAsJson(const crow::Request& req,
30                                           nlohmann::json& jsonOut)
31 {
32     if (!isJsonContentType(
33             req.getHeaderValue(boost::beast::http::field::content_type)))
34     {
35         BMCWEB_LOG_WARNING("Failed to parse content type on request");
36         if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
37         {
38             return JsonParseResult::BadContentType;
39         }
40     }
41     jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
42     if (jsonOut.is_discarded())
43     {
44         BMCWEB_LOG_WARNING("Failed to parse json in request");
45         return JsonParseResult::BadJsonData;
46     }
47 
48     return JsonParseResult::Success;
49 }
50