summaryrefslogtreecommitdiff
path: root/battleNetApi/src/hearthstoneTokenBuilder.cpp
blob: 9509aa6ffbcfc0fe8fa0089cb2c7c0b446163384 (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
114
115
116
117
118
119
120
#include <algorithm>
#include <curl/curl.h>
#include <fstream>
#include <hearthstoneTokenBuilder.hpp>
#include <iostream>
#include <memory>

HearthstoneTokenBuilder::HearthstoneTokenBuilder(const std::span<std::string> &iJsonPaths) {
    _credentialJsonPaths.append_range(iJsonPaths);
}
HearthstoneTokenBuilder &HearthstoneTokenBuilder::buildToken() {
    std::ranges::find_if(_credentialJsonPaths,
                         [](const std::string &iCredentialJsonPath) { return true; });
    if (hasExpired()) {
        if (isUpdateSourceFileAllowed()) {
        }
        const std::pair<std::string, std::uint64_t> kTokenContent{getTokenWithApi()};
        writeTokenToLocalFile(kTokenContent);
    }
    // return getTokenFromLocalFile();
    if (aTokenContainer.empty()) {
        return std::nullopt;
    }
    Token aOutputToken{aTokenContainer.front()};
    aTokenContainer.pop();
    // mCurrentToken = std::make_unique<Token>(...);
    return *this;
}
std::shared_ptr<Token> HearthstoneTokenBuilder::getToken() { return mCurrentToken; }
HearthstoneTokenBuilder &HearthstoneTokenBuilder::allowUpdateSourceFile() {
    mUpdateSourceFile = true;
    return *this;
}
bool HearthstoneTokenBuilder::isUpdateSourceFileAllowed() const { return mUpdateSourceFile; }

const bool HearthstoneTokenBuilder::hasExpired(json iTokenJson) const {
    if (not iTokenJson.contains("Token") or not iTokenJson["Token"].contains("ExpirationTime") or
        not iTokenJson["Token"].contains("Content")) {
        return true;
    }
    if (iTokenJson["Token"]["Content"].dump().length() < kTOKEN_CONTENT_MIN_LENGTH) {
        return true;
    }
    const std::uint64_t kExpirationTime{iTokenJson["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())};
    return kCurrentTime >= kExpirationTime;
}

size_t HearthstoneTokenBuilder::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;
}

std::chrono::seconds HearthstoneTokenBuilder::getCurrentTime() const {
    return std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::utc_clock::now().time_since_epoch());
}

std::pair<std::string, std::uint64_t>
HearthstoneTokenBuilder::getTokenWithApi(const std::string &iAgentJsonFilePath) const {
    std::ifstream aAgentJsonFile{iAgentJsonFilePath};
    json aCredentials = json::parse(aAgentJsonFile);
    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 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("{}:{}", kAgentUsername, kAgentPassword).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\n";
            std::exit(EXIT_FAILURE);
        }
    }
    json aTokenJson = json::parse(aTokenInfo);
    return std::make_pair(aTokenJson["access_token"], aTokenJson["expires_in"]);
}

std::string HearthstoneTokenBuilder::getTokenFromLocalFile() const {
    std::ifstream aTokenFile{mFilePath};
    return json::parse(aTokenFile)["Token"]["Content"];
}

void HearthstoneTokenBuilder::writeTokenToLocalFile(
    const std::pair<std::string, std::uint64_t> &iToken) const {
    std::ifstream aTokenFileInput{mFilePath};
    json aCredentialsFile = json::parse(aTokenFileInput);
    aCredentialsFile["Token"]["Content"] = iToken.first;
    aCredentialsFile["Token"]["ExpirationTime"] =
        std::chrono::duration_cast<std::chrono::seconds>(getCurrentTime() +
                                                         std::chrono::seconds(iToken.second))
            .count();

    std::ofstream aTokenFileOutput{mFilePath};
    aTokenFileOutput << std::setw(4) << aCredentialsFile;
}