blob: 2fc3ee45f554c339fb1122ab7abaff493b2b428a [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 Tanous4f48d5f2021-06-21 08:27:45 -07009static bool hasWebuiRoute = false;
Ed Tanousd4b6c662021-03-10 13:29:30 -080010
Ed Tanousc127a0f2022-05-11 15:23:59 -070011inline void sendUnauthorized(std::string_view url,
12 std::string_view xRequestedWith,
John Edward Broadbent59b98b22021-07-13 15:36:32 -070013 std::string_view accept, crow::Response& res)
Ed Tanousd4b6c662021-03-10 13:29:30 -080014{
15 // If it's a browser connecting, don't send the HTTP authenticate
16 // header, to avoid possible CSRF attacks with basic auth
Ed Tanous4a0e1a02022-09-21 15:28:04 -070017 if (http_helpers::isContentTypeAllowed(
18 accept, http_helpers::ContentType::HTML, false /*allowWildcard*/))
Ed Tanousd4b6c662021-03-10 13:29:30 -080019 {
20 // If we have a webui installed, redirect to that login page
21 if (hasWebuiRoute)
22 {
23 res.result(boost::beast::http::status::temporary_redirect);
Ed Tanousd9f6c622022-03-17 09:12:17 -070024 res.addHeader(boost::beast::http::field::location,
John Edward Broadbent59b98b22021-07-13 15:36:32 -070025 "/#/login?next=" + http_helpers::urlEncode(url));
Ed Tanous347d1a12022-06-22 15:49:37 -070026 return;
Ed Tanousd4b6c662021-03-10 13:29:30 -080027 }
Ed Tanous347d1a12022-06-22 15:49:37 -070028 // If we don't have a webui installed, just return an unauthorized
29 // body
Ed Tanousd4b6c662021-03-10 13:29:30 -080030 res.result(boost::beast::http::status::unauthorized);
Ed Tanous347d1a12022-06-22 15:49:37 -070031 res.body() = "Unauthorized";
32 return;
Ed Tanousd4b6c662021-03-10 13:29:30 -080033 }
Ed Tanous347d1a12022-06-22 15:49:37 -070034
35 res.result(boost::beast::http::status::unauthorized);
36
37 // XHR requests from a browser will set the X-Requested-With header when
38 // doing their requests, even though they might not be requesting html.
39 if (!xRequestedWith.empty())
40 {
41 return;
42 }
43 // if basic auth is disabled, don't propose it.
44 if (!persistent_data::SessionStore::getInstance()
45 .getAuthMethodsConfig()
46 .basic)
47 {
48 return;
49 }
Ed Tanousd9f6c622022-03-17 09:12:17 -070050 res.addHeader(boost::beast::http::field::www_authenticate, "Basic");
Ed Tanousd4b6c662021-03-10 13:29:30 -080051}
52} // namespace forward_unauthorized