409 lines
14 KiB
Python
409 lines
14 KiB
Python
"""AIBridge 核心客户端
|
||
|
||
JNPFClient 基于 requests.Session 实现,自动管理认证头和双 HTTP 客户端。
|
||
|
||
请求头约定(与前端 request.ts 对齐):
|
||
Authorization: {token} # token 已含 "bearer " 前缀(小写)
|
||
App-Code: {app_code} # 多应用系统识别码
|
||
Jnpf-Origin: pc # 来源标识
|
||
Vue-Version: 3 # Vue 版本标识
|
||
Content-Type: application/json # 默认
|
||
"""
|
||
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
import subprocess
|
||
from typing import Any, Dict, Optional, Union
|
||
from urllib.parse import urljoin
|
||
|
||
import requests
|
||
|
||
from aibridge.config import JNPFConfig
|
||
from aibridge.exceptions import APIError, AuthError, JNPFError
|
||
from aibridge.models import APIResponse
|
||
|
||
logger = logging.getLogger("aibridge")
|
||
|
||
|
||
def encrypt_password_aes(password: str, cipher_key: str = "EY8WePvjM5GGwQzn") -> str:
|
||
"""加密密码(与前端登录加密逻辑一致)
|
||
|
||
流程: MD5(明文密码) → AES-128-ECB 加密 → hex
|
||
等同于前端: encryptByMd5(password) → aesEncryption.encryptByAES()
|
||
|
||
Args:
|
||
password: 明文密码
|
||
cipher_key: AES密钥(默认前端 VITE_CIPHER_KEY)
|
||
|
||
Returns:
|
||
AES加密后的hex字符串(96字符)
|
||
|
||
注意: 如果加密结果与前端不兼容,请从浏览器开发者工具复制登录请求的 password 值。
|
||
"""
|
||
# MD5(明文密码)
|
||
md5_pwd = hashlib.md5(password.encode('utf-8')).hexdigest()
|
||
|
||
# AES-128-ECB 加密(通过 Node.js 实现,Python 缺少 pycryptodome)
|
||
key = hashlib.md5(cipher_key.encode('utf-8')).hexdigest()
|
||
node_script = f"""
|
||
const crypto = require('crypto');
|
||
const key = Buffer.from('{key}', 'hex');
|
||
const cipher = crypto.createCipheriv('aes-128-ecb', key, null);
|
||
cipher.setAutoPadding(true);
|
||
let encrypted = cipher.update('{md5_pwd}', 'utf8', 'hex');
|
||
encrypted += cipher.final('hex');
|
||
console.log(encrypted);
|
||
"""
|
||
result = subprocess.run(['node', '-e', node_script], capture_output=True, text=True)
|
||
return result.stdout.strip()
|
||
|
||
|
||
def generate_encrypted_password(password: str, cipher_key: str = "EY8WePvjM5GGwQzn") -> str:
|
||
"""生成可用于 config.py 的加密密码
|
||
|
||
注意: 如果生成的密码无法登录,说明前端使用的 CIPHER_KEY 与默认值不同。
|
||
请从浏览器开发者工具复制登录请求中的 password 值。
|
||
|
||
获取正确密码的方法:
|
||
1. 打开浏览器开发者工具 (F12),切换到 Network 标签
|
||
2. 登录页面输入账号密码,点击登录
|
||
3. 找到 /api/oauth/Login 请求
|
||
4. 复制 Form Data 中的 password 值(96字符的hex字符串)
|
||
|
||
Args:
|
||
password: 明文密码
|
||
cipher_key: 前端 VITE_CIPHER_KEY(默认 EY8WePvjM5GGwQzn)
|
||
|
||
用法:
|
||
from aibridge.client import generate_encrypted_password
|
||
encrypted = generate_encrypted_password("your_password")
|
||
print(f"加密后的密码: {encrypted}")
|
||
"""
|
||
return encrypt_password_aes(password, cipher_key)
|
||
|
||
|
||
# 默认 AES 密钥(与前端 VITE_CIPHER_KEY 一致)
|
||
DEFAULT_CIPHER_KEY = "EY8WePvjM5GGwQzn"
|
||
|
||
|
||
class JNPFClient:
|
||
"""JNPF 低代码平台客户端
|
||
|
||
用法::
|
||
|
||
# 推荐方式:使用默认配置(当前系统,如 myapp)
|
||
from aibridge import JNPFClient, JNPFConfig
|
||
CONFIG = JNPFConfig()
|
||
client = JNPFClient.from_config(CONFIG)
|
||
client.login() # 自动使用 CONFIG 中的账号密码
|
||
|
||
# 或直接构造(需手动传入账号密码)
|
||
client = JNPFClient(base_url="http://localhost:30000", app_code="{YOUR_APP_CODE}")
|
||
client.login(account="admin", password="xxx")
|
||
resp = client.request("GET", "/api/system/Menu/ModuleBySystem")
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
base_url: str = "http://localhost:30000",
|
||
app_code: str = "",
|
||
report_base_url: str = "",
|
||
timeout: int = 30,
|
||
verify_ssl: bool = False,
|
||
):
|
||
self.base_url = base_url.rstrip("/")
|
||
self.report_base_url = (report_base_url or base_url).rstrip("/")
|
||
self.app_code = app_code
|
||
self.timeout = timeout
|
||
self.verify_ssl = verify_ssl
|
||
|
||
if not app_code:
|
||
import warnings
|
||
warnings.warn(
|
||
"[AIBridge] JNPFClient() 创建时 app_code 为空!\n"
|
||
" 这会导致所有 API 请求使用平台系统身份(systemId=309228585019769285),\n"
|
||
" 创建的菜单和功能不会出现在你的业务系统中。\n"
|
||
" 请使用 JNPFClient.from_config(config) 或传入 app_code 参数。\n"
|
||
" 示例: client = JNPFClient(app_code='ais')",
|
||
UserWarning,
|
||
stacklevel=2
|
||
)
|
||
|
||
self.token: str = ""
|
||
self.user_info: Dict[str, Any] = {}
|
||
|
||
# 主 HTTP 客户端
|
||
self._session = self._create_session(self.base_url)
|
||
# 报表独立客户端
|
||
self._report_session = self._create_session(self.report_base_url)
|
||
|
||
# 挂载 API 模块
|
||
from aibridge.modules import (
|
||
AuthAPI, MenuAPI, UserAPI, OrganizeAPI, RoleAPI, PositionAPI,
|
||
DictionaryAPI, VisualDevAPI, OnlineDevAPI, WorkflowAPI,
|
||
DataInterfaceAPI, InterfaceOauthAPI, PortalAPI, MessageAPI, DataSourceAPI,
|
||
DataModelAPI,
|
||
PrintDevAPI, ReportAPI, SysConfigAPI, FileAPI,
|
||
)
|
||
self.auth = AuthAPI(self)
|
||
self.menu = MenuAPI(self)
|
||
self.user = UserAPI(self)
|
||
self.organize = OrganizeAPI(self)
|
||
self.role = RoleAPI(self)
|
||
self.position = PositionAPI(self)
|
||
self.dictionary = DictionaryAPI(self)
|
||
self.visual_dev = VisualDevAPI(self)
|
||
self.online_dev = OnlineDevAPI(self)
|
||
self.workflow = WorkflowAPI(self)
|
||
self.data_interface = DataInterfaceAPI(self)
|
||
self.interface_oauth = InterfaceOauthAPI(self)
|
||
self.portal = PortalAPI(self)
|
||
self.message = MessageAPI(self)
|
||
self.data_source = DataSourceAPI(self)
|
||
self.data_model = DataModelAPI(self)
|
||
self.print_dev = PrintDevAPI(self)
|
||
self.report = ReportAPI(self)
|
||
self.sys_config = SysConfigAPI(self)
|
||
self.file = FileAPI(self)
|
||
|
||
@classmethod
|
||
def from_config(cls, config: JNPFConfig) -> "JNPFClient":
|
||
"""从 JNPFConfig 创建客户端,自动保存账号密码供 login() 无参数调用"""
|
||
client = cls(
|
||
base_url=config.api_base,
|
||
app_code=config.app_code,
|
||
report_base_url=config.report_api_base,
|
||
timeout=config.timeout,
|
||
verify_ssl=config.verify_ssl,
|
||
)
|
||
client._account = config.account
|
||
client._password = config.backend_aes96_password
|
||
return client
|
||
|
||
def _create_session(self, base_url: str) -> requests.Session:
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"Jnpf-Origin": "pc",
|
||
"Vue-Version": "3",
|
||
"Accept": "application/json, text/plain, */*",
|
||
})
|
||
session.verify = self.verify_ssl
|
||
return session
|
||
|
||
def _update_auth_headers(self):
|
||
"""更新认证相关请求头"""
|
||
headers = {}
|
||
if self.token:
|
||
auth = self.token if self.token.startswith("bearer ") else f"bearer {self.token}"
|
||
headers["Authorization"] = auth
|
||
if self.app_code:
|
||
headers["App-Code"] = self.app_code
|
||
self._session.headers.update(headers)
|
||
self._report_session.headers.update(headers)
|
||
|
||
# ==================== 认证方法 ====================
|
||
|
||
def login(self, account: str = None, password: str = None) -> APIResponse:
|
||
"""登录获取 Token
|
||
|
||
Args:
|
||
account: 账号(默认使用 from_config 保存的值)
|
||
password: 密码(默认使用 from_config 保存的值)
|
||
- 96字符: 视为已加密的AES密文,直接使用
|
||
- 其他长度: 明文密码(不推荐,Python无法生成正确的AES密文)
|
||
★ 推荐:使用 .claude/scripts/extract_encrypted_password.js 从浏览器提取96字符AES密文
|
||
"""
|
||
# 默认使用 from_config 保存的账号密码
|
||
if account is None:
|
||
account = getattr(self, '_account', '')
|
||
if password is None:
|
||
password = getattr(self, '_password', '')
|
||
|
||
url = f"{self.base_url}/api/oauth/Login"
|
||
|
||
# 96字符视为已加密的AES密文
|
||
if len(password) == 96:
|
||
encrypted_pwd = password
|
||
origin = "hash"
|
||
else:
|
||
encrypted_pwd = password
|
||
origin = "password"
|
||
|
||
data = {
|
||
"account": account,
|
||
"password": encrypted_pwd,
|
||
"origin": origin,
|
||
"timestamp": 0,
|
||
"grant_type": "password",
|
||
}
|
||
resp = requests.post(
|
||
url,
|
||
data=data,
|
||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||
timeout=self.timeout,
|
||
verify=self.verify_ssl,
|
||
)
|
||
result = resp.json()
|
||
|
||
if result.get("code") != 200:
|
||
raise AuthError(
|
||
msg=result.get("msg", "登录失败"),
|
||
code=result.get("code", 0),
|
||
raw=result,
|
||
)
|
||
|
||
self.token = result["data"]["token"]
|
||
self._update_auth_headers()
|
||
logger.info("登录成功: %s", account)
|
||
return APIResponse(
|
||
code=result["code"],
|
||
data=result["data"],
|
||
msg=result.get("msg", ""),
|
||
raw=result,
|
||
)
|
||
|
||
def login_by_token(self, token: str):
|
||
"""直接设置已有 Token(跳过登录)"""
|
||
self.token = token
|
||
self._update_auth_headers()
|
||
logger.info("Token 已设置")
|
||
|
||
def logout(self) -> APIResponse:
|
||
"""退出登录"""
|
||
resp = self._request("POST", "/api/oauth/Logout", with_credentials=True)
|
||
self.token = ""
|
||
self.user_info = {}
|
||
self._update_auth_headers()
|
||
logger.info("已退出登录")
|
||
return resp
|
||
|
||
def get_user_info(self, system_code: str = "", is_backend: int = 0) -> APIResponse:
|
||
"""获取当前用户信息
|
||
|
||
Args:
|
||
system_code: 系统编码,默认使用 app_code
|
||
is_backend: 是否后台 0=否 1=是
|
||
"""
|
||
params = {
|
||
"systemCode": system_code or self.app_code,
|
||
"isBackend": is_backend,
|
||
}
|
||
resp = self._request("GET", "/api/oauth/CurrentUser", params=params)
|
||
if resp.success and isinstance(resp.data, dict):
|
||
self.user_info = resp.data
|
||
return resp
|
||
|
||
def get_login_config(self) -> APIResponse:
|
||
"""获取登录配置"""
|
||
return self._request("GET", "/api/oauth/getLoginConfig")
|
||
|
||
# ==================== 核心请求方法 ====================
|
||
|
||
def request(
|
||
self,
|
||
method: str,
|
||
path: str,
|
||
*,
|
||
params: dict = None,
|
||
data: dict = None,
|
||
json_data: dict = None,
|
||
use_report_client: bool = False,
|
||
**kwargs,
|
||
) -> APIResponse:
|
||
"""发送 API 请求
|
||
|
||
Args:
|
||
method: HTTP 方法 (GET/POST/PUT/DELETE)
|
||
path: API 路径,如 "/api/system/Menu"
|
||
params: URL 查询参数
|
||
data: 请求体数据(自动 JSON 序列化)
|
||
json_data: 请求体 JSON 数据(优先于 data)
|
||
use_report_client: 是否使用报表客户端
|
||
**kwargs: 传递给 requests 的额外参数
|
||
"""
|
||
return self._request(
|
||
method, path,
|
||
params=params,
|
||
data=data,
|
||
json_data=json_data,
|
||
use_report_client=use_report_client,
|
||
**kwargs,
|
||
)
|
||
|
||
def _request(
|
||
self,
|
||
method: str,
|
||
path: str,
|
||
*,
|
||
params: dict = None,
|
||
data: dict = None,
|
||
json_data: dict = None,
|
||
use_report_client: bool = False,
|
||
with_credentials: bool = False,
|
||
**kwargs,
|
||
) -> APIResponse:
|
||
"""内部请求方法"""
|
||
session = self._report_session if use_report_client else self._session
|
||
|
||
url = f"{self.base_url}{path}" if not use_report_client else f"{self.report_base_url}{path}"
|
||
|
||
req_kwargs = {
|
||
"method": method.upper(),
|
||
"url": url,
|
||
"params": params,
|
||
"timeout": kwargs.pop("timeout", self.timeout),
|
||
}
|
||
|
||
if json_data is not None:
|
||
req_kwargs["json"] = json_data
|
||
elif data is not None:
|
||
req_kwargs["json"] = data
|
||
|
||
if with_credentials:
|
||
session = requests.Session()
|
||
session.headers.update(self._session.headers)
|
||
session.verify = self.verify_ssl
|
||
req_kwargs["cookies"] = {"Cookie": ""}
|
||
|
||
try:
|
||
response = session.request(**req_kwargs)
|
||
result = response.json()
|
||
except requests.exceptions.Timeout:
|
||
raise JNPFError(msg=f"请求超时: {path}")
|
||
except requests.exceptions.ConnectionError:
|
||
raise JNPFError(msg=f"连接失败: {self.base_url}")
|
||
except json.JSONDecodeError:
|
||
raise JNPFError(msg=f"响应非 JSON: {path} status={response.status_code}")
|
||
|
||
code = result.get("code", 0)
|
||
msg = result.get("msg", "")
|
||
resp_data = result.get("data")
|
||
|
||
api_resp = APIResponse(
|
||
code=code,
|
||
data=resp_data,
|
||
msg=msg,
|
||
raw=result,
|
||
)
|
||
|
||
if code != 200:
|
||
logger.warning("API 错误 [%s] %s: %s", code, path, msg)
|
||
|
||
return api_resp
|
||
|
||
def require_success(self, resp: APIResponse) -> APIResponse:
|
||
"""要求响应成功,否则抛出异常"""
|
||
if not resp.success:
|
||
raise APIError(
|
||
msg=resp.msg or "操作失败",
|
||
code=resp.code,
|
||
raw=resp.raw,
|
||
)
|
||
return resp
|
||
|
||
def check_login(self):
|
||
"""检查是否已登录,未登录则抛出异常"""
|
||
if not self.token:
|
||
raise AuthError(msg="未登录,请先调用 login() 或 login_by_token()")
|