1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 #include "http_response.hpp"
5 #include "http_utility.hpp"
6 #include "sessions.hpp"
7
8 #include <boost/beast/http/field.hpp>
9 #include <boost/beast/http/status.hpp>
10 #include <boost/url/format.hpp>
11 #include <boost/url/url.hpp>
12
13 #include <string_view>
14
15 namespace forward_unauthorized
16 {
17
18 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
19 static bool hasWebuiRoute = false;
20
sendUnauthorized(std::string_view url,std::string_view xRequestedWith,std::string_view accept,crow::Response & res)21 inline void sendUnauthorized(std::string_view url,
22 std::string_view xRequestedWith,
23 std::string_view accept, crow::Response& res)
24 {
25 // If it's a browser connecting, don't send the HTTP authenticate
26 // header, to avoid possible CSRF attacks with basic auth
27 if (http_helpers::isContentTypeAllowed(
28 accept, http_helpers::ContentType::HTML, false /*allowWildcard*/))
29 {
30 // If we have a webui installed, redirect to that login page
31 if (hasWebuiRoute)
32 {
33 boost::urls::url forward =
34 boost::urls::format("/?next={}#/login", url);
35 res.result(boost::beast::http::status::temporary_redirect);
36 res.addHeader(boost::beast::http::field::location,
37 forward.buffer());
38 return;
39 }
40 // If we don't have a webui installed, just return an unauthorized
41 // body
42 res.result(boost::beast::http::status::unauthorized);
43 res.write(
44 "No authentication provided, and no login UI present to forward to.");
45 return;
46 }
47
48 res.result(boost::beast::http::status::unauthorized);
49
50 // XHR requests from a browser will set the X-Requested-With header when
51 // doing their requests, even though they might not be requesting html.
52 if (!xRequestedWith.empty())
53 {
54 return;
55 }
56 // if basic auth is disabled, don't propose it.
57 if (!persistent_data::SessionStore::getInstance()
58 .getAuthMethodsConfig()
59 .basic)
60 {
61 return;
62 }
63 res.addHeader(boost::beast::http::field::www_authenticate, "Basic");
64 }
65 } // namespace forward_unauthorized
66