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