"""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_: 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. - 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) - 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", "terminal" (a user on a paired device, step 1.8; the row's device_id binds it to that device, and a new login on the device replaces the old one), "support" (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 typing import NamedTuple, Optional 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() class Active(NamedTuple): """What validate() knows about an active session.""" user_id: Optional[int] # None = the support account device_id: Optional[int] # set for terminal sessions: the device they belong to expires_at: Optional[object] = None # hard end (support sessions); None = none _cache: dict[str, tuple[float, Active]] = {} # sid -> (checked_at monotonic, info) 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, *, device=None, expires_at=None): """Create a session for user (None user_id for the support account). Commits. `device`: the paired device of a terminal login; its previous sessions are replaced (a shared screen shows one user at a time).""" 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 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") if device is not None: for s in db.query(LoginSession).filter(LoginSession.device_id == device.id, LoginSession.ended_at.is_(None)): _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, device_id=(device.id if device is not None else None), expires_at=expires_at, 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 end_for_device(db, device_id: int, reason: str) -> int: from models.session import LoginSession rows = db.query(LoginSession).filter(LoginSession.device_id == device_id, LoginSession.ended_at.is_(None)).all() for r in rows: _end_row(r, reason) db.commit() 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: 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 and not (hit[1].expires_at and hit[1].expires_at <= utcnow()): 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 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) raise XeniaError("auth.session_ended") info = Active(row.user_id, row.device_id, row.expires_at) 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, info) return info 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"