Files
xenia-pos-local/local_backend/routers/auth.py
T
bonaminandClaude Opus 5.5 49a412d748 feat(manager): v2 sign-in (login modes, support access, license notice) and an unlock endpoint for the lock screen
Platform-v2 step 2.6b:
- backend: POST /api/auth/unlock {pin|password} checks the CURRENT session's
  user and keeps the session (no new login/token); 5 wrong tries end it
  (auth.wrong_pin with attempts_left, then auth.session_ended); bootstrap
  gains `login` (manager_mode, autofill_username, support)
- manager LoginPage rewritten on @xenia/ui + i18n: client "manager", password
  or PIN pad per setting, remembered/only account card, support access panel
  (challenge -> code -> 4 h session, not remembered as an account), notice
  when the license runs the free tier (expired/inactive/locked/clock/unverified)
- lock screen on /api/auth/unlock with the shared PinPad
- @xenia/ui PinPad: variable length (minLength/maxLength, OK key, Enter)
- e2e manager.mjs: 33 checks (+ lockout after 5 wrong PINs, PIN login mode,
  support access with a wrong then right code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:17:09 +02:00

432 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, HTTPException, 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__)
class LoginByIdRequest(_PydanticBase):
waiter_id: int
pin: str
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, legacy: bool = False) -> 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 not legacy: # the current manager UI (no `client`) keeps v1 behaviour: pin or password
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, legacy_manager=legacy and client == "manager")
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.
Without `client` (the current manager UI): a manager login with v1 rules (pin or password)."""
return do_login(db, request, client=body.client or "manager", username=body.username,
user_id=body.user_id, pin=body.pin, password=body.password, legacy=body.client is None)
@router.post("/login-by-id", response_model=TokenResponse, dependencies=[Depends(public())], deprecated=True)
def login_by_id(body: LoginByIdRequest, request: Request, db: Session = Depends(get_db)):
"""DEPRECATED (current waiter app): = POST /login {client: "waiter", user_id, pin}. Removed in phase 4."""
return do_login(db, request, client="waiter", username=None, user_id=body.waiter_id, pin=body.pin, password=None)
@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) -> dict:
u = users.get(s.user_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,
"created_at": iso_z(s.created_at), "last_seen_at": iso_z(s.last_seen_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(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."""
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()}
return [_session_out(r, users) 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 HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="current_password is required to set a new password")
if not user.password_hash:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Account has no password set")
if not bcrypt.checkpw(body.current_password.encode(), user.password_hash.encode()):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Current password is incorrect")
if len(body.new_password) < 6:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="New password must be at least 6 characters")
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 HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="PIN must be at least 4 digits")
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 HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already 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 HTTPException(status_code=422, detail="settings must be valid JSON")
user.waiter_settings = body.settings
db.commit()
return {"settings": user.waiter_settings}