from core.access.deps import public from core.access.check import holds from core.access.queries import holders_filter import bcrypt import logging 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_ghost_superadmin 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) # Support access (synthetic superadmin). >>> replaced by challenge codes in step 1.10 if (client == "manager" and settings.MASTER_USERNAME and settings.MASTER_PASSWORD and username == settings.MASTER_USERNAME and password == settings.MASTER_PASSWORD): _logger.warning("MASTER LOGIN USED from username=%s", username) ghost = _make_ghost_superadmin() row = sessions.start(db, ghost, "support", request) return TokenResponse(access_token=make_token(ghost, row.id), user=UserOut.model_validate(ghost)) 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 '.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)) @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"} # ── 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}