blob: 3a92218ca7b6ee33dfe56fde658f707e73c3a382 [file] [log] [blame]
Ed Tanousf9273472017-02-28 16:05:13 -08001#include <unordered_map>
2
3#include <boost/algorithm/string/predicate.hpp>
4
5#include <token_authorization_middleware.hpp>
6
Ed Tanous99923322017-03-03 14:21:24 -08007namespace crow {
8std::string TokenAuthorizationMiddleware::context::get_cookie(const std::string& key) {
9 if (cookie_sessions.count(key)) return cookie_sessions[key];
10 return {};
11}
Ed Tanousf9273472017-02-28 16:05:13 -080012
Ed Tanous99923322017-03-03 14:21:24 -080013void TokenAuthorizationMiddleware::context::set_cookie(const std::string& key, const std::string& value) { cookies_to_push_to_client.emplace(key, value); }
Ed Tanousf9273472017-02-28 16:05:13 -080014
Ed Tanous99923322017-03-03 14:21:24 -080015void TokenAuthorizationMiddleware::before_handle(crow::request& req, response& res, context& ctx) {
Ed Tanous9b65f1f2017-03-07 15:17:13 -080016 return;
17
Ed Tanous99923322017-03-03 14:21:24 -080018 auto return_unauthorized = [&req, &res]() {
19 res.code = 401;
20 res.end();
21 };
Ed Tanous9b65f1f2017-03-07 15:17:13 -080022 if (req.url == "/" || boost::starts_with(req.url, "/static/")){
23 //TODO this is total hackery to allow the login page to work before the user
24 // is authenticated. Also, it will be quite slow for all pages.
25 // Ideally, this should be done in the url router handler, with tagged routes
26 // for the whitelist entries.
27 return;
28 }
29
30 //TODO this
Ed Tanous99923322017-03-03 14:21:24 -080031 if (req.url == "/login") {
32 }
33 // Check for an authorization header, reject if not present
34 if (req.headers.count("Authorization") != 1) {
35 return_unauthorized();
36 return;
37 }
Ed Tanous38bdb982017-03-03 14:19:33 -080038
Ed Tanous99923322017-03-03 14:21:24 -080039 std::string auth_header = req.get_header_value("Authorization");
40 // If the user is attempting any kind of auth other than token, reject
41 if (!boost::starts_with(auth_header, "Token ")) {
42 return_unauthorized();
43 return;
44 }
45}
Ed Tanousf9273472017-02-28 16:05:13 -080046
Ed Tanous99923322017-03-03 14:21:24 -080047void TokenAuthorizationMiddleware::after_handle(request& /*req*/, response& res, context& ctx) {
48 for (auto& cookie : ctx.cookies_to_push_to_client) {
49 res.add_header("Set-Cookie", cookie.first + "=" + cookie.second);
50 }
51}
Ed Tanousf9273472017-02-28 16:05:13 -080052}