summaryrefslogtreecommitdiff
path: root/include/forward_unauthorized.hpp
blob: 2fc3ee45f554c339fb1122ab7abaff493b2b428a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once
#include <http_request.hpp>
#include <http_response.hpp>
#include <http_utility.hpp>

namespace forward_unauthorized
{

static bool hasWebuiRoute = false;

inline void sendUnauthorized(std::string_view url,
                             std::string_view xRequestedWith,
                             std::string_view accept, crow::Response& res)
{
    // If it's a browser connecting, don't send the HTTP authenticate
    // header, to avoid possible CSRF attacks with basic auth
    if (http_helpers::isContentTypeAllowed(
            accept, http_helpers::ContentType::HTML, false /*allowWildcard*/))
    {
        // If we have a webui installed, redirect to that login page
        if (hasWebuiRoute)
        {
            res.result(boost::beast::http::status::temporary_redirect);
            res.addHeader(boost::beast::http::field::location,
                          "/#/login?next=" + http_helpers::urlEncode(url));
            return;
        }
        // If we don't have a webui installed, just return an unauthorized
        // body
        res.result(boost::beast::http::status::unauthorized);
        res.body() = "Unauthorized";
        return;
    }

    res.result(boost::beast::http::status::unauthorized);

    // XHR requests from a browser will set the X-Requested-With header when
    // doing their requests, even though they might not be requesting html.
    if (!xRequestedWith.empty())
    {
        return;
    }
    // if basic auth is disabled, don't propose it.
    if (!persistent_data::SessionStore::getInstance()
             .getAuthMethodsConfig()
             .basic)
    {
        return;
    }
    res.addHeader(boost::beast::http::field::www_authenticate, "Basic");
}
} // namespace forward_unauthorized