46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
"""
|
|
backend/app/services/integration_tool_auth.py
|
|
|
|
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
|
|
依赖:Flask current_app、core.errors、core.http_context。
|
|
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
|
|
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from flask import current_app
|
|
|
|
from app.core.errors import ServiceUnavailableError, UnauthorizedError
|
|
from app.core.http_context import header
|
|
|
|
|
|
def require_integration_tool_auth() -> None:
|
|
"""
|
|
校验 Tool API 访问权限。
|
|
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
|
|
|
|
异常:
|
|
ServiceUnavailableError: 服务端未配置密钥。
|
|
UnauthorizedError: 缺少或错误的凭证。
|
|
"""
|
|
configured = str(
|
|
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
|
or current_app.config.get("INTEGRATION_API_KEY")
|
|
or ""
|
|
).strip()
|
|
if not configured:
|
|
raise ServiceUnavailableError(
|
|
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
|
code="missing_auth",
|
|
)
|
|
|
|
bearer = header("Authorization").strip()
|
|
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
|
integration_key = header("X-Integration-Key").strip()
|
|
if configured in {api_token, integration_key}:
|
|
return
|
|
if not api_token and not integration_key:
|
|
raise UnauthorizedError("missing_auth")
|
|
raise UnauthorizedError("invalid_auth")
|