39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Optional API key gate for mutating routes (DY_API_KEY)."""
|
||
from __future__ import annotations
|
||
|
||
from starlette.middleware.base import BaseHTTPMiddleware
|
||
from starlette.requests import Request
|
||
from starlette.responses import JSONResponse
|
||
|
||
from .config import settings
|
||
|
||
# OAuth redirect + SSE + static covers — never block
|
||
_PUBLIC_PATHS = {
|
||
"/api/shorts/oauth/callback",
|
||
"/api/events/stream",
|
||
}
|
||
|
||
|
||
class ApiKeyMiddleware(BaseHTTPMiddleware):
|
||
async def dispatch(self, request: Request, call_next):
|
||
required = str(settings.api_key or "").strip()
|
||
if not required:
|
||
return await call_next(request)
|
||
|
||
path = request.url.path
|
||
if path in _PUBLIC_PATHS or path.startswith("/covers/"):
|
||
return await call_next(request)
|
||
if request.method in {"GET", "HEAD", "OPTIONS"}:
|
||
return await call_next(request)
|
||
|
||
provided = (
|
||
request.headers.get("X-API-Key")
|
||
or request.headers.get("x-api-key")
|
||
or request.query_params.get("api_key")
|
||
or ""
|
||
).strip()
|
||
if provided != required:
|
||
return JSONResponse({"detail": "需要 API Key(请求头 X-API-Key)"}, status_code=401)
|
||
return await call_next(request)
|