Ed Tanous | f927347 | 2017-02-28 16:05:13 -0800 | [diff] [blame] | 1 | #include <unordered_map> |
| 2 | |
| 3 | #include <boost/algorithm/string/predicate.hpp> |
| 4 | |
| 5 | #include <token_authorization_middleware.hpp> |
| 6 | |
| 7 | namespace crow |
| 8 | { |
| 9 | std::string TokenAuthorizationMiddleware::context::get_cookie(const std::string& key) |
| 10 | { |
| 11 | if (cookie_sessions.count(key)) |
| 12 | return cookie_sessions[key]; |
| 13 | return {}; |
| 14 | } |
| 15 | |
| 16 | void TokenAuthorizationMiddleware::context::set_cookie(const std::string& key, const std::string& value) |
| 17 | { |
| 18 | cookies_to_push_to_client.emplace(key, value); |
| 19 | } |
| 20 | |
| 21 | |
| 22 | void TokenAuthorizationMiddleware::before_handle(crow::request& req, response& res, context& ctx) |
| 23 | { |
Ed Tanous | 38bdb98 | 2017-03-03 14:19:33 -0800 | [diff] [blame^] | 24 | auto return_unauthorized = [&req, &res](){ |
| 25 | res.code = 401; |
| 26 | res.end(); |
| 27 | }; |
Ed Tanous | f927347 | 2017-02-28 16:05:13 -0800 | [diff] [blame] | 28 | if (req.url == "/login"){ |
Ed Tanous | 38bdb98 | 2017-03-03 14:19:33 -0800 | [diff] [blame^] | 29 | |
| 30 | } |
| 31 | // Check for an authorization header, reject if not present |
| 32 | if (req.headers.count("Authorization") != 1) { |
| 33 | return_unauthorized(); |
Ed Tanous | f927347 | 2017-02-28 16:05:13 -0800 | [diff] [blame] | 34 | return; |
| 35 | } |
| 36 | |
Ed Tanous | f927347 | 2017-02-28 16:05:13 -0800 | [diff] [blame] | 37 | std::string auth_header = req.get_header_value("Authorization"); |
| 38 | // If the user is attempting any kind of auth other than token, reject |
| 39 | if (!boost::starts_with(auth_header, "Token ")) { |
Ed Tanous | 38bdb98 | 2017-03-03 14:19:33 -0800 | [diff] [blame^] | 40 | return_unauthorized(); |
| 41 | return; |
Ed Tanous | f927347 | 2017-02-28 16:05:13 -0800 | [diff] [blame] | 42 | } |
| 43 | } |
| 44 | |
| 45 | void TokenAuthorizationMiddleware::after_handle(request& /*req*/, response& res, context& ctx) |
| 46 | { |
| 47 | for (auto& cookie : ctx.cookies_to_push_to_client) { |
| 48 | res.add_header("Set-Cookie", cookie.first + "=" + cookie.second); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | } |