blob: d59621104c7ef5714101536991727b5ce5be6e5a [file] [log] [blame]
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01001#pragma once
2
3#include "http/http_request.hpp"
4#include "logging.hpp"
Ed Tanous18f8f602023-07-18 10:07:23 -07005#include "str_utility.hpp"
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01006
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01007#include <nlohmann/json.hpp>
8
Ed Tanous18f8f602023-07-18 10:07:23 -07009#include <algorithm>
10#include <cctype>
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010011#include <string_view>
12
13enum class JsonParseResult
14{
15 BadContentType,
16 BadJsonData,
17 Success,
18};
19
Ed Tanous18f8f602023-07-18 10:07:23 -070020inline bool isJsonContentType(std::string_view contentType)
21{
22 return bmcweb::asciiIEquals(contentType, "application/json") ||
Ed Tanous1fccd0d2024-03-19 09:16:16 -070023 bmcweb::asciiIEquals(contentType,
24 "application/json; charset=utf-8") ||
25 bmcweb::asciiIEquals(contentType, "application/json;charset=utf-8");
Ed Tanous18f8f602023-07-18 10:07:23 -070026}
27
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010028inline JsonParseResult parseRequestAsJson(const crow::Request& req,
29 nlohmann::json& jsonOut)
30{
Ed Tanous18f8f602023-07-18 10:07:23 -070031 if (!isJsonContentType(
32 req.getHeaderValue(boost::beast::http::field::content_type)))
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010033 {
Ed Tanous62598e32023-07-17 17:06:25 -070034 BMCWEB_LOG_WARNING("Failed to parse content type on request");
Ed Tanous83328312024-05-09 15:48:09 -070035 if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
36 {
37 return JsonParseResult::BadContentType;
38 }
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010039 }
Ed Tanous33c6b582023-02-14 15:05:48 -080040 jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010041 if (jsonOut.is_discarded())
42 {
Ed Tanous62598e32023-07-17 17:06:25 -070043 BMCWEB_LOG_WARNING("Failed to parse json in request");
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010044 return JsonParseResult::BadJsonData;
45 }
46
47 return JsonParseResult::Success;
48}