- auth.single_session_waiter gains 'ask', the new default (Alembic 0051 moves venues on 'off'
to it): a second phone gets auth.session_elsewhere {device, since}; Continue retries with
replace=true and the first phone is signed out at once (live session.ended, reason
"replaced") and says why on its sign-in page. Only phones count (terminal sessions are
their own client). refuse_new / end_old unchanged.
- auth.session_ended now carries the reason; the waiter app keeps it until the next sign-in.
- The waiter app sends queued offline ops on every (re)connection, so an order queued on a
phone that was signed out by another goes out after the next sign-in there (e2e checked).
- auth.terminal_require_username (venue) + Device.require_username (per device, wins):
GET /api/devices/me/users lists nobody, the screen asks for a username then PIN/password,
a picked user_id is refused (auth.username_required), "tap" falls back to PIN.
- Manager: Sign-in settings (ask, the new switch), the device dialog's usernames choice.
Plan platform-v2 6F.7.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
272 lines
11 KiB
Python
272 lines
11 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 | ask).
|
|
`ask` (waiters, the default since 6F.7): a login while signed in elsewhere is refused with
|
|
auth.session_elsewhere (where, since when) until the app retries with replace=True; then
|
|
the old sessions end with reason "replaced" (their sockets get session.ended at once).
|
|
Only the waiter's phones count: a terminal session (the counter) is its own client.
|
|
- 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().
|
|
- Ending a session also closes its live sockets (services.ws_bus.end_session, plan 3.1a).
|
|
"""
|
|
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:
|
|
if client == "waiter":
|
|
return _setting(db, "auth.single_session_waiter", "ask") # 6F.7: ask is the default
|
|
return _setting(db, "auth.single_session_manager", "off") if client == "manager" else "off"
|
|
|
|
|
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
|
|
|
def device_label(user_agent: str | None) -> str:
|
|
"""A short, language-neutral name for where a session runs ("Android · Chrome")."""
|
|
ua = user_agent or ""
|
|
system = next((name for key, name in (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"),
|
|
("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux"))
|
|
if key in ua), "")
|
|
browser = next((name for key, name in (("EdgA", "Edge"), ("Edg/", "Edge"), ("Firefox", "Firefox"), ("FxiOS", "Firefox"),
|
|
("CriOS", "Chrome"), ("Chrome", "Chrome"), ("Safari", "Safari"))
|
|
if key in ua), "")
|
|
if "; wv)" in ua:
|
|
browser = "app"
|
|
return " · ".join(x for x in (system, browser) if x)
|
|
|
|
|
|
def start(db, user, client: str, request=None, *, device=None, expires_at=None, replace: bool = False):
|
|
"""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). `replace`: the person said yes to signing
|
|
out their other session (rule `ask`)."""
|
|
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)
|
|
if active and rule == "ask" and not replace:
|
|
last = max(active, key=lambda s: s.created_at)
|
|
from core.timeutil import iso_z
|
|
raise XeniaError("auth.session_elsewhere", client=client, since=iso_z(last.created_at),
|
|
device=device_label(last.user_agent) or "?", ip=last.ip or "")
|
|
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)
|
|
from services import ws_bus
|
|
ws_bus.end_session(row.id, reason) # its open sockets get session.ended and close (3.1a)
|
|
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)
|
|
# why it ended (replaced, logout, idle...): the app can say "you signed in elsewhere"
|
|
raise XeniaError("auth.session_ended", reason=(row.end_reason if row is not None else None) or "unknown")
|
|
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"
|
|
|
|
|
|
def terminal_requires_username(db, device=None) -> bool:
|
|
"""Paired screens (6F.7): type a username instead of picking a name. The device's own
|
|
choice (Device.require_username) wins over the venue's auth.terminal_require_username."""
|
|
own = getattr(device, "require_username", None)
|
|
if own is not None:
|
|
return bool(own)
|
|
return _setting(db, "auth.terminal_require_username", "false") == "true"
|