# -*- coding: utf-8 -*- """鉴权层:中心机 X-API-Token 与 管理页面会话 token(HMAC 签名)双通道。""" from __future__ import annotations import base64 import hashlib import hmac import time from fastapi import Header, HTTPException from fileserver.core import config def sign_admin_token(user: str) -> str: """签发管理会话 token:base64("{user}|{exp}|{hmac}"),默认 12h 有效。""" exp = int(time.time()) + config.ADMIN_TOKEN_TTL payload = f"{user}|{exp}" sig = hmac.new(config.ADMIN_SECRET.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest() return base64.urlsafe_b64encode(f"{payload}|{sig}".encode("utf-8")).decode("utf-8") def verify_admin_token(token: str) -> bool: """校验管理会话 Bearer token(HMAC 签名 + 过期时间)。""" return bool(_decode_admin(token)) def _decode_admin(token: str) -> str: """解析管理会话,返回登录用户名;无效/过期返回空串。""" if not token: return "" try: raw = base64.urlsafe_b64decode(token.encode("utf-8")).decode("utf-8") user, exp, sig = raw.rsplit("|", 2) expect = hmac.new(config.ADMIN_SECRET.encode("utf-8"), f"{user}|{exp}".encode("utf-8"), hashlib.sha256).hexdigest() if not hmac.compare_digest(sig, expect): return "" if int(exp) <= time.time(): return "" return user except Exception: # noqa: BLE001 return "" def admin_identity(x_api_token: str, authorization: str) -> str: """解析当前调用方身份:X-API-Token → "center";管理会话 → 登录用户名;否则空串。""" if config.TOKEN and x_api_token.strip() == config.TOKEN: return "center" if authorization.startswith("Bearer "): user = _decode_admin(authorization[7:].strip()) if user: return user return "" def check_admin(x_api_token: str = Header(default="", alias="X-API-Token"), authorization: str = Header(default="", alias="Authorization")) -> str: """FastAPI 依赖:X-API-Token(中心机/自动化)或管理会话 Bearer(管理页面)二选一通过。 返回调用方身份("center" 或登录用户名),供记录上传人等审计字段。""" who = admin_identity(x_api_token, authorization) if not who: raise HTTPException(401, "无效的文件服务器令牌") return who def verify_login(username: str, password: str) -> bool: """校验管理页面账号密码(常量时间比较)。""" if not (config.ADMIN_USER and config.ADMIN_PASSWORD): return False return (hmac.compare_digest(username, config.ADMIN_USER) and hmac.compare_digest(password, config.ADMIN_PASSWORD))