145 lines
5.0 KiB
Python
145 lines
5.0 KiB
Python
"""FastAPI 依赖:登录态、权限判定、数据范围。
|
|
|
|
接口鉴权只认权限码,因此加新页面不用改网关配置,删权限也不用改代码。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from typing import Annotated
|
|
|
|
from fastapi import Depends, Request
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from .db import get_session
|
|
from .envelope import forbidden, unauthorized
|
|
from .models import Account, Project, Status
|
|
from .security import TokenError, decode_token
|
|
from .service import data_scope, permissions
|
|
|
|
DbSession = Annotated[Session, Depends(get_session)]
|
|
|
|
|
|
def client_ip(request: Request) -> str:
|
|
"""访客 IP。过了反代以后 ``request.client`` 只会是代理的地址,先认 ``X-Forwarded-For``。
|
|
|
|
登录日志、审计、免登失败告警都要用它定位是谁在试,所以放在这里共用一份,
|
|
不在每个 API 模块里各抄一遍——抄多了迟早有一处忘了认反向代理头。
|
|
"""
|
|
forwarded = request.headers.get("X-Forwarded-For")
|
|
if forwarded:
|
|
return forwarded.split(",")[0].strip()
|
|
return request.client.host if request.client else ""
|
|
|
|
|
|
def _bearer(request: Request) -> str:
|
|
header = request.headers.get("Authorization") or ""
|
|
if header.lower().startswith("bearer "):
|
|
return header[7:].strip()
|
|
token = request.cookies.get("pms_token") or request.query_params.get("token") or ""
|
|
return token.strip()
|
|
|
|
|
|
def current_account(db: DbSession, request: Request) -> Account:
|
|
token = _bearer(request)
|
|
if not token:
|
|
raise unauthorized("请先登录")
|
|
try:
|
|
payload = decode_token(token)
|
|
except TokenError as exc:
|
|
raise unauthorized(str(exc)) from exc
|
|
|
|
account = db.get(Account, int(payload.get("sub") or 0))
|
|
if account is None or account.is_deleted:
|
|
raise unauthorized("账号不存在或已被删除")
|
|
if not Status.is_active(account.status):
|
|
raise unauthorized(f"账号已{Status.label(account.status)},请联系管理员")
|
|
|
|
request.state.account = account
|
|
return account
|
|
|
|
|
|
CurrentUser = Annotated[Account, Depends(current_account)]
|
|
|
|
|
|
@dataclass
|
|
class Principal:
|
|
"""当前人的"账号 + 授权视图 + 数据范围上下文",一个依赖搞定三层鉴权所需的东西。"""
|
|
|
|
account: Account
|
|
permission: permissions.PermissionContext
|
|
scope: data_scope.ScopeContext
|
|
|
|
|
|
def principal(db: DbSession, account: CurrentUser) -> Principal:
|
|
cached: Principal | None = getattr(db, "_pms_principal", None)
|
|
if cached is not None and cached.account.id == account.id:
|
|
return cached
|
|
built = Principal(
|
|
account=account,
|
|
permission=permissions.build_context(db, account),
|
|
scope=data_scope.build_scope_context(db, account),
|
|
)
|
|
try:
|
|
db._pms_principal = built # type: ignore[attr-defined]
|
|
except Exception: # pragma: no cover - 极少数 Session 实现不允许挂属性
|
|
pass
|
|
return built
|
|
|
|
|
|
PrincipalOf = Annotated[Principal, Depends(principal)]
|
|
|
|
|
|
def require(code: str, *also: str):
|
|
"""接口级权限。``@require("project:budget:edit")``。"""
|
|
wanted = (code, *also)
|
|
|
|
def dependency(current: PrincipalOf) -> Principal:
|
|
if not current.permission.can_any(wanted):
|
|
raise forbidden(f"缺少权限:{' 或 '.join(wanted)}")
|
|
return current
|
|
|
|
return Depends(dependency)
|
|
|
|
|
|
def data_filter(module: str):
|
|
"""把某模块的数据权限条件注到查询上。"""
|
|
|
|
def dependency(db: DbSession, current: PrincipalOf) -> data_scope.ScopeDecision:
|
|
return data_scope.evaluate(db, module, current.scope)
|
|
|
|
return Depends(dependency)
|
|
|
|
|
|
def scope_of(db: Session, current: Principal, module: str) -> data_scope.ScopeDecision:
|
|
return data_scope.evaluate(db, module, current.scope)
|
|
|
|
|
|
def assert_project_visible(db: Session, current: Principal, project_id: int,
|
|
module: str = "project", *,
|
|
allow_deleted: bool = False) -> Project:
|
|
"""单个对象的越权检查。
|
|
|
|
列表过滤挡不住"直接猜 ID 调详情"这条路,所以每个按 id 取项目的接口都要过这里。
|
|
判定方式和列表完全一致(同一份 :func:`data_scope.evaluate`),不会出现
|
|
"列表看不见但详情打得开"。
|
|
|
|
``allow_deleted=True`` 只给回收站用(删除确认与恢复):软删除的项目对业务接口
|
|
一律当作不存在,但对"把它救回来"这两条接口必须还得看得见。
|
|
"""
|
|
from .envelope import not_found
|
|
|
|
project = db.get(Project, project_id)
|
|
if project is None or (project.is_deleted and not allow_deleted):
|
|
raise not_found("项目不存在")
|
|
|
|
decision = data_scope.evaluate(db, module, current.scope)
|
|
if decision.unlimited:
|
|
return project
|
|
|
|
statement = decision.apply_to(select(Project.id).where(Project.id == project_id))
|
|
if db.execute(statement).first() is None:
|
|
raise forbidden("没有该项目的数据权限")
|
|
return project
|