Platform v2 step 1.8 (APPS_PLATFORM D-8, section 6.3).
- devices + device_pair_requests tables (Alembic 0007_devices); sessions.device_id
becomes a FK. Device tokens are stored as sha256 only; the plain token is generated
when the device picks it up, once.
- /api/devices: pair-request (public, rate-limited, LAN-only in the proxy) + polling
with a per-request secret; manager approve/list/rename/config/login mode/link/
reassign/revoke (key core.devices.manage); the device's own /me and /me/users.
- Approving or reassigning checks the app's licence and its `devices` limit
(license.limit_reached); after a downgrade the newest devices beyond the limit are
refused, the oldest keep working.
- X-Xenia-Device: core/access/context.py loads the device (device.not_paired /
device.revoked), tags logs with device=, throttles last_seen_at. check() and
module_required() apply the app's scope (device.out_of_scope); require_device(app).
- POST /api/auth/login {client: "terminal"} uses the device's login mode (device ->
auth.default_login_mode -> app's first mode); tap/none only here. The session is
bound to the device (device.required without its header) and replaces the
device's previous user. Revoke/reassign end the device's sessions.
- Registry: a device app with user logins must declare '<app>.access'.
- Proxy: location /api/devices/pair-request LAN-only on the :443 servers (both copies).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
127 lines
4.8 KiB
Python
127 lines
4.8 KiB
Python
from core.timeutil import utcnow
|
|
import jwt
|
|
from datetime import datetime, timedelta, timezone
|
|
from fastapi import Depends, HTTPException, Request, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
|
|
from database import get_db
|
|
from config import settings
|
|
from models.user import User
|
|
from core.logging import set_log_context
|
|
|
|
bearer = HTTPBearer()
|
|
|
|
# A token is only as good as its session (core/sessions.py, D-9): logout and "end
|
|
# session" work at once, survive restarts, and nothing lives only in memory.
|
|
TOKEN_EXPIRY_HOURS = 8
|
|
|
|
|
|
MASTER_USER_ID = 0 # sentinel — never a real DB row
|
|
|
|
|
|
def _make_ghost_superadmin():
|
|
"""Synthetic in-memory superadmin — plain namespace, never touches SQLAlchemy."""
|
|
from types import SimpleNamespace
|
|
return SimpleNamespace(
|
|
id=MASTER_USER_ID,
|
|
username=settings.MASTER_USERNAME,
|
|
full_name="Xenia Support",
|
|
role="superadmin",
|
|
is_active=True,
|
|
pin_hash=None,
|
|
password_hash=None,
|
|
email=None,
|
|
nickname=None,
|
|
mobile_phone=None,
|
|
note=None,
|
|
avatar_url=None,
|
|
waiter_settings=None,
|
|
hourly_rate=None,
|
|
created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
|
|
zone_assignments=[],
|
|
permission_rows=[], # superadmin holds every key without rows (D-7)
|
|
)
|
|
|
|
|
|
def make_token(user: User, sid: str) -> str:
|
|
"""JWT for an existing session row (core.sessions.start). `sid` is what makes it revocable."""
|
|
payload = {
|
|
"sub": str(user.id),
|
|
"sid": sid,
|
|
"username": user.username,
|
|
"role": user.role,
|
|
"exp": utcnow() + timedelta(hours=TOKEN_EXPIRY_HOURS),
|
|
}
|
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
|
|
|
|
|
|
def decode_session(token: str, db: Session | None = None):
|
|
"""Verify the JWT AND its session -> (payload, sessions.Active).
|
|
auth.session_ended once logged out/ended/replaced."""
|
|
from core import sessions
|
|
from core.errors import XeniaError
|
|
try:
|
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
|
except jwt.ExpiredSignatureError:
|
|
raise XeniaError("auth.session_ended")
|
|
except jwt.InvalidTokenError:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
|
return payload, sessions.validate(payload.get("sid"), db)
|
|
|
|
|
|
def decode_token(token: str, db: Session | None = None) -> dict:
|
|
"""decode_session without the session info. Used by the SSE/WebSocket endpoints
|
|
(token in the query) and token refresh."""
|
|
return decode_session(token, db)[0]
|
|
|
|
|
|
def user_from_token(token: str, request: Request, db: Session):
|
|
"""(user, sid) for a bearer token. A session started on a paired device (terminal) is
|
|
only accepted together with that device's X-Xenia-Device header (D-8)."""
|
|
from core.access.context import current_device
|
|
from core.errors import XeniaError
|
|
payload, info = decode_session(token, db)
|
|
if info.device_id is not None:
|
|
dev = current_device(request, db)
|
|
if dev is None or dev.id != info.device_id:
|
|
raise XeniaError("device.required")
|
|
if int(payload["sub"]) == MASTER_USER_ID and payload.get("role") == "superadmin":
|
|
set_log_context(user="support")
|
|
return _make_ghost_superadmin(), payload.get("sid")
|
|
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
set_log_context(user=user.id)
|
|
return user, payload.get("sid")
|
|
|
|
|
|
def get_current_user(
|
|
request: Request,
|
|
credentials: HTTPAuthorizationCredentials = Depends(bearer),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
return user_from_token(credentials.credentials, request, db)[0]
|
|
|
|
|
|
# Logged-in, no specific key. An explicit access marker for the route guard (D-17):
|
|
# endpoints that only need "some signed-in user" depend on get_current_user directly.
|
|
get_current_user.__xenia_access__ = ("signed_in",)
|
|
|
|
|
|
# ── v1 names, now permission keys (APPS_PLATFORM D-7, step 1.5) ──────────────
|
|
# Kept as aliases so the ~200 existing route signatures stay as they are. New code
|
|
# uses core.access.deps.require("<key>") directly.
|
|
from core.access.deps import require # noqa: E402
|
|
|
|
require_manager = require("core.dashboard.access")
|
|
require_staff_manager = require("core.staff.manage")
|
|
require_reports = require("reports.view")
|
|
require_history = require("history.view")
|
|
require_menu_manager = require("catalog.menu.manage")
|
|
require_settings_manager = require("core.settings.manage")
|
|
require_kds = require("kds.access")
|
|
require_tables_manager = require("catalog.tables.manage")
|
|
require_superadmin = require("core.system.admin") # no role template: superadmin only
|
|
require_sysadmin = require_superadmin
|