Files
DecomEval/backend/app/api/deps.py
T

30 lines
888 B
Python

from __future__ import annotations
from dataclasses import dataclass
from fastapi import Header, HTTPException
from app.security import read_token
@dataclass
class Actor:
kind: str
id: str
role: str
name: str
def current_actor(authorization: str | None = Header(default=None)) -> Actor:
if not authorization or not authorization.lower().startswith("bearer "):
raise HTTPException(status_code=401, detail="请先登录")
body = read_token(authorization.split(" ", 1)[1].strip())
if body is None:
raise HTTPException(status_code=401, detail="登录已失效")
return Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
def require_admin(actor: Actor) -> None:
if actor.role != "admin":
raise HTTPException(status_code=403, detail="需要管理员")