blob: 850a0b79b0435bc545ae89d3df1663e65acbb640 [file] [log] [blame]
Ed Tanousd4b6c662021-03-10 13:29:30 -08001#pragma once
2#include <http_request.hpp>
3#include <http_response.hpp>
4#include <http_utility.hpp>
5
6namespace forward_unauthorized
7{
8
Ed Tanouscf9e4172022-12-21 09:30:16 -08009// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous4f48d5f2021-06-21 08:27:45 -070010static bool hasWebuiRoute = false;
Ed Tanousd4b6c662021-03-10 13:29:30 -080011
Ed Tanousc127a0f2022-05-11 15:23:59 -070012inline void sendUnauthorized(std::string_view url,
13 std::string_view xRequestedWith,
John Edward Broadbent59b98b22021-07-13 15:36:32 -070014 std::string_view accept, crow::Response& res)
Ed Tanousd4b6c662021-03-10 13:29:30 -080015{
16 // If it's a browser connecting, don't send the HTTP authenticate
17 // header, to avoid possible CSRF attacks with basic auth
Ed Tanous4a0e1a02022-09-21 15:28:04 -070018 if (http_helpers::isContentTypeAllowed(
19 accept, http_helpers::ContentType::HTML, false /*allowWildcard*/))
Ed Tanousd4b6c662021-03-10 13:29:30 -080020 {
21 // If we have a webui installed, redirect to that login page
22 if (hasWebuiRoute)
23 {
24 res.result(boost::beast::http::status::temporary_redirect);
Ed Tanousd9f6c622022-03-17 09:12:17 -070025 res.addHeader(boost::beast::http::field::location,
John Edward Broadbent59b98b22021-07-13 15:36:32 -070026 "/#/login?next=" + http_helpers::urlEncode(url));
Ed Tanous347d1a12022-06-22 15:49:37 -070027 return;
Ed Tanousd4b6c662021-03-10 13:29:30 -080028 }
Ed Tanous347d1a12022-06-22 15:49:37 -070029 // If we don't have a webui installed, just return an unauthorized
30 // body
Ed Tanousd4b6c662021-03-10 13:29:30 -080031 res.result(boost::beast::http::status::unauthorized);
Ed Tanous347d1a12022-06-22 15:49:37 -070032 res.body() = "Unauthorized";
33 return;
Ed Tanousd4b6c662021-03-10 13:29:30 -080034 }
Ed Tanous347d1a12022-06-22 15:49:37 -070035
36 res.result(boost::beast::http::status::unauthorized);
37
38 // XHR requests from a browser will set the X-Requested-With header when
39 // doing their requests, even though they might not be requesting html.
40 if (!xRequestedWith.empty())
41 {
42 return;
43 }
44 // if basic auth is disabled, don't propose it.
45 if (!persistent_data::SessionStore::getInstance()
46 .getAuthMethodsConfig()
47 .basic)
48 {
49 return;
50 }
Ed Tanousd9f6c622022-03-17 09:12:17 -070051 res.addHeader(boost::beast::http::field::www_authenticate, "Basic");
Ed Tanousd4b6c662021-03-10 13:29:30 -080052}
53} // namespace forward_unauthorized