新增 SealAI 子模块:认证层 + API 传输层 + 服务层
架构:融入现有三层结构,SealAI 作为各层的子目录与 HAB 模块并列 api/sealai/ - SealAiClient(Bearer JWT)+ auth_api + billing_api + schemas services/sealai/ - auth_service(SSO换token/缓存)+ billing_service config.py - 新增 get_corp(corp_id) 按ID查询企业配置 认证流程:快报 accesstoken → SSO 换 Bearer JWT → 缓存到 sealai_tokens.json 已验证:auth/me 和 billing/status 端点正常返回数据
This commit is contained in:
1 parent
bfce1fce77
commit
9d517defe3
10 files changed
+405
No files matched your search
@@ -0,0 +1,19 @@
|
||||
"""SealAI 服务层统一 re-export。"""
|
||||
|
||||
from ekb_cli.services.sealai.auth_service import (
|
||||
get_sealai_client,
|
||||
get_bearer_token,
|
||||
invalidate_token,
|
||||
)
|
||||
from ekb_cli.services.sealai.billing_service import (
|
||||
query_billing_status,
|
||||
get_feature_usage,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"get_sealai_client",
|
||||
"get_bearer_token",
|
||||
"invalidate_token",
|
||||
"query_billing_status",
|
||||
"get_feature_usage",
|
||||
]
|
||||
@@ -0,0 +1,109 @@
|
||||
"""SealAI 认证业务逻辑层。
|
||||
|
||||
职责:SSO 换 Bearer token、本地缓存、自动刷新、对外暴露 get_sealai_client()。
|
||||
|
||||
认证流程:
|
||||
快报 accesstoken
|
||||
→ GET {corpId}.sealai.cc/api/auth/oauth2/session/oem-hosecloud?token=...&returnToken=1
|
||||
→ Bearer JWT(缓存到 ~/.config/ekb-cli/sealai_tokens.json)
|
||||
→ SealAiClient(corp_id, bearer_token)
|
||||
|
||||
缓存格式:
|
||||
{ "ID01Jdq2yIDnMr": { "token": "...", "fetched_at": 1712345678 } }
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from ekb_cli import config as ekb_config
|
||||
from ekb_cli.errors import NotLoggedInError, AuthenticationError, ApiResponseError
|
||||
from ekb_cli.api.sealai.client import SealAiClient
|
||||
|
||||
|
||||
_TOKEN_CACHE_PATH = Path.home() / ".config" / "ekb-cli" / "sealai_tokens.json"
|
||||
_TOKEN_TTL = 3600 # 保守 1 小时,到期前强制刷新
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
if _TOKEN_CACHE_PATH.exists():
|
||||
try:
|
||||
return json.loads(_TOKEN_CACHE_PATH.read_text())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def _save_cache(cache: dict) -> None:
|
||||
_TOKEN_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
_TOKEN_CACHE_PATH.write_text(json.dumps(cache, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
def _fetch_token(corp_id: str, access_token: str) -> str:
|
||||
"""用快报 accesstoken 向 SealAI 换取 Bearer JWT(SSO)。"""
|
||||
url = f"https://{corp_id.lower()}.sealai.cc/api/auth/oauth2/session/oem-hosecloud"
|
||||
try:
|
||||
resp = httpx.get(
|
||||
url,
|
||||
params={"token": access_token, "returnToken": "1"},
|
||||
headers={"Accept": "application/json"},
|
||||
timeout=15,
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 401:
|
||||
raise AuthenticationError("快报 token 无效,无法登录 SealAI")
|
||||
raise ApiResponseError(e.response.status_code, str(e))
|
||||
|
||||
data = resp.json()
|
||||
# 响应:{ "token": "..." } 或 { "data": { "token": "..." } }
|
||||
token = data.get("token") or (data.get("data") or {}).get("token")
|
||||
if not token:
|
||||
raise AuthenticationError(f"SealAI SSO 响应中未找到 token:{data}")
|
||||
return token
|
||||
|
||||
|
||||
def get_bearer_token(corp_id: str, force_refresh: bool = False) -> str:
|
||||
"""获取 Bearer token(优先读缓存,过期自动刷新)。"""
|
||||
cache = _load_cache()
|
||||
entry = cache.get(corp_id, {})
|
||||
now = int(time.time())
|
||||
|
||||
if not force_refresh and entry.get("token") and (now - entry.get("fetched_at", 0)) < _TOKEN_TTL:
|
||||
return entry["token"]
|
||||
|
||||
corp = ekb_config.get_corp(corp_id)
|
||||
if not corp:
|
||||
raise NotLoggedInError(f"企业 {corp_id} 未配置快报认证,请先运行 ekb auth add")
|
||||
|
||||
token = _fetch_token(corp_id, corp["access_token"])
|
||||
cache[corp_id] = {"token": token, "fetched_at": now}
|
||||
_save_cache(cache)
|
||||
return token
|
||||
|
||||
|
||||
def invalidate_token(corp_id: str) -> None:
|
||||
"""清除指定企业的缓存 token(用于 401 后强制重新获取)。"""
|
||||
cache = _load_cache()
|
||||
cache.pop(corp_id, None)
|
||||
_save_cache(cache)
|
||||
|
||||
|
||||
def get_sealai_client(corp_id: str | None = None, force_refresh: bool = False) -> SealAiClient:
|
||||
"""获取当前企业的 SealAiClient,自动处理 token 获取和缓存。
|
||||
|
||||
Args:
|
||||
corp_id: 企业 ID,None 时使用当前配置企业
|
||||
force_refresh: 强制重新换取 token(快报 token 更换后使用)
|
||||
"""
|
||||
if corp_id is None:
|
||||
corp_id = ekb_config.get_current_corp_id()
|
||||
if not corp_id:
|
||||
raise NotLoggedInError()
|
||||
|
||||
token = get_bearer_token(corp_id, force_refresh=force_refresh)
|
||||
return SealAiClient(corp_id=corp_id, bearer_token=token)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""SealAI 计费 / 订阅业务逻辑层。"""
|
||||
|
||||
from ekb_cli.api.sealai import get_billing_status
|
||||
from ekb_cli.api.sealai.client import SealAiClient
|
||||
from ekb_cli.api.sealai.schemas import BillingStatusData, Feature
|
||||
|
||||
|
||||
def query_billing_status(client: SealAiClient) -> BillingStatusData:
|
||||
"""查询当前企业订阅状态及各功能配额。"""
|
||||
return get_billing_status(client)
|
||||
|
||||
|
||||
def get_feature_usage(client: SealAiClient, code: str) -> Feature | None:
|
||||
"""查询单个功能项使用情况。
|
||||
|
||||
常用 code:
|
||||
ai-approval AI 审批余额
|
||||
approval-rules 审核规则配额
|
||||
ai-fill AI 填单开关
|
||||
financial-policies 财务制度配额
|
||||
knowledge-documents 知识文档配额
|
||||
"""
|
||||
status = get_billing_status(client)
|
||||
return status.get_feature(code)
|
||||
Reference in new issue
Block a user