Ed Tanous | ed5f895 | 2023-06-22 14:06:22 -0700 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include "authentication.hpp" |
| 4 | #include "http_request.hpp" |
| 5 | #include "http_response.hpp" |
| 6 | #include "http_utility.hpp" |
| 7 | #include "json_html_serializer.hpp" |
| 8 | #include "logging.hpp" |
| 9 | #include "security_headers.hpp" |
| 10 | #include "utils/hex_utils.hpp" |
| 11 | |
| 12 | #include <boost/beast/http/message.hpp> |
| 13 | #include <boost/beast/http/string_body.hpp> |
| 14 | #include <nlohmann/json.hpp> |
| 15 | |
| 16 | #include <array> |
| 17 | |
| 18 | namespace crow |
| 19 | { |
| 20 | |
| 21 | inline void completeResponseFields(const Request& req, Response& res) |
| 22 | { |
Ed Tanous | 62598e3 | 2023-07-17 17:06:25 -0700 | [diff] [blame] | 23 | BMCWEB_LOG_INFO("Response: {} {}", req.url().encoded_path(), |
| 24 | res.resultInt()); |
Ed Tanous | ed5f895 | 2023-06-22 14:06:22 -0700 | [diff] [blame] | 25 | addSecurityHeaders(req, res); |
| 26 | |
| 27 | authentication::cleanupTempSession(req); |
| 28 | |
| 29 | res.setHashAndHandleNotModified(); |
| 30 | |
| 31 | if (res.body().empty() && res.jsonValue.is_structured()) |
| 32 | { |
| 33 | using http_helpers::ContentType; |
| 34 | std::array<ContentType, 3> allowed{ContentType::CBOR, ContentType::JSON, |
| 35 | ContentType::HTML}; |
| 36 | ContentType prefered = |
| 37 | getPreferedContentType(req.getHeaderValue("Accept"), allowed); |
| 38 | |
| 39 | if (prefered == ContentType::HTML) |
| 40 | { |
| 41 | json_html_util::prettyPrintJson(res); |
| 42 | } |
| 43 | else if (prefered == ContentType::CBOR) |
| 44 | { |
| 45 | res.addHeader(boost::beast::http::field::content_type, |
| 46 | "application/cbor"); |
| 47 | nlohmann::json::to_cbor(res.jsonValue, res.body()); |
| 48 | } |
| 49 | else |
| 50 | { |
| 51 | // Technically prefered could also be NoMatch here, but we'd |
| 52 | // like to default to something rather than return 400 for |
| 53 | // backward compatibility. |
| 54 | res.addHeader(boost::beast::http::field::content_type, |
| 55 | "application/json"); |
| 56 | res.body() = res.jsonValue.dump( |
| 57 | 2, ' ', true, nlohmann::json::error_handler_t::replace); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } // namespace crow |