feat(backend): sign people out after N days without use (auth.idle_days, default 14)
Platform-v2 step 2.99d, owner decision 2026-11-14. - New core setting auth.idle_days (int, default 14, 0 = never). A manager, waiter or paired-device session unused for that long ends with reason "idle" on its next request (sessions.validate) or when someone opens "Signed in now" (sessions.end_idle in GET /api/auth/sessions). Support keeps its own 4 h expiry. - Manager: Settings -> Sign-in & security -> "Sign people out after" (7/14/30/60/90 days / Never; a value set elsewhere is kept); "Signed in now" names the reason. Texts en/el. - Tests: backend 284 (+ 14-day default, list drops idle ones, setting incl. 0); manager e2e checks the default and saving 30. The support-access check that failed once in ~8 runs now saves a screenshot and the page's alert text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,9 @@ Sessions
|
||||
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
|
||||
so an ended session is refused on its very next request.
|
||||
- last_seen_at is written at most every LAST_SEEN_EVERY_S, in its own DB session.
|
||||
- Idle sessions (owner decision 2026-11-14, plan 2.99d): a session unused for
|
||||
auth.idle_days days (default 14, 0 = never) ends with reason "idle" on its next request
|
||||
(validate) or when someone lists sessions (end_idle). Support sessions use expires_at.
|
||||
|
||||
Login modes (settings, declared in modules/core/manifest.py)
|
||||
- auth.manager_login_mode: password | pin (manager in a browser: never tap/none, D-8)
|
||||
@@ -128,6 +131,33 @@ def end_for_device(db, device_id: int, reason: str) -> int:
|
||||
return len(rows)
|
||||
|
||||
|
||||
def idle_days(db) -> int:
|
||||
try:
|
||||
return max(0, int(_setting(db, "auth.idle_days", "14")))
|
||||
except ValueError:
|
||||
return 14
|
||||
|
||||
|
||||
def _idle(row, days: int, now) -> bool:
|
||||
return days > 0 and row.client != "support" and now - row.last_seen_at > timedelta(days=days)
|
||||
|
||||
|
||||
def end_idle(db) -> int:
|
||||
"""End every active session unused for auth.idle_days. Returns how many."""
|
||||
from models.session import LoginSession
|
||||
days = idle_days(db)
|
||||
if not days:
|
||||
return 0
|
||||
now = utcnow()
|
||||
rows = db.query(LoginSession).filter(LoginSession.ended_at.is_(None), LoginSession.client != "support",
|
||||
LoginSession.last_seen_at < now - timedelta(days=days)).all()
|
||||
for r in rows:
|
||||
_end_row(r, "idle")
|
||||
if rows:
|
||||
db.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def validate(sid: str | None, db=None) -> Active:
|
||||
"""(user_id, device_id) of an active session. Raises auth.session_ended."""
|
||||
if not sid:
|
||||
@@ -147,6 +177,9 @@ def validate(sid: str | None, db=None) -> Active:
|
||||
if row is not None and row.ended_at is None and row.expires_at is not None and row.expires_at <= utcnow():
|
||||
_end_row(row, "expired")
|
||||
db.commit()
|
||||
elif row is not None and row.ended_at is None and _idle(row, idle_days(db), utcnow()):
|
||||
_end_row(row, "idle")
|
||||
db.commit()
|
||||
if row is None or row.ended_at is not None:
|
||||
with _lock:
|
||||
_cache.pop(sid, None)
|
||||
|
||||
@@ -27,6 +27,7 @@ MODULE = Module(
|
||||
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
||||
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
|
||||
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
|
||||
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
|
||||
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
|
||||
|
||||
@@ -294,6 +294,7 @@ def list_sessions(request: Request, include_ended: bool = False, db: Session = D
|
||||
"""Active sessions (optionally the last 200 ended ones too), newest first. `current`
|
||||
marks the caller's own session; `device_name`/`device_app` name a terminal's device."""
|
||||
from models.device import Device
|
||||
sessions.end_idle(db) # so "Signed in now" never lists someone gone for weeks (auth.idle_days)
|
||||
q = db.query(LoginSession)
|
||||
if not include_ended:
|
||||
q = q.filter(LoginSession.ended_at.is_(None))
|
||||
|
||||
@@ -169,3 +169,51 @@ def test_session_survives_cache_loss_like_a_restart(client, make_user):
|
||||
h = _bearer(client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD}))
|
||||
sessions.clear_cache()
|
||||
assert client.get("/api/auth/me", headers=h).status_code == 200
|
||||
|
||||
|
||||
# ── idle sessions (plan 2.99d, owner decision 2026-11-14) ────────────────────
|
||||
|
||||
def _age(db, days, **flt):
|
||||
from datetime import timedelta
|
||||
from core import sessions
|
||||
from core.timeutil import utcnow
|
||||
from models.session import LoginSession
|
||||
for row in db.query(LoginSession).filter_by(**flt).all():
|
||||
row.last_seen_at = utcnow() - timedelta(days=days)
|
||||
db.commit()
|
||||
sessions.clear_cache()
|
||||
|
||||
|
||||
def test_idle_session_ends_after_14_days_by_default(client, db, make_user):
|
||||
w = make_user(role="waiter")
|
||||
wh = _bearer(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN}))
|
||||
_age(db, 13, user_id=w.id)
|
||||
assert client.get("/api/auth/me", headers=wh).status_code == 200 # 13 days: still in
|
||||
_age(db, 15, user_id=w.id)
|
||||
r = client.get("/api/auth/me", headers=wh)
|
||||
assert r.status_code == 401 and r.json()["error"]["code"] == "auth.session_ended"
|
||||
from models.session import LoginSession
|
||||
db.expire_all()
|
||||
assert db.query(LoginSession).filter_by(user_id=w.id).one().end_reason == "idle"
|
||||
|
||||
|
||||
def test_signed_in_now_drops_idle_sessions(client, db, make_user, login):
|
||||
owner = make_user(role="owner")
|
||||
w = make_user(role="waiter")
|
||||
client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN})
|
||||
oh = login(owner)
|
||||
_age(db, 20, user_id=w.id)
|
||||
assert all(s["user_id"] != w.id for s in client.get("/api/auth/sessions", headers=oh).json())
|
||||
ended = client.get("/api/auth/sessions?include_ended=true", headers=oh).json()
|
||||
assert next(s for s in ended if s["user_id"] == w.id)["end_reason"] == "idle"
|
||||
|
||||
|
||||
def test_idle_days_setting_and_zero_means_never(client, db, make_user, admin_h):
|
||||
w = make_user(role="waiter")
|
||||
wh = _bearer(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN}))
|
||||
_set(client, admin_h, "auth.idle_days", "0")
|
||||
_age(db, 400, user_id=w.id)
|
||||
assert client.get("/api/auth/me", headers=wh).status_code == 200
|
||||
_set(client, admin_h, "auth.idle_days", "3")
|
||||
_age(db, 4, user_id=w.id)
|
||||
assert client.get("/api/auth/me", headers=wh).status_code == 401
|
||||
|
||||
Reference in New Issue
Block a user