summaryrefslogtreecommitdiff
path: root/http/parsing.hpp
blob: d59621104c7ef5714101536991727b5ce5be6e5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once

#include "http/http_request.hpp"
#include "logging.hpp"
#include "str_utility.hpp"

#include <nlohmann/json.hpp>

#include <algorithm>
#include <cctype>
#include <string_view>

enum class JsonParseResult
{
    BadContentType,
    BadJsonData,
    Success,
};

inline bool isJsonContentType(std::string_view contentType)
{
    return bmcweb::asciiIEquals(contentType, "application/json") ||
           bmcweb::asciiIEquals(contentType,
                                "application/json; charset=utf-8") ||
           bmcweb::asciiIEquals(contentType, "application/json;charset=utf-8");
}

inline JsonParseResult parseRequestAsJson(const crow::Request& req,
                                          nlohmann::json& jsonOut)
{
    if (!isJsonContentType(
            req.getHeaderValue(boost::beast::http::field::content_type)))
    {
        BMCWEB_LOG_WARNING("Failed to parse content type on request");
        if constexpr (!BMCWEB_INSECURE_IGNORE_CONTENT_TYPE)
        {
            return JsonParseResult::BadContentType;
        }
    }
    jsonOut = nlohmann::json::parse(req.body(), nullptr, false);
    if (jsonOut.is_discarded())
    {
        BMCWEB_LOG_WARNING("Failed to parse json in request");
        return JsonParseResult::BadJsonData;
    }

    return JsonParseResult::Success;
}