blob: f16d8903dad1588ac64a22c35c8ec63964a0d246 [file] [log] [blame]
Ed Tanous1aa0c2b2022-02-08 12:24:30 +01001#pragma once
2
3#include "http/http_request.hpp"
4#include "logging.hpp"
5
6#include <boost/algorithm/string/predicate.hpp>
7#include <nlohmann/json.hpp>
8
9#include <string_view>
10
11enum class JsonParseResult
12{
13 BadContentType,
14 BadJsonData,
15 Success,
16};
17
18inline JsonParseResult parseRequestAsJson(const crow::Request& req,
19 nlohmann::json& jsonOut)
20{
21 std::string_view contentType =
22 req.getHeaderValue(boost::beast::http::field::content_type);
23
24 if (!boost::iequals(contentType, "application/json") &&
25 !boost::iequals(contentType, "application/json; charset=utf-8"))
26 {
27 BMCWEB_LOG_WARNING << "Failed to parse content type on request";
28#ifndef BMCWEB_INSECURE_IGNORE_CONTENT_TYPE
29 return JsonParseResult::BadContentType;
30#endif
31 }
Ed Tanous33c6b582023-02-14 15:05:48 -080032 jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010033 if (jsonOut.is_discarded())
34 {
35 BMCWEB_LOG_WARNING << "Failed to parse json in request";
36 return JsonParseResult::BadJsonData;
37 }
38
39 return JsonParseResult::Success;
40}