blob: 9a19baf452c74da9e88cfcf5720da7510f405c22 [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") ||
23 bmcweb::asciiIEquals(contentType, "application/json; charset=utf-8");
24}
25
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010026inline JsonParseResult parseRequestAsJson(const crow::Request& req,
27 nlohmann::json& jsonOut)
28{
Ed Tanous18f8f602023-07-18 10:07:23 -070029 if (!isJsonContentType(
30 req.getHeaderValue(boost::beast::http::field::content_type)))
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010031 {
Ed Tanous62598e32023-07-17 17:06:25 -070032 BMCWEB_LOG_WARNING("Failed to parse content type on request");
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010033#ifndef BMCWEB_INSECURE_IGNORE_CONTENT_TYPE
34 return JsonParseResult::BadContentType;
35#endif
36 }
Ed Tanous33c6b582023-02-14 15:05:48 -080037 jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010038 if (jsonOut.is_discarded())
39 {
Ed Tanous62598e32023-07-17 17:06:25 -070040 BMCWEB_LOG_WARNING("Failed to parse json in request");
Ed Tanous1aa0c2b2022-02-08 12:24:30 +010041 return JsonParseResult::BadJsonData;
42 }
43
44 return JsonParseResult::Success;
45}