Files
webhook/middleware.py

38 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""鉴权中间件:校验请求中的 API Key。"""
import uuid
from aiohttp import web
from .config import WEBHOOK_API_KEY
from .response import error
@web.middleware
async def auth_middleware(request: web.Request, handler):
"""对 /upload 和 /webhook 路径强制校验 API Key。"""
# 健康检查不需要鉴权
if request.path == "/healthz":
return await handler(request)
auth_header = request.headers.get("Authorization", "")
if auth_header.startswith("Bearer "):
key = auth_header[len("Bearer "):]
else:
key = request.headers.get("X-API-Key", "")
if key != WEBHOOK_API_KEY:
return error("unauthorized", code=401, status=401)
return await handler(request)
@web.middleware
async def request_id_middleware(request: web.Request, handler):
"""为每个请求附加唯一 request_id便于日志追踪。"""
request_id = request.headers.get("X-Request-ID", uuid.uuid4().hex[:12])
request["request_id"] = request_id
response = await handler(request)
response.headers["X-Request-ID"] = request_id
return response