summaryrefslogtreecommitdiff
path: root/battleNetApi/src/token.cpp
blob: fdfb182feac3e7842576098fdfbb33979427312e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "token.hpp"
#include <charconv>
#include <chrono>
#include <curl/curl.h>
#include <format>
#include <fstream>
#include <iostream>
#include <regex>
#include <system_error>

Token::Token(const std::string &iTokenFilePath, const std::string &iUsername, const std::string &iPassword)
    : mFilePath{iTokenFilePath}, mUsername{iUsername}, mPassword{iPassword}, mToken{getValidToken()} {}

std::string Token::toString() 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;
    }
    const bool kTokenExpired{
        std::chrono::duration_cast<std::chrono::seconds>(std::chrono::utc_clock::now().time_since_epoch()).count() >=
        aTimeLimit};
    if (kTokenExpired) {
        return true;
    }
    return false;
}

std::string Token::getTokenFromLocalFile() const {
    std::ifstream aTokenFile{mFilePath};
    std::string aLine;
    std::getline(aTokenFile, aLine);
    return aLine.substr(0, aLine.find(" "));
}

std::string Token::getValidToken() {
    if (hasTokenExpired()) {
        return writeNewTokenToLocalFile();
    }
    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 "";
}

std::string Token::getTokenWithApi() const {
    CURL *aCurl{curl_easy_init()};
    std::string aTokenInfo;
    if (aCurl) {
        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_POSTFIELDS, "grant_type=client_credentials");
        CURLcode result_code{curl_easy_perform(aCurl)};
        curl_easy_cleanup(aCurl);
        if (result_code != CURLE_OK) {
            std::cerr << "ERROR: token request failed" << std::endl;
            std::exit(EXIT_FAILURE);
        }
    }

    return extractTokenWithRegex(aTokenInfo, "\"access_token\":\"(\\w+)\"");
}

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 {
        iUserData->append(static_cast<char *>(iPtr), newLength);
    } catch (std::bad_alloc &e) {
        // handle memory problem
        return 0;
    }
    return newLength;
}