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 | { |
| 24 | if (req.url == "/login"){ |
| 25 | return; |
| 26 | } |
| 27 | |
| 28 | // Check for an authorization header, reject if not present |
| 29 | if (req.headers.count("Authorization") != 1) { |
| 30 | res.code = 400; |
| 31 | res.end(); |
| 32 | return; |
| 33 | } |
| 34 | std::string auth_header = req.get_header_value("Authorization"); |
| 35 | // If the user is attempting any kind of auth other than token, reject |
| 36 | if (!boost::starts_with(auth_header, "Token ")) { |
| 37 | res.code = 400; |
| 38 | res.end(); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | void TokenAuthorizationMiddleware::after_handle(request& /*req*/, response& res, context& ctx) |
| 43 | { |
| 44 | for (auto& cookie : ctx.cookies_to_push_to_client) { |
| 45 | res.add_header("Set-Cookie", cookie.first + "=" + cookie.second); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | } |