blob: 3f83e49f73b8d4b4a003f37585aeb64136d960bc [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01003#pragma once
4
5#include "http/http_request.hpp"
Ed Tanouse4628c82024-12-16 10:57:04 -08006#include "http_utility.hpp"
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01007#include "logging.hpp"
Ed Tanous18f8f602023-07-18 10:07:23 -07008#include "str_utility.hpp"
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01009
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010010#include <nlohmann/json.hpp>
11
Ed Tanous18f8f602023-07-18 10:07:23 -070012#include <algorithm>
13#include <cctype>
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010014#include <string_view>
15
16enum class JsonParseResult
17{
18 BadContentType,
19 BadJsonData,
20 Success,
21};
22
Ed Tanous18f8f602023-07-18 10:07:23 -070023inline bool isJsonContentType(std::string_view contentType)
24{
Ed Tanouse4628c82024-12-16 10:57:04 -080025 return http_helpers::getContentType(contentType) ==
26 http_helpers::ContentType::JSON;
Ed Tanous18f8f602023-07-18 10:07:23 -070027}
28
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010029inline JsonParseResult parseRequestAsJson(const crow::Request& req,
30 nlohmann::json& jsonOut)
31{
Ed Tanous18f8f602023-07-18 10:07:23 -070032 if (!isJsonContentType(
33 req.getHeaderValue(boost::beast::http::field::content_type)))
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010034 {
Ed Tanous62598e32023-07-17 17:06:25 -070035 BMCWEB_LOG_WARNING("Failed to parse content type on request");
Ed Tanous83328312024-05-09 15:48:09 -070036 if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
37 {
38 return JsonParseResult::BadContentType;
39 }
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010040 }
Ed Tanous33c6b582023-02-14 15:05:48 -080041 jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010042 if (jsonOut.is_discarded())
43 {
Ed Tanous62598e32023-07-17 17:06:25 -070044 BMCWEB_LOG_WARNING("Failed to parse json in request");
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010045 return JsonParseResult::BadJsonData;
46 }
47
48 return JsonParseResult::Success;
49}