blob: b39537c2b756b0820d32203449709a00a355a38d [file] [log] [blame]
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01001#pragma once
2
3#include "http/http_request.hpp"
Ed Tanouse4628c82024-12-16 10:57:04 -08004#include "http_utility.hpp"
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01005#include "logging.hpp"
Ed Tanous18f8f602023-07-18 10:07:23 -07006#include "str_utility.hpp"
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01007
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01008#include <nlohmann/json.hpp>
9
Ed Tanous18f8f602023-07-18 10:07:23 -070010#include <algorithm>
11#include <cctype>
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010012#include <string_view>
13
14enum class JsonParseResult
15{
16 BadContentType,
17 BadJsonData,
18 Success,
19};
20
Ed Tanous18f8f602023-07-18 10:07:23 -070021inline bool isJsonContentType(std::string_view contentType)
22{
Ed Tanouse4628c82024-12-16 10:57:04 -080023 return http_helpers::getContentType(contentType) ==
24 http_helpers::ContentType::JSON;
Ed Tanous18f8f602023-07-18 10:07:23 -070025}
26
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010027inline JsonParseResult parseRequestAsJson(const crow::Request& req,
28 nlohmann::json& jsonOut)
29{
Ed Tanous18f8f602023-07-18 10:07:23 -070030 if (!isJsonContentType(
31 req.getHeaderValue(boost::beast::http::field::content_type)))
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010032 {
Ed Tanous62598e32023-07-17 17:06:25 -070033 BMCWEB_LOG_WARNING("Failed to parse content type on request");
Ed Tanous83328312024-05-09 15:48:09 -070034 if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
35 {
36 return JsonParseResult::BadContentType;
37 }
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010038 }
Ed Tanous33c6b582023-02-14 15:05:48 -080039 jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010040 if (jsonOut.is_discarded())
41 {
Ed Tanous62598e32023-07-17 17:06:25 -070042 BMCWEB_LOG_WARNING("Failed to parse json in request");
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010043 return JsonParseResult::BadJsonData;
44 }
45
46 return JsonParseResult::Success;
47}