Platform v2 step 1.6 (APPS_PLATFORM D-8, D-9, §6.2, §6.4).
- sessions table (revision 0006); every JWT carries `sid` and is accepted
only while its session is active (validated per request, 10 s cache that
is dropped the moment a session ends); the in-memory blacklist is gone, so
logout and "end session" survive restarts
- one login path, POST /api/auth/login {client, username?, user_id?, pin?,
password?}: manager mode password|pin (username-only "none" removed, D-8),
waiter mode pin|password|tap (tap answers auth.mode_needs_device until
paired devices exist), optional "waiter must type username", and the app's
access key (core.dashboard.access / waiter_app.access)
- auth.single_session_manager / _waiter: off | refuse_new | end_old
- /login without `client` = the current manager UI with v1 rules (pin or
password; refuse_new treated as end_old because its lock screen re-logs-in);
/login-by-id is a deprecated wrapper for the current waiter app;
/login-no-auth removed
- GET /api/auth/sessions, POST /api/auth/sessions/{id}/end (core.staff.manage);
blocking a user ends their sessions; refresh keeps the session; logout
takes the bearer header (or ?token= as before)
- settings API validates enum/bool/int values from the manifests;
security.login_method migrated to auth.manager_login_mode
- tests: modes, single-session rules, logout, refresh, forged token without
session, manager session list/end
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
6.4 KiB
Python
174 lines
6.4 KiB
Python
"""Login sessions and login modes (APPS_PLATFORM D-8, D-9, §6.2, §6.4).
|
|
|
|
Sessions
|
|
- start(db, user, client, request) creates a row and applies the client's single-session
|
|
rule (setting auth.single_session_<client>: off | refuse_new | end_old).
|
|
- validate(sid) is called on every authenticated request (routers.deps.decode_token).
|
|
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.
|
|
|
|
Login modes (settings, declared in modules/core/manifest.py)
|
|
- auth.manager_login_mode: password | pin (manager in a browser: never tap/none, D-8)
|
|
- auth.waiter_login_mode: pin | password | tap (tap needs a paired device: step 1.8)
|
|
- auth.waiter_require_username: the waiter must type their username, not just pick a name
|
|
|
|
Agent notes:
|
|
- Clients: "manager", "waiter" now; "terminal" (devices) in 1.8; "support" in 1.10.
|
|
- Never trust a JWT alone: always go through validate().
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from datetime import timedelta
|
|
|
|
from core.errors import XeniaError
|
|
from core.timeutil import utcnow
|
|
|
|
logger = logging.getLogger("xenia.sessions")
|
|
|
|
CLIENTS = ("manager", "waiter", "terminal", "support")
|
|
CACHE_TTL_S = 10
|
|
LAST_SEEN_EVERY_S = 60
|
|
|
|
_lock = threading.Lock()
|
|
_cache: dict[str, tuple[float, int | None]] = {} # sid -> (checked_at monotonic, user_id) for ACTIVE sessions
|
|
|
|
|
|
def _setting(db, key: str, default: str) -> str:
|
|
from models.settings import PosSettings
|
|
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
|
return row.value if row and row.value else default
|
|
|
|
|
|
def single_session_rule(db, client: str) -> str:
|
|
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off"
|
|
|
|
|
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
|
|
|
def start(db, user, client: str, request=None, *, legacy_manager: bool = False):
|
|
"""Create a session for user (None user_id for the support ghost). Commits."""
|
|
from models.session import LoginSession
|
|
if client not in CLIENTS:
|
|
raise ValueError(f"unknown client {client!r}")
|
|
user_id = getattr(user, "id", None) or None
|
|
rule = single_session_rule(db, client)
|
|
if legacy_manager and rule == "refuse_new":
|
|
# The current manager UI re-logs-in to unlock its lock screen; refusing would lock
|
|
# the owner out. Until the phase 2 manager has a real unlock, treat it as end_old.
|
|
rule = "end_old"
|
|
if user_id is not None and rule != "off":
|
|
active = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.client == client,
|
|
LoginSession.ended_at.is_(None)).all()
|
|
if active and rule == "refuse_new":
|
|
raise XeniaError("auth.session_exists", client=client)
|
|
for s in active:
|
|
_end_row(s, "replaced")
|
|
now = utcnow()
|
|
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
|
|
ip=(request.client.host if request is not None and request.client else None),
|
|
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
|
|
db.add(row)
|
|
db.commit()
|
|
logger.info("session.started sid=%s user=%s client=%s rule=%s", row.id[:8], user_id, client, rule)
|
|
return row
|
|
|
|
|
|
def _end_row(row, reason: str) -> None:
|
|
row.ended_at = utcnow()
|
|
row.end_reason = reason
|
|
with _lock:
|
|
_cache.pop(row.id, None)
|
|
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
|
|
|
|
|
|
def end(db, sid: str, reason: str) -> bool:
|
|
from models.session import LoginSession
|
|
row = db.get(LoginSession, sid)
|
|
if row is None or row.ended_at is not None:
|
|
return False
|
|
_end_row(row, reason)
|
|
db.commit()
|
|
return True
|
|
|
|
|
|
def end_for_user(db, user_id: int, reason: str) -> int:
|
|
from models.session import LoginSession
|
|
rows = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.ended_at.is_(None)).all()
|
|
for r in rows:
|
|
_end_row(r, reason)
|
|
db.commit()
|
|
return len(rows)
|
|
|
|
|
|
def validate(sid: str | None, db=None) -> int | None:
|
|
"""User id of an active session (None for support). Raises auth.session_ended."""
|
|
if not sid:
|
|
raise XeniaError("auth.session_ended")
|
|
now_m = time.monotonic()
|
|
with _lock:
|
|
hit = _cache.get(sid)
|
|
if hit and now_m - hit[0] < CACHE_TTL_S:
|
|
return hit[1]
|
|
from models.session import LoginSession
|
|
own = db is None
|
|
if own:
|
|
from database import SessionLocal
|
|
db = SessionLocal()
|
|
try:
|
|
row = db.get(LoginSession, sid)
|
|
if row is None or row.ended_at is not None:
|
|
with _lock:
|
|
_cache.pop(sid, None)
|
|
raise XeniaError("auth.session_ended")
|
|
user_id = row.user_id
|
|
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
|
finally:
|
|
if own:
|
|
db.close()
|
|
if stale:
|
|
_touch(sid)
|
|
with _lock:
|
|
_cache[sid] = (now_m, user_id)
|
|
return user_id
|
|
|
|
|
|
def _touch(sid: str) -> None:
|
|
from database import SessionLocal
|
|
from models.session import LoginSession
|
|
s = SessionLocal()
|
|
try:
|
|
row = s.get(LoginSession, sid)
|
|
if row is not None and row.ended_at is None:
|
|
row.last_seen_at = utcnow()
|
|
s.commit()
|
|
except Exception:
|
|
logger.debug("session.touch_failed sid=%s", sid[:8], exc_info=True)
|
|
finally:
|
|
s.close()
|
|
|
|
|
|
def clear_cache() -> None:
|
|
with _lock:
|
|
_cache.clear()
|
|
|
|
|
|
# ── login modes ──────────────────────────────────────────────────────────────
|
|
|
|
def manager_login_mode(db) -> str:
|
|
v = _setting(db, "auth.manager_login_mode", "password")
|
|
return v if v in ("password", "pin") else "password"
|
|
|
|
|
|
def waiter_login_mode(db) -> str:
|
|
v = _setting(db, "auth.waiter_login_mode", "pin")
|
|
return v if v in ("pin", "password", "tap") else "pin"
|
|
|
|
|
|
def waiter_requires_username(db) -> bool:
|
|
return _setting(db, "auth.waiter_require_username", "false") == "true"
|