Files
xenia-pos-local/local_backend/routers/auth.py
T
bonaminandClaude Opus 5.5 2dc5da446e feat: foundations for the manager conversion (platform-v2 step 6.1)
- Backend: every HTTPException in routers/ is an error code now (260 raises, ~105 new codes,
  texts in en + el); XeniaError(detail=...) keeps the three v1-shaped answers old pages read;
  bad / unknown tokens answer auth.session_ended; test_errors refuses new HTTPExceptions.
- Manager: v2.json is the list of pages on the v2 rules: scripts/lint.mjs lints them,
  tests/v2-guards.test.mjs refuses Greek and colour literals, `strict` paths make
  set-state-in-effect an error.
- src/live/useLiveQuery.js (react-query + live events + refresh on reconnect); Signed in now
  uses it.
- Dead manager files removed (3.1k lines unreachable from main.jsx).
- Tests: backend 544 passed, manager unit 33, run-all (no Android) passed (manager's live
  bell check passed on a rerun).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:31:36 +02:00

428 lines
20 KiB
Python

from core.access.deps import public
from core.access.check import holds
from core.access.queries import holders_filter
import bcrypt
import logging
import threading
from typing import Optional
import jwt
from fastapi import APIRouter, Depends, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from database import get_db
from config import settings
from models.user import User
from schemas.auth import LoginRequest, TokenResponse, UpdateMeRequest
from pydantic import BaseModel as _PydanticBase
_logger = logging.getLogger(__name__)
from schemas.user import UserOut
from core.i18n import normalize_language
from routers.deps import bearer, get_current_user, make_token, decode_token, make_support_user
from core import sessions
from core.access.deps import require
from core.errors import XeniaError
from core.timeutil import iso_z
from models.session import LoginSession
from routers.recovery import try_recovery_code
router = APIRouter()
_optional_bearer = HTTPBearer(auto_error=False)
# ── Login (one endpoint, D-8, D-9, §6.4) ──────────────────────────────────────
def _check_secret(user, pin, password, db) -> bool:
if password and user.password_hash and bcrypt.checkpw(password.encode(), user.password_hash.encode()):
return True
if password and try_recovery_code(password, user, db):
return True
return bool(pin and user.pin_hash and bcrypt.checkpw(pin.encode(), user.pin_hash.encode()))
def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None,
pin: str | None, password: str | None) -> TokenResponse:
"""The one login path. Applies the client's login mode, its access key and the
single-session rule, then creates a session (core/sessions.py)."""
if client not in ("manager", "waiter", "terminal"):
raise XeniaError("validation.invalid")
if client == "terminal":
return _terminal_login(db, request, username=username, user_id=user_id, pin=pin, password=password)
if client == "manager":
mode = sessions.manager_login_mode(db)
if mode == "password" and not password:
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
if mode == "pin" and not (pin or password):
raise XeniaError("auth.invalid_credentials")
if not username:
raise XeniaError("auth.username_required")
else:
mode = sessions.waiter_login_mode(db)
if mode == "tap":
raise XeniaError("auth.mode_needs_device", mode="tap") # >>> step 1.8: paired devices
if mode == "password" and not password:
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
if mode == "pin" and not pin:
raise XeniaError("auth.login_mode_not_allowed", mode="password")
if sessions.waiter_requires_username(db) and not username:
raise XeniaError("auth.username_required")
q = db.query(User).filter(User.is_active == True) # noqa: E712
user = q.filter(User.username == username).first() if username else (
q.filter(User.id == user_id).first() if user_id is not None else None)
if user is None or not _check_secret(user, pin, password, db):
raise XeniaError("auth.invalid_credentials")
needed = "core.dashboard.access" if client == "manager" else "waiter_app.access"
if not holds(user, needed):
raise XeniaError("auth.client_not_allowed", client=client)
row = sessions.start(db, user, client, request)
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
def _terminal_login(db: Session, request: Request, *, username, user_id, pin, password) -> TokenResponse:
"""A user on a paired device (D-8). Needs the X-Xenia-Device header; the device's login
mode applies (tap and none exist only here). The user needs '<app>.access'. The session
is bound to the device and replaces the device's previous one."""
from core.access.context import current_device
from core.modules.state import blocked_error, is_effective
from routers.devices import effective_login_mode
device = current_device(request, db)
if device is None:
raise XeniaError("device.not_paired")
if not is_effective(device.app_key, db):
raise blocked_error(device.app_key, db)
mode = effective_login_mode(db, device)
if mode == "none":
raise XeniaError("auth.login_mode_not_allowed", mode="none") # the device works without a user
if mode == "pin" and not pin:
raise XeniaError("auth.login_mode_not_allowed", mode="password")
if mode == "password" and not password:
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
q = db.query(User).filter(User.is_active == True) # noqa: E712
user = q.filter(User.username == username).first() if username else (
q.filter(User.id == user_id).first() if user_id is not None else None)
if user is None or (mode != "tap" and not _check_secret(user, pin, password, db)):
raise XeniaError("auth.invalid_credentials")
if not holds(user, f"{device.app_key}.access"):
raise XeniaError("auth.client_not_allowed", client=device.app_key)
row = sessions.start(db, user, "terminal", request, device=device)
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(public())])
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
"terminal" = a user on a paired device: send the X-Xenia-Device header."""
return do_login(db, request, client=body.client, username=body.username,
user_id=body.user_id, pin=body.pin, password=body.password)
@router.post("/refresh", response_model=TokenResponse)
def refresh(credentials: HTTPAuthorizationCredentials = Depends(bearer), db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""A fresh token (new expiry) for the SAME session."""
payload = decode_token(credentials.credentials, db)
return TokenResponse(access_token=make_token(user, payload["sid"]), user=UserOut.model_validate(user))
# ── Unlock (plan step 2.6b) ──────────────────────────────────────────────────
# The manager's lock screen (and later the apps' own) checks the PIN of the user who owns
# the CURRENT session, and keeps that session: no new login, no new token, so the
# single-session rules never see a second login. After UNLOCK_MAX_FAILURES wrong tries
# the session is ended (someone is guessing on an unattended screen).
UNLOCK_MAX_FAILURES = 5
_unlock_failures: dict[str, int] = {} # sid -> wrong tries since the last success
_unlock_lock = threading.Lock()
class UnlockRequest(_PydanticBase):
pin: Optional[str] = None
password: Optional[str] = None
@router.post("/unlock")
def unlock(body: UnlockRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""POST {pin} (or {password}) with the session's own token. 200 {user} = unlocked.
Wrong: 401 auth.wrong_pin {attempts_left}; the last allowed miss ends the session
(401 auth.session_ended)."""
sid = getattr(request.state, "xenia_sid", None)
if _check_secret(user, body.pin, body.password, db):
with _unlock_lock:
_unlock_failures.pop(sid, None)
return {"user": UserOut.model_validate(user)}
with _unlock_lock:
failures = _unlock_failures.get(sid, 0) + 1
_unlock_failures[sid] = failures
if failures >= UNLOCK_MAX_FAILURES:
with _unlock_lock:
_unlock_failures.pop(sid, None)
sessions.end(db, sid, "unlock_failed")
_logger.warning("auth.unlock: too many wrong PINs, session ended user=%s", user.id)
raise XeniaError("auth.session_ended")
raise XeniaError("auth.wrong_pin", attempts_left=UNLOCK_MAX_FAILURES - failures)
@router.post("/logout", dependencies=[Depends(public())])
def logout(credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
token: Optional[str] = None, db: Session = Depends(get_db)):
"""Ends the caller's session (Authorization header, or ?token= as v1 sent it)."""
raw = credentials.credentials if credentials else token
if raw:
try:
payload = jwt.decode(raw, settings.SECRET_KEY, algorithms=["HS256"])
sessions.end(db, payload.get("sid"), "logout")
except jwt.InvalidTokenError:
pass
return {"status": "logged out"}
# ── Support access (D-16, §6.5) ─────────────────────────────────────────────
# The login screen's "Support access" asks for a challenge, the builder answers with
# tools/support_code.py <SITE_ID> <challenge>, and verify opens a 4 h support session
# (synthetic superadmin). Works offline. Replaces the MASTER_USERNAME/PASSWORD account.
SUPPORT_CHALLENGE_TTL_MIN = 15
SUPPORT_SESSION_HOURS = 4
SUPPORT_MAX_ATTEMPTS = 5 # wrong codes per challenge
SUPPORT_MAX_OPEN = 5 # unexpired, unused challenges at once
class SupportVerifyRequest(_PydanticBase):
challenge: str
code: str
def _support_configured() -> None:
if not (settings.SUPPORT_SECRET and settings.SITE_ID):
raise XeniaError("auth.support_not_configured")
@router.post("/support/challenge", status_code=201, dependencies=[Depends(public())])
def support_challenge(request: Request, db: Session = Depends(get_db)):
"""A new challenge to read to the builder: {challenge: "ABCD-EFGH", site_id, expires_at}."""
from datetime import timedelta
from core import support_codes
from core.timeutil import utcnow
from models.support_challenge import SupportChallenge
_support_configured()
now = utcnow()
open_now = db.query(SupportChallenge).filter(SupportChallenge.used_at.is_(None), SupportChallenge.expires_at > now,
SupportChallenge.attempts < SUPPORT_MAX_ATTEMPTS).count()
if open_now >= SUPPORT_MAX_OPEN:
raise XeniaError("auth.support_rate_limited")
while True:
ch = support_codes.new_challenge()
if not db.query(SupportChallenge).filter(SupportChallenge.challenge == ch).first():
break
row = SupportChallenge(challenge=ch, created_at=now, expires_at=now + timedelta(minutes=SUPPORT_CHALLENGE_TTL_MIN),
ip=request.headers.get("x-real-ip") or (request.client.host if request.client else None),
user_agent=request.headers.get("user-agent", "")[:300])
db.add(row)
db.commit()
_logger.info("support.challenge id=%s", row.id)
return {"challenge": support_codes.group(ch, 4), "site_id": settings.SITE_ID, "expires_at": iso_z(row.expires_at)}
@router.post("/support/verify", response_model=TokenResponse, dependencies=[Depends(public())])
def support_verify(body: SupportVerifyRequest, request: Request, db: Session = Depends(get_db)):
"""The builder's code for a challenge -> a support session (4 h, single use per challenge)."""
import hmac as _hmac
from datetime import timedelta
from core import support_codes
from core.timeutil import utcnow
from models.support_challenge import SupportChallenge
_support_configured()
now = utcnow()
row = db.query(SupportChallenge).filter(
SupportChallenge.challenge == support_codes.normalize_challenge(body.challenge)).first()
if row is None or row.used_at is not None or row.expires_at <= now or row.attempts >= SUPPORT_MAX_ATTEMPTS:
raise XeniaError("auth.support_code_invalid")
expected = support_codes.code_for(settings.SUPPORT_SECRET, settings.SITE_ID, row.challenge)
if not _hmac.compare_digest(expected, support_codes.normalize_code(body.code)):
row.attempts += 1
db.commit()
_logger.warning("support.code_wrong challenge=%s attempts=%s", row.id, row.attempts)
raise XeniaError("auth.support_code_invalid")
support = make_support_user()
session = sessions.start(db, support, "support", request, expires_at=now + timedelta(hours=SUPPORT_SESSION_HOURS))
row.used_at = now
row.session_id = session.id
db.commit()
_logger.warning("support.access_used challenge=%s sid=%s ip=%s", row.id, session.id[:8], session.ip)
from core.notifications import notify
notify("support.access_used", "warning", "perm:core.settings.manage", {"ip": session.ip or "?"},
dedupe_key=f"support.access_used:{row.id}", db=db)
return TokenResponse(access_token=make_token(support, session.id, hours=SUPPORT_SESSION_HOURS),
user=UserOut.model_validate(support))
# ── Sessions (D-9): who is logged in where ─────────────────────────────────
def _session_out(s, users: dict, devices: dict, current_sid) -> dict:
u = users.get(s.user_id)
d = devices.get(s.device_id)
return {"id": s.id, "user_id": s.user_id, "username": u.username if u else ("support" if s.client == "support" else None),
"full_name": u.full_name if u else None, "client": s.client, "device_id": s.device_id,
"device_name": d.name if d else None, "device_app": d.app_key if d else None,
"current": s.id == current_sid,
"created_at": iso_z(s.created_at), "last_seen_at": iso_z(s.last_seen_at), "expires_at": iso_z(s.expires_at),
"ended_at": iso_z(s.ended_at), "end_reason": s.end_reason, "ip": s.ip, "user_agent": s.user_agent}
@router.get("/sessions")
def list_sessions(request: Request, include_ended: bool = False, db: Session = Depends(get_db),
user: User = Depends(require("core.staff.manage"))):
"""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))
rows = q.order_by(LoginSession.created_at.desc()).limit(200).all()
users = {u.id: u for u in db.query(User).filter(User.id.in_({r.user_id for r in rows if r.user_id})).all()}
devices = {d.id: d for d in db.query(Device).filter(Device.id.in_({r.device_id for r in rows if r.device_id})).all()}
return [_session_out(r, users, devices, getattr(request.state, "xenia_sid", None)) for r in rows]
@router.post("/sessions/{sid}/end")
def end_session(sid: str, db: Session = Depends(get_db), user: User = Depends(require("core.staff.manage"))):
target = db.get(LoginSession, sid)
if target is None:
raise XeniaError("auth.session_not_found")
if target.client == "support" and user.role != "superadmin":
raise XeniaError("access.denied", key="core.system.admin")
sessions.end(db, sid, "ended_by_manager")
return {"ok": True}
@router.get("/me", response_model=UserOut)
def me(user: User = Depends(get_current_user)):
return user
# ─── Public manager list (login screen — no auth required) ───────────────────
class PublicManagerOut(_PydanticBase):
id: int
username: str
full_name: str | None
model_config = {"from_attributes": True}
@router.get("/managers", response_model=list[PublicManagerOut], dependencies=[Depends(public())])
def public_manager_list(db: Session = Depends(get_db)):
"""Public endpoint — returns accounts with dashboard access for login screen."""
managers = db.query(User).filter(
holders_filter("core.dashboard.access"),
User.is_active == True,
).all()
return [PublicManagerOut(id=m.id, username=m.username, full_name=m.full_name) for m in managers]
# ─── Public waiter list (login screen — no auth required) ────────────────────
from pydantic import BaseModel as _BaseModel
class PublicWaiterOut(_BaseModel):
id: int
full_name: str | None
nickname: str | None
avatar_url: str | None
on_shift: bool
model_config = {"from_attributes": True}
@router.get("/waiters", response_model=list[PublicWaiterOut], dependencies=[Depends(public())])
def public_waiter_list(db: Session = Depends(get_db)):
"""Public endpoint — returns active waiters with on-shift flag. No auth required."""
from models.shift import WaiterShift
waiters = db.query(User).filter(holders_filter("waiter_app.access"), User.is_active == True).all()
on_shift_ids = {
row.waiter_id
for row in db.query(WaiterShift).filter(WaiterShift.ended_at == None).all()
}
return [
PublicWaiterOut(
id=w.id,
full_name=w.full_name,
nickname=w.nickname,
avatar_url=w.avatar_url,
on_shift=w.id in on_shift_ids,
)
for w in waiters
]
@router.patch("/me", response_model=UserOut)
def update_me(body: UpdateMeRequest, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
# Password change — requires current_password verification
if body.new_password is not None:
if not body.current_password:
raise XeniaError("auth.password_current_required")
if not user.password_hash:
raise XeniaError("auth.no_password")
if not bcrypt.checkpw(body.current_password.encode(), user.password_hash.encode()):
raise XeniaError("auth.password_wrong")
if len(body.new_password) < 6:
raise XeniaError("auth.password_too_short", min=6)
user.password_hash = bcrypt.hashpw(body.new_password.encode(), bcrypt.gensalt()).decode()
# PIN change — no current PIN required (already authenticated)
if body.new_pin is not None:
if len(body.new_pin) < 4:
raise XeniaError("auth.pin_too_short", min=4)
user.pin_hash = bcrypt.hashpw(body.new_pin.encode(), bcrypt.gensalt()).decode()
# Username change — check uniqueness
if body.username is not None and body.username != user.username:
conflict = db.query(User).filter(User.username == body.username, User.id != user.id).first()
if conflict:
raise XeniaError("staff.username_taken")
user.username = body.username
# Display name
if body.full_name is not None:
user.full_name = body.full_name
# Personal language (D-12); "" = inherit
if body.language is not None:
user.language = normalize_language(body.language)
db.commit()
db.refresh(user)
return user
class WaiterSettingsPayload(_PydanticBase):
settings: str # raw JSON string
@router.get("/me/settings")
def get_my_settings(user: User = Depends(get_current_user)):
"""Return the stored waiter settings JSON blob for the current user."""
return {"settings": user.waiter_settings or "{}"}
@router.put("/me/settings")
def put_my_settings(body: WaiterSettingsPayload, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Replace the stored waiter settings JSON blob."""
import json as _json
try:
_json.loads(body.settings) # validate it's valid JSON
except Exception:
raise XeniaError("settings.invalid_json")
user.waiter_settings = body.settings
db.commit()
return {"settings": user.waiter_settings}