- 添加用户登录、登出及令牌管理功能 - 实现基于JWT和Redis的认证系统 - 完善用户和角色管理API - 添加密码加密与验证功能 - 配置数据库连接和Redis客户端 - 实现中间件进行权限验证 - 初始化管理员和测试用户数据 - 更新模型和接口文档 - 添加测试API和配置文件
46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
from fastapi import Request, HTTPException, status, Depends
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
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
|
|
user = await db.query(User).filter(User.id == user_id).first()
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="用户不存在"
|
|
)
|
|
|
|
return user |