diff options
| author | Aotrix <[email protected]> | 2026-01-25 01:52:23 +0100 |
|---|---|---|
| committer | Aotrix <[email protected]> | 2026-01-25 01:52:23 +0100 |
| commit | 15de61ad9fead748287537cdcc11fc82683a09ef (patch) | |
| tree | b048c1b5c3efa493d852fb32e8d1beb6018e09e7 /battleNetApi/src/token.cpp | |
| parent | b93862f9f1fab10a569c9706335b6133fe44d996 (diff) | |
Added JSON support for token generation
Diffstat (limited to 'battleNetApi/src/token.cpp')
| -rw-r--r-- | battleNetApi/src/token.cpp | 92 |
1 files changed, 39 insertions, 53 deletions
diff --git a/battleNetApi/src/token.cpp b/battleNetApi/src/token.cpp index fdfb182..de0276a 100644 --- a/battleNetApi/src/token.cpp +++ b/battleNetApi/src/token.cpp @@ -1,37 +1,29 @@ #include "token.hpp" -#include <charconv> #include <chrono> #include <curl/curl.h> #include <format> #include <fstream> #include <iostream> -#include <regex> -#include <system_error> +#include <nlohmann/json.hpp> -Token::Token(const std::string &iTokenFilePath, const std::string &iUsername, const std::string &iPassword) - : mFilePath{iTokenFilePath}, mUsername{iUsername}, mPassword{iPassword}, mToken{getValidToken()} {} +using json = nlohmann::json; -std::string Token::toString() const { return mToken; } +Token::Token(const std::string &iTokenFilePath) : mFilePath{iTokenFilePath}, mToken{generateToken()} {} + +std::string Token::text() const { return mToken; } const bool Token::hasTokenExpired() const { std::ifstream aTokenFile{mFilePath}; - std::string aLine; - std::getline(aTokenFile, aLine); - if (aLine.empty()) { - return true; - } - const std::string kTimeLimitText{aLine.substr(aLine.find(" ") + 1)}; - long int aTimeLimit; - const auto kConversionStatus{ - std::from_chars(kTimeLimitText.data(), kTimeLimitText.data() + kTimeLimitText.size(), aTimeLimit)}; - if (kConversionStatus.ec != std::errc{}) { - std::cerr << "Conversion of token timestamp failed.\n"; - return true; + json aCredentialsFile = json::parse(aTokenFile); + if (not aCredentialsFile.contains("Token") or not aCredentialsFile["Token"].contains("ExpirationTime") or + not aCredentialsFile["Token"].contains("Content") or aCredentialsFile["Token"]["Content"].empty()) { + return false; } - const bool kTokenExpired{ - std::chrono::duration_cast<std::chrono::seconds>(std::chrono::utc_clock::now().time_since_epoch()).count() >= - aTimeLimit}; - if (kTokenExpired) { + const std::uint64_t kExpirationTime{aCredentialsFile["Token"]["ExpirationTime"]}; + const std::uint64_t kCurrentTime{static_cast<std::uint64_t>( + std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now().time_since_epoch()) + .count())}; + if (kCurrentTime >= kExpirationTime) { return true; } return false; @@ -39,42 +31,47 @@ const bool Token::hasTokenExpired() const { std::string Token::getTokenFromLocalFile() const { std::ifstream aTokenFile{mFilePath}; - std::string aLine; - std::getline(aTokenFile, aLine); - return aLine.substr(0, aLine.find(" ")); + return json::parse(aTokenFile)["Token"]["Content"]; } -std::string Token::getValidToken() { +std::string Token::generateToken() { if (hasTokenExpired()) { - return writeNewTokenToLocalFile(); + const std::string kTokenContent{getTokenWithApi()}; + writeNewTokenToLocalFile(kTokenContent); } return getTokenFromLocalFile(); } -std::string Token::writeNewTokenToLocalFile() const { - std::fstream aTokenFile{mFilePath}; - std::string aLine; - std::getline(aTokenFile, aLine); - const std::string kToken{getTokenWithApi()}; - if (not kToken.empty()) { - std::chrono::seconds aExpiresAt{getCurrentTime() + std::chrono::hours(24)}; - aTokenFile << kToken << " " << aExpiresAt.count() << '\n'; - return kToken; - } - std::cerr << "Error: no valid token can be generated.\n"; - return ""; +void Token::writeNewTokenToLocalFile(const std::string &iTokenContent) const { + std::ifstream aTokenFileInput{mFilePath}; + json aCredentialsFile = json::parse(aTokenFileInput); + aCredentialsFile["Token"]["Content"] = iTokenContent; + aCredentialsFile["Token"]["ExpirationTime"] = + std::chrono::duration_cast<std::chrono::seconds>(getCurrentTime() + std::chrono::hours(24)).count(); + + std::ofstream aTokenFileOutput{mFilePath}; + aTokenFileOutput << std::setw(4) << aCredentialsFile; } std::string Token::getTokenWithApi() const { + std::ifstream aCredentialsFile{mFilePath}; + json aCredentials = json::parse(aCredentialsFile); + if (not aCredentials.contains("Agent") or not aCredentials["Agent"].contains("Username") or + not aCredentials["Agent"].contains("Password")) { + std::cerr << "Please define Agent/Username and Agent/Password in the JSON credentials file\n"; + std::exit(EXIT_FAILURE); + } + const std::string kAgentUsername{aCredentials["Agent"]["Username"]}; + const std::string kAgentPassword{aCredentials["Agent"]["Password"]}; CURL *aCurl{curl_easy_init()}; std::string aTokenInfo; - if (aCurl) { + if (aCurl and not kAgentUsername.empty() and not kAgentPassword.empty()) { curl_easy_setopt(aCurl, CURLOPT_URL, "https://oauth.battle.net/token"); curl_easy_setopt(aCurl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(aCurl, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(aCurl, CURLOPT_WRITEFUNCTION, curlCallbackStringOutput); curl_easy_setopt(aCurl, CURLOPT_WRITEDATA, &aTokenInfo); - curl_easy_setopt(aCurl, CURLOPT_USERPWD, std::format("{}:{}", mUsername, mPassword).data()); + curl_easy_setopt(aCurl, CURLOPT_USERPWD, std::format("{}:{}", kAgentUsername, kAgentPassword).data()); curl_easy_setopt(aCurl, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); CURLcode result_code{curl_easy_perform(aCurl)}; curl_easy_cleanup(aCurl); @@ -83,24 +80,13 @@ std::string Token::getTokenWithApi() const { std::exit(EXIT_FAILURE); } } - - return extractTokenWithRegex(aTokenInfo, "\"access_token\":\"(\\w+)\""); + return json::parse(aTokenInfo)["access_token"]; } std::chrono::seconds Token::getCurrentTime() const { return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::utc_clock::now().time_since_epoch()); } -std::string Token::extractTokenWithRegex(const std::string &iText, const std::string &iRegex) const { - const std::regex kRegex{iRegex}; - std::smatch aMatches; - if (std::regex_search(iText, aMatches, kRegex)) { - return aMatches[1].str(); - } - std::cerr << std::format("Unable to retrieve token with regex '{}'", iRegex); - return ""; -} - size_t Token::curlCallbackStringOutput(void *iPtr, size_t iSize, size_t iNmemb, std::string *iUserData) { size_t newLength{iSize * iNmemb}; try { |
