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