blob: cf813537edbb0625b9409388761f02f7c394db3e [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 Tanous1aa0c2b2022-02-08 12:24:30 +010035#ifndef BMCWEB_INSECURE_IGNORE_CONTENT_TYPE
36 return JsonParseResult::BadContentType;
37#endif
38 }
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}