Teaspeak-Server/license/server/KeyIdCache.cpp

79 lines
2.3 KiB
C++
Raw Normal View History

#include "log/LogUtils.h"
2020-02-28 05:24:07 -05:00
#include "DatabaseHandler.h"
using namespace license;
2020-02-28 05:24:07 -05:00
using namespace license::server::database;
using namespace std;
using namespace std::chrono;
2020-02-28 05:24:07 -05:00
KeyIdCache::KeyIdCache(DatabaseHandler *handle) : handle(handle) {}
2020-02-28 05:24:07 -05:00
void KeyIdCache::clear_cache() {
std::lock_guard elock{this->entry_lock};
this->entries.clear();
}
std::string KeyIdCache::get_key_from_id(size_t keyId) {
{
2020-02-28 05:24:07 -05:00
std::lock_guard elock{this->entry_lock};
for(const auto& entry : this->entries)
if(entry->keyId == keyId) return entry->key;
}
2020-02-28 05:24:07 -05:00
sql::command(this->handle->sql(), "SELECT `key`, `keyId` FROM `license` WHERE `keyId` = :key", variable{":key", keyId})
.query(&KeyIdCache::insert_entry, this);
{
2020-02-28 05:24:07 -05:00
std::lock_guard elock{this->entry_lock};
for(const auto& entry : this->entries)
if(entry->keyId == keyId) return entry->key;
return ""; //Key not found!
}
}
2020-02-28 05:24:07 -05:00
size_t KeyIdCache::get_key_id_from_key(const std::string &key) {
{
2020-02-28 05:24:07 -05:00
std::lock_guard elock{this->entry_lock};
for(const auto& entry : this->entries)
if(entry->key == key) return entry->keyId;
}
2020-02-28 05:24:07 -05:00
auto result = sql::command(this->handle->sql(), "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());
{
2020-02-28 05:24:07 -05:00
std::lock_guard elock{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) {
2020-02-28 05:24:07 -05:00
string key{"unknown"};
size_t keyId{0};
for(int index = 0; index < length; index++) {
if(names[index] == "key")
key = value[index];
else if(names[index] == "keyId")
2020-02-28 05:24:07 -05:00
keyId = std::strtoll(value[index].c_str(), nullptr, 10);
}
if(!keyId) {
logWarning(LOG_GENERAL, "Failed to parse key id for key {}", key);
return 0;
}
{
2020-02-28 05:24:07 -05:00
auto entry = new KeyIdCache::CacheEntry{key, keyId, system_clock::now()};
std::lock_guard elock{this->entry_lock};
this->entries.emplace_back(entry);
}
return 0;
}