41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from fastapi import Header, HTTPException, Request
|
|
|
|
from app.auth.platform import platform_identity
|
|
from app.security import read_token
|
|
|
|
|
|
@dataclass
|
|
class Actor:
|
|
kind: str
|
|
id: str
|
|
role: str
|
|
name: str
|
|
|
|
|
|
def current_actor(request: Request, 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="登录已失效")
|
|
actor = Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
|
|
if actor.kind == "platform":
|
|
_check_platform(request, actor)
|
|
return actor
|
|
|
|
|
|
def _check_platform(request: Request, actor: Actor) -> None:
|
|
"""平台账号的令牌跟随平台登录:换人、退出或角色变化后即失效。"""
|
|
identity = platform_identity(request.headers)
|
|
if identity is None or identity.user_id != actor.id or identity.role != actor.role or actor.role != "admin":
|
|
raise HTTPException(status_code=401, detail="平台登录已变化,请重新进入")
|
|
|
|
|
|
def require_admin(actor: Actor) -> None:
|
|
if actor.role != "admin":
|
|
raise HTTPException(status_code=403, detail="需要管理员")
|