2024-04-23 02:27:08 +02:00
|
|
|
#include "TokenManager.hpp"
|
|
|
|
#include <uuid/uuid.h>
|
|
|
|
#include <algorithm>
|
|
|
|
|
2024-06-25 16:05:39 +02:00
|
|
|
CUUIDToken::CUUIDToken(const std::string& uuid_, std::any data_, std::chrono::steady_clock::duration expires) : data(data_), uuid(uuid_) {
|
|
|
|
expiresAt = std::chrono::steady_clock::now() + expires;
|
2024-04-23 02:27:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
std::string CUUIDToken::getUUID() {
|
|
|
|
return uuid;
|
|
|
|
}
|
|
|
|
|
2024-04-28 19:17:48 +02:00
|
|
|
std::string CTokenManager::getRandomUUID() {
|
2024-04-23 02:27:08 +02:00
|
|
|
std::string uuid;
|
|
|
|
do {
|
|
|
|
uuid_t uuid_;
|
|
|
|
uuid_generate_random(uuid_);
|
2024-04-23 02:40:03 +02:00
|
|
|
uuid = std::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", (uint16_t)uuid_[0], (uint16_t)uuid_[1],
|
|
|
|
(uint16_t)uuid_[2], (uint16_t)uuid_[3], (uint16_t)uuid_[4], (uint16_t)uuid_[5], (uint16_t)uuid_[6], (uint16_t)uuid_[7], (uint16_t)uuid_[8],
|
|
|
|
(uint16_t)uuid_[9], (uint16_t)uuid_[10], (uint16_t)uuid_[11], (uint16_t)uuid_[12], (uint16_t)uuid_[13], (uint16_t)uuid_[14], (uint16_t)uuid_[15]);
|
2024-04-23 02:27:08 +02:00
|
|
|
} while (m_mTokens.contains(uuid));
|
|
|
|
|
2024-04-28 19:17:48 +02:00
|
|
|
return uuid;
|
|
|
|
}
|
|
|
|
|
2024-06-25 16:05:39 +02:00
|
|
|
std::string CTokenManager::registerNewToken(std::any data, std::chrono::steady_clock::duration expires) {
|
2024-04-28 19:17:48 +02:00
|
|
|
std::string uuid = getRandomUUID();
|
|
|
|
|
2024-05-05 18:16:00 +02:00
|
|
|
m_mTokens[uuid] = makeShared<CUUIDToken>(uuid, data, expires);
|
2024-04-23 02:27:08 +02:00
|
|
|
return uuid;
|
|
|
|
}
|
|
|
|
|
2024-05-05 18:16:00 +02:00
|
|
|
SP<CUUIDToken> CTokenManager::getToken(const std::string& uuid) {
|
2024-04-23 02:27:08 +02:00
|
|
|
|
|
|
|
// cleanup expired tokens
|
2024-06-25 16:05:39 +02:00
|
|
|
const auto NOW = std::chrono::steady_clock::now();
|
2024-04-23 02:27:08 +02:00
|
|
|
std::erase_if(m_mTokens, [this, &NOW](const auto& el) { return el.second->expiresAt < NOW; });
|
|
|
|
|
|
|
|
if (!m_mTokens.contains(uuid))
|
|
|
|
return {};
|
|
|
|
|
|
|
|
return m_mTokens.at(uuid);
|
|
|
|
}
|
|
|
|
|
2024-05-05 18:16:00 +02:00
|
|
|
void CTokenManager::removeToken(SP<CUUIDToken> token) {
|
2024-04-23 02:27:08 +02:00
|
|
|
if (!token)
|
|
|
|
return;
|
|
|
|
m_mTokens.erase(token->uuid);
|
|
|
|
}
|