- 添加用户登录、登出及令牌管理功能 - 实现基于JWT和Redis的认证系统 - 完善用户和角色管理API - 添加密码加密与验证功能 - 配置数据库连接和Redis客户端 - 实现中间件进行权限验证 - 初始化管理员和测试用户数据 - 更新模型和接口文档 - 添加测试API和配置文件
41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
import redis.asyncio as redis
|
|
from config import redis_settings
|
|
|
|
# 创建Redis连接池
|
|
redis_pool = redis.ConnectionPool.from_url(
|
|
redis_settings.url,
|
|
decode_responses=True
|
|
)
|
|
|
|
|
|
async def get_redis():
|
|
"""获取Redis连接"""
|
|
async with redis.Redis(connection_pool=redis_pool) as conn:
|
|
try:
|
|
yield conn
|
|
finally:
|
|
await conn.close()
|
|
|
|
|
|
async def set_token_in_redis(redis_conn, user_id: int, token: str, expire_seconds: int):
|
|
"""将令牌存储到Redis"""
|
|
key = f"user:token:{user_id}"
|
|
await redis_conn.set(key, token, ex=expire_seconds)
|
|
|
|
|
|
async def get_token_from_redis(redis_conn, user_id: int):
|
|
"""从Redis获取令牌"""
|
|
key = f"user:token:{user_id}"
|
|
return await redis_conn.get(key)
|
|
|
|
|
|
async def delete_token_from_redis(redis_conn, user_id: int):
|
|
"""从Redis删除令牌"""
|
|
key = f"user:token:{user_id}"
|
|
await redis_conn.delete(key)
|
|
|
|
|
|
async def check_token_in_redis(redis_conn, user_id: int, token: str):
|
|
"""检查令牌是否在Redis中且有效"""
|
|
stored_token = await get_token_from_redis(redis_conn, user_id)
|
|
return stored_token == token |