Line data Source code
1 : #include "BasicRequestAuthentication.h"
2 : #include <string>
3 : #include <cstdlib>
4 : #include "RequestAuthenticationBase.h"
5 :
6 : namespace Odb::Lib::App
7 : {
8 0 : BasicRequestAuthentication::BasicRequestAuthentication(bool disableAuthentication)
9 0 : : RequestAuthenticationBase(disableAuthentication)
10 : {
11 0 : }
12 :
13 0 : crow::response BasicRequestAuthentication::AuthenticateRequest(const crow::request& req)
14 : {
15 0 : auto resp = RequestAuthenticationBase::AuthenticateRequest(req);
16 0 : if (resp.code != crow::status::OK)
17 : {
18 0 : const auto& authHeader = req.get_header_value(AUTHORIZATION_HEADER_NAME);
19 0 : if (authHeader.empty()) return crow::response(crow::status::UNAUTHORIZED, "Unauthorized");
20 :
21 0 : auto authValue = authHeader.substr(6);
22 0 : if (authValue.empty()) return crow::response(crow::status::UNAUTHORIZED, "Unauthorized");
23 :
24 0 : auto authValueDecoded = crow::utility::base64decode(authValue, authValue.size());
25 0 : if (authValueDecoded.empty()) return crow::response(crow::status::UNAUTHORIZED, "Unauthorized");
26 :
27 0 : auto seperatorPos = authValueDecoded.find(':');
28 0 : if (seperatorPos == std::string::npos) return crow::response(crow::status::UNAUTHORIZED, "Unauthorized");
29 :
30 0 : auto username = authValueDecoded.substr(0, seperatorPos);
31 0 : auto password = authValueDecoded.substr(seperatorPos + 1);
32 :
33 0 : resp = VerifyCredentials(username, password);
34 0 : }
35 0 : return resp;
36 0 : }
37 :
38 0 : crow::response BasicRequestAuthentication::VerifyCredentials(const std::string& username, const std::string& password)
39 : {
40 : // 500 - Internal Server Error
41 0 : auto szValidUsername = std::getenv(USERNAME_ENV_NAME);
42 0 : std::string validUsername;
43 0 : if (szValidUsername != nullptr)
44 : {
45 0 : validUsername = szValidUsername;
46 : }
47 :
48 0 : if (validUsername.empty()) //return crow::response(500, "Failed retrieving credentials");
49 : {
50 : // default username if none supplied in environment
51 0 : validUsername = "odb";
52 : }
53 :
54 0 : auto szValidPassword = std::getenv(PASSWORD_ENV_NAME);
55 0 : std::string validPassword;
56 0 : if (szValidPassword != nullptr)
57 : {
58 0 : validPassword = szValidPassword;
59 : }
60 :
61 0 : if (validPassword.empty()) //return crow::response(500, "Failed retrieving credentials");
62 : {
63 : // default password if none supplied in environment
64 0 : validPassword = "plusplus";
65 : }
66 :
67 : // 403 - Forbidden
68 0 : if (username != validUsername ||
69 0 : password != validPassword)
70 : {
71 0 : return crow::response(crow::status::FORBIDDEN, "Invalid username or password");
72 : }
73 :
74 : // 200 Authorized!
75 0 : return crow::response(crow::status::OK, "Authorized");
76 0 : }
77 : }
|