- 重构用户和角色模型,优化字段定义和关系 - 增强初始化数据脚本,支持数据更新检查 - 改进用户和角色API端点,增加验证逻辑 - 扩展Pydantic模型,分离请求和响应模式 - 自定义Swagger UI界面并优化API文档 - 移除测试文件并更新依赖项配置
52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
from fastapi import Request, HTTPException, status, Depends
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
import redis.asyncio as redis
|
|
|
|
from database import get_db
|
|
from utils.jwt import decode_token
|
|
from utils.redis_client import get_redis, check_token_in_redis
|
|
|
|
security = HTTPBearer()
|
|
|
|
|
|
async def get_current_user(
|
|
request: Request,
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
db: AsyncSession = Depends(get_db),
|
|
redis_conn: redis.Redis = Depends(get_redis),
|
|
):
|
|
"""获取当前用户"""
|
|
token = credentials.credentials
|
|
|
|
# 解码令牌
|
|
payload = decode_token(token)
|
|
if not payload:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="无效的认证凭据",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
user_id = int(payload.get("sub"))
|
|
|
|
# 检查令牌是否在Redis中
|
|
is_valid = await check_token_in_redis(redis_conn, user_id, token)
|
|
if not is_valid:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="令牌已过期或已登出",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
# 查找用户
|
|
from models import User
|
|
|
|
result = await db.execute(select(User).filter(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
|
|
|
|
return user
|