Teaspeak-Server/license/server/KeyIdCache.cpp

67 lines
2.1 KiB
C++
Raw Normal View History

#include "log/LogUtils.h"
#include "LicenseManager.h"
using namespace license;
using namespace license::server;
using namespace std;
using namespace std::chrono;
using KeyIdCache = LicenseManager::KeyIdCache;
KeyIdCache::KeyIdCache(license::server::LicenseManager *handle) : handle(handle) {}
std::string KeyIdCache::getKey(size_t keyId) {
{
threads::MutexLock lock(this->entry_lock);
for(const auto& entry : this->entries)
if(entry->keyId == keyId) return entry->key;
}
sql::command(this->handle->database, "SELECT `key`, `keyId` FROM `license` WHERE `keyId` = :key", variable{":key", keyId})
.query(&KeyIdCache::insert_entry, this);
{
threads::MutexLock lock(this->entry_lock);
for(const auto& entry : this->entries)
if(entry->keyId == keyId) return entry->key;
return ""; //Key not found!
}
}
size_t KeyIdCache::getKeyId(const std::string &key) {
{
threads::MutexLock lock(this->entry_lock);
for(const auto& entry : this->entries)
if(entry->key == key) return entry->keyId;
}
auto result = sql::command(this->handle->database, "SELECT `key`, `keyId` FROM `license` WHERE `key` = :key", variable{":key", key})
.query(&KeyIdCache::insert_entry, this);
if(!result)
logError(LOG_GENERAL, "Failed to query key id for license. Query resulted in {}", result.fmtStr());
{
threads::MutexLock lock(this->entry_lock);
for(const auto& entry : this->entries)
if(entry->key == key)
return entry->keyId;
return 0; //Key not found!
}
}
int KeyIdCache::insert_entry(int length, std::string *value, std::string *names) {
string key;
size_t keyId = 0;
for(int index = 0; index < length; index++)
if(names[index] == "key")
key = value[index];
else if(names[index] == "keyId")
keyId = stoll(value[index]);
{
threads::MutexLock lock(this->entry_lock);
this->entries.push_back(new KeyIdCache::CacheEntry{key, keyId, system_clock::now()});
}
return 0;
}