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