blob: b129402018cddeab7230ccb608789c668f9b66a7 [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
Ed Tanousd7857202025-01-28 15:32:26 -08005#include "bmcweb_config.h"
6
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01007#include "http/http_request.hpp"
Ed Tanouse4628c82024-12-16 10:57:04 -08008#include "http_utility.hpp"
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01009#include "logging.hpp"
10
Ed Tanousd7857202025-01-28 15:32:26 -080011#include <boost/beast/http/field.hpp>
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010012#include <nlohmann/json.hpp>
13
Ed Tanous18f8f602023-07-18 10:07:23 -070014#include <cctype>
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010015#include <string_view>
16
17enum class JsonParseResult
18{
19 BadContentType,
20 BadJsonData,
21 Success,
22};
23
Ed Tanous18f8f602023-07-18 10:07:23 -070024inline bool isJsonContentType(std::string_view contentType)
25{
Ed Tanouse4628c82024-12-16 10:57:04 -080026 return http_helpers::getContentType(contentType) ==
27 http_helpers::ContentType::JSON;
Ed Tanous18f8f602023-07-18 10:07:23 -070028}
29
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010030inline JsonParseResult parseRequestAsJson(const crow::Request& req,
31 nlohmann::json& jsonOut)
32{
Ed Tanous18f8f602023-07-18 10:07:23 -070033 if (!isJsonContentType(
34 req.getHeaderValue(boost::beast::http::field::content_type)))
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010035 {
Ed Tanous62598e32023-07-17 17:06:25 -070036 BMCWEB_LOG_WARNING("Failed to parse content type on request");
Ed Tanous83328312024-05-09 15:48:09 -070037 if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
38 {
39 return JsonParseResult::BadContentType;
40 }
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010041 }
Ed Tanous33c6b582023-02-14 15:05:48 -080042 jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010043 if (jsonOut.is_discarded())
44 {
Ed Tanous62598e32023-07-17 17:06:25 -070045 BMCWEB_LOG_WARNING("Failed to parse json in request");
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010046 return JsonParseResult::BadJsonData;
47 }
48
49 return JsonParseResult::Success;
50}