"""密碼登入 + HMAC 簽名 token(存在瀏覽器 localStorage,以 Bearer 送出,HF 的 iframe 裡也能用)。""" import hashlib import hmac import time from fastapi import Header, HTTPException, Request from . import config _KEY = hashlib.sha256(("session:" + config.APP_SECRET).encode()).digest() _fails: dict[str, list] = {} # ip -> [失敗次數, 第一次失敗時間] MAX_FAILS, LOCK_SECONDS = 5, 600 def issue_token() -> str: exp = str(int(time.time()) + config.SESSION_DAYS * 86400) sig = hmac.new(_KEY, exp.encode(), hashlib.sha256).hexdigest() return f"{exp}.{sig}" def verify_token(token: str) -> bool: try: exp, sig = token.split(".", 1) if int(exp) < time.time(): return False except ValueError: return False good = hmac.new(_KEY, exp.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(good, sig) def check_secret(secret: str) -> bool: a = hashlib.sha256((secret or "").encode()).digest() b = hashlib.sha256(config.APP_SECRET.encode()).digest() return bool(config.APP_SECRET) and hmac.compare_digest(a, b) def client_ip(req: Request) -> str: xff = req.headers.get("x-forwarded-for") if xff: return xff.split(",")[0].strip() return req.client.host if req.client else "unknown" def is_locked(ip: str) -> bool: rec = _fails.get(ip) if not rec: return False if time.time() - rec[1] > LOCK_SECONDS: _fails.pop(ip, None) return False return rec[0] >= MAX_FAILS def record_fail(ip: str): rec = _fails.setdefault(ip, [0, time.time()]) rec[0] += 1 def clear_fails(ip: str): _fails.pop(ip, None) async def require_auth(authorization: str | None = Header(default=None)): if not authorization or not authorization.startswith("Bearer ") or not verify_token(authorization[7:]): raise HTTPException(status_code=401, detail="未授權")