douyinWEB/backend/app/session_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

186 lines
5.8 KiB
Python

# -*- coding: utf-8 -*-
"""Site-wide session login (cookie JWT)."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import secrets
import time
from typing import Any, Optional
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.types import ASGIApp, Receive, Scope, Send
from .config import settings
SESSION_COOKIE = "dy_session"
SESSION_TTL_SEC = 7 * 86400
# Unauthenticated API paths (OAuth callback, login itself)
_PUBLIC_API_PREFIXES = (
"/api/auth/login",
"/api/auth/status",
"/api/tiktok/oauth/callback/",
)
_PUBLIC_API_EXACT = {
"/api/health",
"/api/shorts/oauth/callback",
"/api/tiktok/oauth/callback/",
"/api/tiktok/oauth/callback",
"/api/events/stream",
"/api/x2/ingest",
"/api/x2/extension/poll",
}
def _secret() -> str:
s = str(settings.session_secret or "").strip()
if s:
return s
return "douyinweb-default-session-secret"
def hash_password(password: str) -> str:
return hashlib.sha256(f"{_secret()}:{password}".encode()).hexdigest()
def get_admin_credentials() -> tuple[str, str]:
"""Return (username, password_hash) from DB; seed from config on first use."""
from . import db
m = db.get_settings_map()
user = str(m.get("admin_username") or "").strip()
pw_hash = str(m.get("admin_password_hash") or "").strip()
if user and pw_hash:
return user, pw_hash
user = str(settings.admin_username or "hackrobot").strip()
pw_hash = hash_password(str(settings.admin_password or ""))
db.update_settings_map({"admin_username": user, "admin_password_hash": pw_hash})
return user, pw_hash
def verify_admin(username: str, password: str) -> bool:
user, pw_hash = get_admin_credentials()
if not secrets.compare_digest(str(username or ""), user):
return False
return secrets.compare_digest(hash_password(str(password or "")), pw_hash)
def change_admin_password(*, username: str, current_password: str, new_password: str) -> None:
from . import db
user, pw_hash = get_admin_credentials()
if not secrets.compare_digest(str(username or ""), user):
raise ValueError("无权限")
if not secrets.compare_digest(hash_password(str(current_password or "")), pw_hash):
raise ValueError("当前密码错误")
new_p = str(new_password or "")
if len(new_p) < 8:
raise ValueError("新密码至少 8 位")
db.update_settings_map({"admin_password_hash": hash_password(new_p)})
def create_session_token(username: str) -> str:
payload = {
"u": username,
"exp": int(time.time()) + SESSION_TTL_SEC,
}
body = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode().rstrip("=")
sig = hmac.new(_secret().encode(), body.encode(), hashlib.sha256).hexdigest()
return f"{body}.{sig}"
def verify_session_token(token: str) -> Optional[str]:
if not token or "." not in token:
return None
body, sig = token.rsplit(".", 1)
expected = hmac.new(_secret().encode(), body.encode(), hashlib.sha256).hexdigest()
if not secrets.compare_digest(sig, expected):
return None
pad = "=" * (-len(body) % 4)
try:
payload = json.loads(base64.urlsafe_b64decode(body + pad).decode())
except Exception:
return None
if int(payload.get("exp") or 0) < int(time.time()):
return None
user = str(payload.get("u") or "").strip()
return user or None
def session_user_from_request(request: Request) -> Optional[str]:
if not settings.auth_enabled:
return str(settings.admin_username or "admin")
token = (request.cookies.get(SESSION_COOKIE) or "").strip()
if not token:
auth = request.headers.get("Authorization") or ""
if auth.lower().startswith("bearer "):
token = auth[7:].strip()
return verify_session_token(token) if token else None
def set_session_cookie(response: Response, username: str, *, secure: bool) -> None:
token = create_session_token(username)
response.set_cookie(
key=SESSION_COOKIE,
value=token,
httponly=True,
secure=secure,
samesite="lax",
max_age=SESSION_TTL_SEC,
path="/",
)
def clear_session_cookie(response: Response) -> None:
response.delete_cookie(key=SESSION_COOKIE, path="/")
def _request_secure(request: Request) -> bool:
proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "http").split(",")[0].strip()
return proto == "https"
class SessionAuthMiddleware:
"""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
if not settings.auth_enabled:
await self.app(scope, receive, send)
return
request = Request(scope, receive=receive)
path = request.url.path
if path.startswith("/covers/"):
if session_user_from_request(request):
await self.app(scope, receive, send)
return
resp = JSONResponse({"detail": "未登录"}, status_code=401)
await resp(scope, receive, send)
return
if not path.startswith("/api/"):
await self.app(scope, receive, send)
return
if path in _PUBLIC_API_EXACT or any(path.startswith(p) for p in _PUBLIC_API_PREFIXES):
await self.app(scope, receive, send)
return
if session_user_from_request(request):
await self.app(scope, receive, send)
return
resp = JSONResponse({"detail": "未登录,请先登录"}, status_code=401)
await resp(scope, receive, send)