douyinWEB/backend/app/auth.py
eric 57690bd286 feat: Web /x 控制台下发任务,插件自动配对领取执行
插件 X popup 保持可独立运行;打开本站即可自动配对,无需手填 Token。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 00:14:25 -05:00

60 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",
"/api/x2/extension/poll",
}
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)