This commit is contained in:
Felix
2025-12-05 20:41:51 +08:00
parent 28ee12ca72
commit aafbbbd895
3 changed files with 8 additions and 7 deletions

View File

@@ -69,26 +69,19 @@ class CustomHTTPBearer(HTTPBearer):
# Check for x-wx-openid header first (WeChat Cloud Hosting authentication)
wx_openid = request.headers.get('x-wx-openid')
# print(request.headers)
# print(wx_openid)
if not wx_openid:
wx_openid = request.headers.get('X-WX-OPENID')
if wx_openid:
# Handle WeChat Cloud Hosting authentication
wx_unionid = request.headers.get('x-wx-unionid')
if not wx_unionid:
wx_unionid = request.headers.get('X-WX-UNIONID')
try:
# Check if we have a cached token for this openid
cached_token = await redis_client.get(f'wx_openid_token:{wx_openid}')
if cached_token:
# Verify the cached token is still valid via standard flow
try:
await jwt_authentication(cached_token)
return HTTPAuthorizationCredentials(scheme="Bearer", credentials=cached_token)
except Exception:
# If token is invalid, remove it from cache and recreate below
await redis_client.delete(f'wx_openid_token:{wx_openid}')
# If no cached token or invalid token, authenticate the user

View File

@@ -38,6 +38,7 @@ async def register_init(app: FastAPI):
await create_table()
# 连接 redis
await redis_client.open()
# await redis_client.refresh_all()
# 初始化 limiter
await FastAPILimiter.init(
redis_client,

View File

@@ -59,6 +59,13 @@ class RedisCli(Redis):
if keys:
await self.delete(*keys)
async def refresh_all(self):
try:
await self.flushall()
except Exception as e:
log.error('❌ 数据库 redis 刷新异常 {}', e)
raise
# 创建 redis 客户端单例
redis_client: RedisCli = RedisCli()