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,7 +9,8 @@ class Session {
public: public:
static constexpr auto SESSION_LIFETIME = std::chrono::minutes(30); static constexpr auto SESSION_LIFETIME = std::chrono::minutes(30);
static constexpr size_t SESSION_ID_SIZE = 32;
Session(int userId); Session(int userId);
// extend the session lifetime // extend the session lifetime

View File

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

View File

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