feat: add optional sliding idle timeout to PIHTTPServerSessionAuth
The idle timeout is opt-in: when set with setSessionIdleTimeout(), a session expires after that period without a successful request and every successful request extends it. When unset (the default), sessions are not touched and keep the previous behavior: the absolute tokenTtl applied to created, or living until logout. Both deadlines can be combined and the earlier one wins. - SessionRec: add last_used, drop the unused refresh_token field - checkToken(): update last_used only while the idle timeout is enabled - tests: IdleTimeout, IdleActivityExtendsSession, IdleDisabledKeepsSession, HasSessionIdleTimeout
This commit is contained in:
@@ -74,10 +74,19 @@ PIHTTP::AuthInfo PIHTTPServerSessionAuth::checkToken(const PIString & token) {
|
||||
PIMutexLocker locker(mutex);
|
||||
SessionRec s = sessions.value(token);
|
||||
if (s.isInvalid()) return false;
|
||||
if (hasTokenTtl() && PISystemTime::current() - s.created >= token_ttl) {
|
||||
const PISystemTime now = PISystemTime::current();
|
||||
if (hasTokenTtl() && now - s.created >= token_ttl) {
|
||||
sessions.remove(token);
|
||||
return false;
|
||||
}
|
||||
if (hasSessionIdleTimeout()) {
|
||||
const PISystemTime base = s.last_used.isNull() ? s.created : s.last_used;
|
||||
if (now - base >= session_idle_timeout) {
|
||||
sessions.remove(token);
|
||||
return false;
|
||||
}
|
||||
sessions[token].last_used = now;
|
||||
}
|
||||
return {true, s.user_id};
|
||||
}
|
||||
|
||||
@@ -88,8 +97,9 @@ PIString PIHTTPServerSessionAuth::issueToken(int user_id) {
|
||||
if (data.isEmpty()) return PIString();
|
||||
PIString token = data.toHex();
|
||||
SessionRec & s(sessions[token]);
|
||||
s.user_id = user_id;
|
||||
s.created = PISystemTime::current();
|
||||
s.user_id = user_id;
|
||||
s.created = PISystemTime::current();
|
||||
s.last_used = s.created;
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -132,6 +142,24 @@ bool PIHTTPServerSessionAuth::hasTokenTtl() const {
|
||||
}
|
||||
|
||||
|
||||
void PIHTTPServerSessionAuth::setSessionIdleTimeout(PISystemTime t) {
|
||||
PIMutexLocker locker(mutex);
|
||||
session_idle_timeout = t;
|
||||
}
|
||||
|
||||
|
||||
PISystemTime PIHTTPServerSessionAuth::sessionIdleTimeout() const {
|
||||
PIMutexLocker locker(mutex);
|
||||
return session_idle_timeout;
|
||||
}
|
||||
|
||||
|
||||
bool PIHTTPServerSessionAuth::hasSessionIdleTimeout() const {
|
||||
PIMutexLocker locker(mutex);
|
||||
return !session_idle_timeout.isNull();
|
||||
}
|
||||
|
||||
|
||||
PIHTTP::MessageMutable PIHTTPServerSessionAuth::handleLogin(const PIHTTP::MessageConst & request) {
|
||||
PIJSON j = PIJSON::fromJSON(PIString::fromUTF8(request.body()));
|
||||
if (!j.isObject() || !j.contains("login") || !j.contains("password") || j["login"].toString().isEmpty())
|
||||
|
||||
Reference in New Issue
Block a user