blob: 5b437b1695f636ba8cc57a41d92111970c9e50fb [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
John Edward Broadbent59b98b22021-07-13 15:36:32 -070017 if (http_helpers::requestPrefersHtml(accept))
Ed Tanousd4b6c662021-03-10 13:29:30 -080018 {
19 // If we have a webui installed, redirect to that login page
20 if (hasWebuiRoute)
21 {
22 res.result(boost::beast::http::status::temporary_redirect);
23 res.addHeader("Location",
John Edward Broadbent59b98b22021-07-13 15:36:32 -070024 "/#/login?next=" + http_helpers::urlEncode(url));
Ed Tanousd4b6c662021-03-10 13:29:30 -080025 }
26 else
27 {
28 // If we don't have a webui installed, just return a lame
29 // unauthorized body
30 res.result(boost::beast::http::status::unauthorized);
31 res.body() = "Unauthorized";
32 }
33 }
34 else
35 {
36 res.result(boost::beast::http::status::unauthorized);
Ed Tanousc127a0f2022-05-11 15:23:59 -070037
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())
Ed Tanousd4b6c662021-03-10 13:29:30 -080041 {
Ed Tanousc127a0f2022-05-11 15:23:59 -070042 // Only propose basic auth as an option if it's enabled.
43 if (persistent_data::SessionStore::getInstance()
44 .getAuthMethodsConfig()
45 .basic)
46 {
47 res.addHeader("WWW-Authenticate", "Basic");
48 }
Ed Tanousd4b6c662021-03-10 13:29:30 -080049 }
50 }
51}
52} // namespace forward_unauthorized