36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
|
|
from fastapi import Header, HTTPException
|
||
|
|
|
||
|
|
from app.config import settings
|
||
|
|
from app.dependencies import get_store
|
||
|
|
from app.store import User
|
||
|
|
|
||
|
|
|
||
|
|
def require_user(authorization: str | None = Header(default=None)) -> User:
|
||
|
|
"""FastAPI-Dependency: liefert den authentifizierten Nutzer.
|
||
|
|
|
||
|
|
Bei AUTH_ENABLED=false gilt ein anonymer Standardnutzer (dev/Test). Sonst ist
|
||
|
|
ein gueltiges Bearer-Token noetig (sonst 401).
|
||
|
|
"""
|
||
|
|
store = get_store()
|
||
|
|
if not settings.auth_enabled:
|
||
|
|
return store.ensure_anonymous_user()
|
||
|
|
|
||
|
|
if not authorization or not authorization.lower().startswith("bearer "):
|
||
|
|
raise HTTPException(status_code=401, detail="Bearer token required")
|
||
|
|
|
||
|
|
token = authorization.split(" ", 1)[1].strip()
|
||
|
|
user = store.get_user_by_token(token)
|
||
|
|
if user is None:
|
||
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|
||
|
|
return user
|
||
|
|
|
||
|
|
|
||
|
|
def require_admin(x_admin_key: str | None = Header(default=None)) -> None:
|
||
|
|
"""Schuetzt die Nutzerverwaltung ueber ADMIN_API_KEY (aus der Umgebung)."""
|
||
|
|
expected = settings.admin_api_key.strip()
|
||
|
|
if not expected:
|
||
|
|
raise HTTPException(
|
||
|
|
status_code=503, detail="Admin API not configured (ADMIN_API_KEY unset)"
|
||
|
|
)
|
||
|
|
if not x_admin_key or x_admin_key.strip() != expected:
|
||
|
|
raise HTTPException(status_code=401, detail="Invalid admin key")
|