douyinWEB/backend/app/auth.py
eric 9806ed3a0a feat: X2 推送接入 API 与 /x 实时看板
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 23:39:41 -05:00

59 lines
1.9 KiB
Python
Raw 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.

# -*- coding: utf-8 -*-
"""Optional API key gate for mutating routes (DY_API_KEY)."""
from __future__ import annotations
from starlette.datastructures import Headers, QueryParams
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from .config import settings
# OAuth redirect + SSE + static covers — never block
_PUBLIC_PATHS = {
"/api/shorts/oauth/callback",
"/api/tiktok/oauth/callback/",
"/api/tiktok/oauth/callback",
"/api/events/stream",
"/api/x2/ingest",
}
class ApiKeyMiddleware:
"""Pure ASGI middleware — avoid BaseHTTPMiddleware (deadlocks SSE/streaming)."""
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
required = str(settings.api_key or "").strip()
if not required:
await self.app(scope, receive, send)
return
path = scope.get("path") or ""
method = (scope.get("method") or "GET").upper()
if path in _PUBLIC_PATHS or path.startswith("/covers/"):
await self.app(scope, receive, send)
return
if method in {"GET", "HEAD", "OPTIONS"}:
await self.app(scope, receive, send)
return
headers = Headers(scope=scope)
qs = QueryParams((scope.get("query_string") or b"").decode("latin-1"))
provided = (
headers.get("X-API-Key")
or headers.get("x-api-key")
or qs.get("api_key")
or ""
).strip()
if provided != required:
resp = JSONResponse({"detail": "需要 API Key(请求头 X-API-Key)"}, status_code=401)
await resp(scope, receive, send)
return
await self.app(scope, receive, send)