This commit is contained in:
Lukas Forsberg 2026-01-23 22:28:43 +01:00
parent f498328249
commit 38ff44f2e9
3 changed files with 8 additions and 4 deletions

View File

@ -9,6 +9,7 @@ class Session {
public:
static constexpr auto SESSION_LIFETIME = std::chrono::minutes(30);
static constexpr size_t SESSION_ID_SIZE = 32;
Session(int userId);

View File

@ -49,7 +49,7 @@ void SessionHandler::cleanupWorker(){
}
std::optional<std::string> SessionHandler::createSession(int userId){
std::string sessionId = randomString(32);
std::string sessionId = randomString(Session::SESSION_ID_SIZE);
std::lock_guard<std::mutex> lock(sessionMutex);
if (!sessions.emplace(sessionId, Session(userId)).second){
return {};
@ -60,6 +60,7 @@ std::optional<std::string> SessionHandler::createSession(int userId){
std::optional<int> SessionHandler::isSessionValid(const std::string& sessionId){
auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lock(sessionMutex);
auto it = sessions.find(sessionId);
if(it != sessions.end()){
if (it->second.isExpired(now)){
@ -67,6 +68,7 @@ std::optional<int> SessionHandler::isSessionValid(const std::string& sessionId){
it = sessions.erase(it);
return {};
}
it->second.extend(now); // extend session life time
return it->second.userId();
}
return {};

View File

@ -13,8 +13,9 @@ std::string getSessionId(const crow::request& req) {
auto cookie_header = req.get_header_value("Cookie");
std::string prefix = "session_id=";
auto pos = cookie_header.find(prefix);
if (pos == std::string::npos) return "";
return cookie_header.substr(pos + prefix.size(), 32);
if (pos == std::string::npos)
return "";
return cookie_header.substr(pos + prefix.size(), Session::SESSION_ID_SIZE);
}
bool isLoggedIn(const crow::request& req) {