mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 05:39:20 +08:00
- models.py: add VALID_ROLES + normalize_role as the single source of truth - identity.py: route _canonical_record/_migrate_legacy_users/load_users/set_role through normalize_role - context.py: token payload role mapping via normalize_role - services/auth.py + api/routers/auth.py: set_role guards validate against VALID_ROLES - tests/multi_user/test_role_normalization.py: 16 tests, first set_role coverage in repo Zero behavior change: legal roles pass through; unknown values keep the same least-privilege degrade path; only guard error strings derived from sorted(VALID_ROLES) differ.
44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
"""Request-local current user context."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextvars import ContextVar, Token
|
|
from typing import Any
|
|
|
|
from .models import CurrentUser, normalize_role
|
|
from .paths import local_admin_user, scope_for_user
|
|
|
|
_current_user: ContextVar[CurrentUser | None] = ContextVar("deeptutor_current_user", default=None)
|
|
|
|
|
|
def set_current_user(user: CurrentUser) -> Token[CurrentUser | None]:
|
|
return _current_user.set(user)
|
|
|
|
|
|
def reset_current_user(token: Token[CurrentUser | None]) -> None:
|
|
_current_user.reset(token)
|
|
|
|
|
|
def get_current_user() -> CurrentUser:
|
|
return _current_user.get() or local_admin_user()
|
|
|
|
|
|
def get_current_user_or_none() -> CurrentUser | None:
|
|
return _current_user.get()
|
|
|
|
|
|
def user_from_token_payload(payload: Any | None) -> CurrentUser:
|
|
if payload is None:
|
|
return local_admin_user()
|
|
user_id = str(getattr(payload, "user_id", "") or "")
|
|
username = str(getattr(payload, "username", "") or "local")
|
|
role = normalize_role(str(getattr(payload, "role", "user") or "user"))
|
|
if not user_id:
|
|
user_id = "local-admin" if role == "admin" and username == "local" else username
|
|
return CurrentUser(
|
|
id=user_id,
|
|
username=username,
|
|
role=role, # type: ignore[arg-type]
|
|
scope=scope_for_user(user_id, is_admin=role == "admin"),
|
|
)
|