dependencies.py 1.3 KB

123456789101112131415161718192021222324252627282930
  1. """读取会话与写事务分开,AI 测试等慢请求不能占住数据库写锁。"""
  2. from fastapi import Depends
  3. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  4. from app.infrastructure.database import Session, transaction
  5. from app.infrastructure.security import decode_access, public_user
  6. from app.domain.models import User
  7. from app.shared.common import BusinessError
  8. async def read_db():
  9. async with Session() as session:
  10. yield session
  11. async def write_db():
  12. async with transaction() as session:
  13. yield session
  14. bearer = HTTPBearer(auto_error=False, description="登录返回 access_token,Swagger Authorize 只填令牌值")
  15. async def current_user(credentials: HTTPAuthorizationCredentials | None = Depends(bearer), session=Depends(read_db)) -> dict:
  16. """访问每次检查数据库 active 与角色,停用用户不用等 JWT 自然过期。"""
  17. if credentials is None or credentials.scheme.lower() != "bearer" or not credentials.credentials:
  18. raise BusinessError("请先登录", 401, "AUTH_REQUIRED")
  19. user = await session.get(User, decode_access(credentials.credentials))
  20. if not user or not user.active:
  21. raise BusinessError("账号不存在或已停用", 401, "USER_DISABLED")
  22. return await public_user(session, user)