Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include "http/http_request.hpp" |
| 4 | #include "logging.hpp" |
Ed Tanous | 18f8f60 | 2023-07-18 10:07:23 -0700 | [diff] [blame] | 5 | #include "str_utility.hpp" |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 6 | |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 7 | #include <nlohmann/json.hpp> |
| 8 | |
Ed Tanous | 18f8f60 | 2023-07-18 10:07:23 -0700 | [diff] [blame] | 9 | #include <algorithm> |
| 10 | #include <cctype> |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 11 | #include <string_view> |
| 12 | |
| 13 | enum class JsonParseResult |
| 14 | { |
| 15 | BadContentType, |
| 16 | BadJsonData, |
| 17 | Success, |
| 18 | }; |
| 19 | |
Ed Tanous | 18f8f60 | 2023-07-18 10:07:23 -0700 | [diff] [blame] | 20 | inline bool isJsonContentType(std::string_view contentType) |
| 21 | { |
| 22 | return bmcweb::asciiIEquals(contentType, "application/json") || |
Ed Tanous | 1fccd0d | 2024-03-19 09:16:16 -0700 | [diff] [blame^] | 23 | bmcweb::asciiIEquals(contentType, |
| 24 | "application/json; charset=utf-8") || |
| 25 | bmcweb::asciiIEquals(contentType, "application/json;charset=utf-8"); |
Ed Tanous | 18f8f60 | 2023-07-18 10:07:23 -0700 | [diff] [blame] | 26 | } |
| 27 | |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 28 | inline JsonParseResult parseRequestAsJson(const crow::Request& req, |
| 29 | nlohmann::json& jsonOut) |
| 30 | { |
Ed Tanous | 18f8f60 | 2023-07-18 10:07:23 -0700 | [diff] [blame] | 31 | if (!isJsonContentType( |
| 32 | req.getHeaderValue(boost::beast::http::field::content_type))) |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 33 | { |
Ed Tanous | 62598e3 | 2023-07-17 17:06:25 -0700 | [diff] [blame] | 34 | BMCWEB_LOG_WARNING("Failed to parse content type on request"); |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 35 | #ifndef BMCWEB_INSECURE_IGNORE_CONTENT_TYPE |
| 36 | return JsonParseResult::BadContentType; |
| 37 | #endif |
| 38 | } |
Ed Tanous | 33c6b58 | 2023-02-14 15:05:48 -0800 | [diff] [blame] | 39 | jsonOut = nlohmann::json::parse(req.body(), nullptr, false); |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 40 | if (jsonOut.is_discarded()) |
| 41 | { |
Ed Tanous | 62598e3 | 2023-07-17 17:06:25 -0700 | [diff] [blame] | 42 | BMCWEB_LOG_WARNING("Failed to parse json in request"); |
Ed Tanous | 1aa0c2b | 2022-02-08 12:24:30 +0100 | [diff] [blame] | 43 | return JsonParseResult::BadJsonData; |
| 44 | } |
| 45 | |
| 46 | return JsonParseResult::Success; |
| 47 | } |