1 // SPDX-License-Identifier: Apache-2.0 2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors 3 #pragma once 4 5 #include "http/http_request.hpp" 6 #include "http_utility.hpp" 7 #include "logging.hpp" 8 #include "str_utility.hpp" 9 10 #include <nlohmann/json.hpp> 11 12 #include <algorithm> 13 #include <cctype> 14 #include <string_view> 15 16 enum class JsonParseResult 17 { 18 BadContentType, 19 BadJsonData, 20 Success, 21 }; 22 23 inline bool isJsonContentType(std::string_view contentType) 24 { 25 return http_helpers::getContentType(contentType) == 26 http_helpers::ContentType::JSON; 27 } 28 29 inline JsonParseResult parseRequestAsJson(const crow::Request& req, 30 nlohmann::json& jsonOut) 31 { 32 if (!isJsonContentType( 33 req.getHeaderValue(boost::beast::http::field::content_type))) 34 { 35 BMCWEB_LOG_WARNING("Failed to parse content type on request"); 36 if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE) 37 { 38 return JsonParseResult::BadContentType; 39 } 40 } 41 jsonOut = nlohmann::json::parse(req.body(), nullptr, false); 42 if (jsonOut.is_discarded()) 43 { 44 BMCWEB_LOG_WARNING("Failed to parse json in request"); 45 return JsonParseResult::BadJsonData; 46 } 47 48 return JsonParseResult::Success; 49 } 50