feat(app): 适配 JNPF 多租户 (--tenant, 账号串 租户号@账号)
JNPF v7 打开 config.MultiTenancy 后, 账号必须带租户号, 否则 admin 把整个 account 当 tenantCode 去查 base_tenant → 「租户不存在」。 核心认知: 租户是**登录态的属性**, 不是请求参数。只体现在 POST /oauth/Login 的账号串里; 后端签发的 token 其 loginId 形如 `zhangsan:349057407209541`, 之后每个请求由 admin 按 token 自己切数据源。所以不需要给任何 API 加租户 参数, 适配全是本地状态和 CLI 的事。 - core/config: 新增 DEFAULT_TENANT(JNPF_TENANT env, 默认 host) 与纯函数 loginAccount() / splitAccount(); loginAccount 见到 '@' 就不重复拼租户号, 老写法 `--account 'zhangsan@admin'` 继续可用 - core/client: ClientOptions.tenant / JnpfClient.tenant; doLogin 发拼好的串, fromToken 从缓存恢复, persist 落 tenant。**account 自带的租户优先于 opt.tenant** —— 反过来 token.json 会把租户错记成 --tenant 的默认值 - core/types: TokenFile 加可选 tenant; account 原样保存, 老 token.json 照样能读 - app/login|switch|status|logout: 加 --tenant; switch 的 --appCode 降为可选 (两者至少给一个, 没给的沿用 token 里的) - app/create: 重新登录时带上 tenant —— app create 是在当前租户里建应用 - app/_check_system: PLATFORM_APPS 白名单 + keyword 查不到时回退全量列表。 /api/system/System 只返回门户/自建应用, 平台应用 mainSystem/workFlow/ teamwork 不在里面, 也没有列全表的端点, 原来的精确匹配一律判成「不存在」 - DEFAULT_APP_CODE 'testspace' → 'mainSystem'(本地集群 base_system 里没 testspace) - app/logout: --tenant 仅二次确认(token 是单文件, 清掉就是当前租户被登出); 租户对不上时 warn **同时**进 JSON 和 ctx.success —— log.warn 在默认 quiet 模式下会被 _output_filter 丢进 buffer 再丢掉 - di/create: tenantId 保持 '0', 只订正注释。实测 public 与 jnpf_tenant_l1d9xv905q31 两个 schema 的种子数据各 119 行 f_tenant_id 全是 '0'; 只有列隔离(f_type=1)才拿它当隔离键, 本部署是 schema 隔离 已在 wuguirong 集群实测: 跨租户落库正确(zhangsan → jnpf_tenant_l1d9xv905q31, host → public), dbPing/llmPing/menuIntegrity 三项全通。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
a8ce286501
commit
0b83ecd9ac
12 files changed
+208
-39
No files matched your search
@@ -18,6 +18,18 @@
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
|
||||
/**
|
||||
* JNPF 平台内置应用名单。
|
||||
*
|
||||
* 这些应用在每个租户 schema 初始化时就由 JNPF-PostgreSQL.sql 建好,但**不出现在**
|
||||
* `/api/system/System`(应用中心列表)的返回里 —— 该端点只列门户/自建应用。
|
||||
* 列在这里是为了让 checkSystemExists 对它们直接放行,而不是误报「appCode 不存在」。
|
||||
*
|
||||
* 各版本 JNPF 的内置应用可能不同(这里只列本地 v7 集群实测存在的),
|
||||
* 换环境报「xxx 不存在」但 base_system 里明明有 → 就是漏了这个名单,补进去即可。
|
||||
*/
|
||||
const PLATFORM_APPS = new Set(['mainSystem', 'workFlow', 'teamwork'])
|
||||
|
||||
/**
|
||||
* 检测 base_system 是否含 appCode.
|
||||
* 返 true = 存在, false = 缺失, null = API 调用失败 (无法判断).
|
||||
@@ -31,6 +43,16 @@ export async function checkSystemExists(
|
||||
appCode: string,
|
||||
): Promise<boolean | null> {
|
||||
if (!appCode) return null
|
||||
|
||||
// JNPF 平台内置应用(每个租户 schema 初始化时就带的 is_main 类应用)。
|
||||
// 它们在 base_system 里真实存在,但**不会**出现在 `/api/system/System` 的返回里 ——
|
||||
// 那个端点是「应用中心」列表,只列门户/自建应用。实测(2026-10-14,本地 JNPF v7 集群):
|
||||
// base_system 有 5 行 (mainSystem/workFlow/teamwork/workSystem/developSystem),
|
||||
// /api/system/System 全量只返回 workSystem + developSystem 这 2 个。
|
||||
// 平台应用也没有「列全表」端点(/system/SystemBase、/system/SystemAll 都 400)。
|
||||
// 所以对平台应用不能判定为「不存在」,否则一律误报 —— 直接放行。
|
||||
if (PLATFORM_APPS.has(appCode)) return true
|
||||
|
||||
try {
|
||||
const r = await c.get<{ list: { id?: string; enCode?: string }[] }>(
|
||||
'/system/System',
|
||||
@@ -40,7 +62,15 @@ export async function checkSystemExists(
|
||||
log.warn(`(system 缺失检测 API 失败: code=${r.code} ${r.msg})`)
|
||||
return null
|
||||
}
|
||||
return !!r.data?.list?.some((x) => x.enCode === appCode)
|
||||
if (r.data?.list?.some((x) => x.enCode === appCode)) return true
|
||||
// keyword 过滤在部分 JNPF 版本上不可靠(实测 keyword=workFlow 返回 0 条),
|
||||
// 回退到全量列表再判一次,避免把「过滤不灵」误当成「应用被删」。
|
||||
const all = await c.get<{ list: { id?: string; enCode?: string }[] }>(
|
||||
'/system/System',
|
||||
{ currentPage: 1, pageSize: 500 },
|
||||
)
|
||||
if (all.code === 200 && all.data?.list?.some((x) => x.enCode === appCode)) return true
|
||||
return false
|
||||
} catch (e) {
|
||||
log.warn(`(system 缺失检测异常: ${(e as Error).message})`)
|
||||
return null
|
||||
|
||||
@@ -51,7 +51,7 @@ import { parse as yamlParse, stringify as yamlStringify } from 'yaml'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { DacliError } from '../../core/types.ts'
|
||||
import { clearToken, getTokenPath, loadToken } from '../../core/config.ts'
|
||||
import { clearToken, getTokenPath, loadToken, DEFAULT_APP_CODE } from '../../core/config.ts'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): 跨命令 auto-fix (S-X1/S-X2 silent + G-X1 suggest)
|
||||
import { setupOutputFilter, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): stdout 三模式 + CommandLog 落盘
|
||||
@@ -185,7 +185,7 @@ export function buildAppClearCommand(): Command {
|
||||
|
||||
// v2.1+ L2 silent+suggest: 跨命令 auto-fix pipeline
|
||||
// appCode 正则本身允许 `-`/`_`, S-X1 会 strip 但合法, 只是让 appCode 在后续 login/init 用一致 enCode
|
||||
const fixCtx = await fetchExistingLists(c as unknown as Awaited<ReturnType<typeof JnpfClient.fromToken>>, c.appCode || 'testspace')
|
||||
const fixCtx = await fetchExistingLists(c as unknown as Awaited<ReturnType<typeof JnpfClient.fromToken>>, c.appCode || DEFAULT_APP_CODE)
|
||||
const cmdFix = runCommandAutoFix(opts as unknown as Record<string, unknown>, fixCtx)
|
||||
if (cmdFix.silent.length > 0) {
|
||||
Object.assign(opts, cmdFix.opts)
|
||||
|
||||
@@ -22,7 +22,7 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { saveToken, currentWebUrl } from '../../core/config.ts'
|
||||
import { saveToken, currentWebUrl, DEFAULT_APP_CODE } from '../../core/config.ts'
|
||||
import type { TokenFile } from '../../core/types.ts'
|
||||
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
|
||||
import { loadDbProfile } from '../../core/db-driver.ts'
|
||||
@@ -101,7 +101,7 @@ export function buildAppCreateCommand(): Command {
|
||||
}
|
||||
|
||||
// v2.1+ L2 silent+suggest: 跨命令 auto-fix pipeline (S-X1/S-X2/G-X1)
|
||||
const fixCtx = await fetchExistingLists(c, c.appCode || 'testspace')
|
||||
const fixCtx = await fetchExistingLists(c, c.appCode || DEFAULT_APP_CODE)
|
||||
const cmdFix = runCommandAutoFix(opts as unknown as Record<string, unknown>, fixCtx)
|
||||
if (cmdFix.silent.length > 0) {
|
||||
Object.assign(opts, cmdFix.opts)
|
||||
@@ -231,7 +231,7 @@ async function runCreate(opts: CreateOpts): Promise<{ systemId: string; dbLinkId
|
||||
c = await JnpfClient.login({
|
||||
account: opts.account || 'admin',
|
||||
password: opts.password || '123456',
|
||||
appCode: 'testspace', // 平台占位
|
||||
appCode: DEFAULT_APP_CODE, // 平台占位(曾硬编码 testspace,那套环境之外不存在)
|
||||
} as any)
|
||||
log.dim(` 强制登录: ${c.account} @ ${c.appCode} (baseUrl=${c.baseUrl})`)
|
||||
}
|
||||
@@ -355,13 +355,16 @@ async function runCreate(opts: CreateOpts): Promise<{ systemId: string; dbLinkId
|
||||
const c2 = await JnpfClient.login({
|
||||
baseUrl: c.baseUrl,
|
||||
appCode: opts.appCode,
|
||||
account: opts.account || 'admin',
|
||||
// 沿用当前登录的租户: app create 是"在当前租户里建应用", 不能换租户
|
||||
tenant: c.tenant,
|
||||
account: opts.account || c.account || 'admin',
|
||||
password: opts.password || '123456',
|
||||
})
|
||||
const tf: TokenFile = {
|
||||
baseUrl: c2.baseUrl,
|
||||
appCode: opts.appCode,
|
||||
account: opts.account || 'admin',
|
||||
account: opts.account || c.account || 'admin',
|
||||
tenant: c2.tenant || undefined,
|
||||
token: c2.token,
|
||||
loginAt: new Date().toISOString(),
|
||||
dbLinkId: dbLinkId || c2.dbLinkId,
|
||||
@@ -370,7 +373,7 @@ async function runCreate(opts: CreateOpts): Promise<{ systemId: string; dbLinkId
|
||||
log.ok(` ✓ 已登录 + 保存 token (appCode=${opts.appCode}, dbLinkId=${tf.dbLinkId})`)
|
||||
} catch (e) {
|
||||
log.warn(` ⚠ 切换登录失败: ${(e as Error).message}`)
|
||||
log.warn(` 请手动: dacli app login --account=admin --password=123456 --appCode=${opts.appCode}`)
|
||||
log.warn(` 请手动: dacli app login --tenant ${c.tenant || '<租户号>'} --account=${opts.account || 'admin'} --password=123456 --appCode=${opts.appCode}`)
|
||||
}
|
||||
|
||||
// 返回 success summary 给 .action() 的 printCommandEnd
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
DEFAULT_ACCOUNT,
|
||||
DEFAULT_APP_CODE,
|
||||
DEFAULT_PASSWORD,
|
||||
DEFAULT_TENANT,
|
||||
clearToken,
|
||||
getTokenPath,
|
||||
} from '../../core/config.ts'
|
||||
@@ -27,14 +28,16 @@ import { setupOutputFilter, printCommandEnd } from '../_output_filter.ts' // v2.
|
||||
|
||||
export function buildAppLoginCommand(): Command {
|
||||
const cmd = new Command('login')
|
||||
.description('登录 JNPF (默认 admin/123456@testspace, 统一测试场; developSystem/workSystem 是 JNPF 只读 baseline), 持久化 token 到 ~/.dacli-token/token.json (DACLI_TOKEN_DIR 可覆盖)')
|
||||
.option('--account <a>', '账号', DEFAULT_ACCOUNT)
|
||||
.description('登录 JNPF (默认 host@admin/123456@mainSystem 平台占位; developSystem/workSystem 是 JNPF 只读 baseline), 持久化 token 到 ~/.dacli-token/token.json (DACLI_TOKEN_DIR 可覆盖)')
|
||||
.option('--tenant <t>', '租户号 (JNPF 多租户; 默认 host=宿主租户。也可直接把租户号写进 --account, 如 \'zhangsan@admin\')', DEFAULT_TENANT)
|
||||
.option('--account <a>', '账号 (不含租户号; 写全串 \'租户号@账号\' 也可以, 此时忽略 --tenant)', DEFAULT_ACCOUNT)
|
||||
.option('--password <p>', '密码 (明文; 96 字符 hex 视为已加密)', DEFAULT_PASSWORD)
|
||||
.option('--appCode <c>', '应用代码 (testspace 推荐=测试场 | jxcj=业务 | developSystem/workSystem=只读 baseline)', DEFAULT_APP_CODE)
|
||||
.option('--appCode <c>', '应用代码 (默认 mainSystem 平台占位 | jxcj=业务 | developSystem/workSystem=只读 baseline)', DEFAULT_APP_CODE)
|
||||
.option('--baseUrl <u>', 'JNPF API 根地址 (含 /api)')
|
||||
.option('--no-check-system', '跳过 base_system 存在性检测 (默认 ON, v0.11e+ Phase E)')
|
||||
.option('--verbose', '完整输出 (含 base_system 检测等过程日志)', false)
|
||||
.action(async (opts: {
|
||||
tenant: string
|
||||
account: string
|
||||
password: string
|
||||
appCode: string
|
||||
@@ -48,6 +51,7 @@ export function buildAppLoginCommand(): Command {
|
||||
const startTime = Date.now()
|
||||
|
||||
const c = await JnpfClient.login({
|
||||
tenant: opts.tenant,
|
||||
account: opts.account,
|
||||
password: opts.password,
|
||||
appCode: opts.appCode,
|
||||
@@ -92,6 +96,7 @@ export function buildAppLoginCommand(): Command {
|
||||
}
|
||||
|
||||
log.ok(`登录成功: ${c.account} @ ${c.appCode}`)
|
||||
if (c.tenant) log.dim(`租户 : ${c.tenant}`)
|
||||
log.dim(`baseUrl : ${c.baseUrl}`)
|
||||
log.dim(`token : ${c.token.slice(0, 32)}... (${c.token.length} chars)`)
|
||||
if (c.dbLinkId) log.dim(`dbLinkId : ${c.dbLinkId}`)
|
||||
@@ -104,6 +109,7 @@ export function buildAppLoginCommand(): Command {
|
||||
appCode: c.appCode,
|
||||
summary: {
|
||||
account: c.account,
|
||||
tenant: c.tenant,
|
||||
appCode: c.appCode,
|
||||
baseUrl: c.baseUrl,
|
||||
dbLinkId: c.dbLinkId,
|
||||
@@ -119,15 +125,20 @@ export function buildAppLoginCommand(): Command {
|
||||
installHelpHook(cmd, {
|
||||
purpose: '登录 JNPF, 把 token 写到 ~/.dacli-token/token.json (默认 home, 可由 DACLI_TOKEN_DIR env 覆盖), 后续命令自动复用',
|
||||
optional: {
|
||||
'--account': '账号 (默认 admin)',
|
||||
'--tenant': '租户号 (默认 host=宿主租户; JNPF 开多租户后账号必须带租户号, 否则后端把整个账号当租户号去查, 报「租户不存在」)',
|
||||
'--account': '账号 (默认 admin; 写全串 \'租户号@账号\' 也可以, 此时忽略 --tenant)',
|
||||
'--password': '密码 (默认 123456; 已是 96 字符 hex 时跳过加密)',
|
||||
'--appCode': '应用代码 (默认 testspace=统一测试场, 禁止用 developSystem/workSystem 改 baseline)',
|
||||
'--baseUrl': '强制指定 baseUrl, 否则按 [env JNPF_BASE_URL → ~/.dacli/config.json baseUrl → http://nginx/api → http://127.0.0.1:30000/api] 依次尝试 (2026-08-06 dacli 清理)',
|
||||
'--appCode': '应用代码 (默认 mainSystem=平台占位, 禁止用 developSystem/workSystem 改 baseline)',
|
||||
'--baseUrl': '强制指定 baseUrl, 否则按 [env JNPF_BASE_URL → ~/.dacli/config.json baseUrl] 依次尝试 (2026-08-06 dacli 清理)',
|
||||
'--no-check-system': '跳过 base_system 存在性检测 (默认 ON)',
|
||||
},
|
||||
example: 'dacli app login --appCode=tds',
|
||||
example: [
|
||||
'dacli app login --tenant zhangsan --account admin --password 123456',
|
||||
"dacli app login --account 'zhangsan@admin' --password 123456 # 老写法等价",
|
||||
].join('\n'),
|
||||
source: { web: 'web/apps/jnpf-web-apps-main/src/api/core/auth.ts:27 loginApi', api: 'POST /api/oauth/Login' },
|
||||
notes: [
|
||||
'租户只影响**登录**: 签发的 token 里已带租户上下文 (loginId 形如 host:8803…), 之后每个请求自动落在该租户, 不需要再传租户参数',
|
||||
'token 7 天有效',
|
||||
'已加密的 96 字符 hex 不会重复加密',
|
||||
'detectDbLinkId 自动从 /system/DataSource 拉业务库 id',
|
||||
|
||||
@@ -28,6 +28,8 @@ import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_fil
|
||||
interface LogoutOpts {
|
||||
/** 跳过 web logoutApi (仅清本地 token) */
|
||||
noRemoteLogout?: boolean
|
||||
/** 期望登出的租户号; 仅二次确认, 不做选择性清除 */
|
||||
tenant?: string
|
||||
json?: boolean
|
||||
verbose?: boolean
|
||||
}
|
||||
@@ -35,6 +37,7 @@ interface LogoutOpts {
|
||||
export function buildAppLogoutCommand(): Command {
|
||||
const cmd = new Command('logout')
|
||||
.description('退出登录 (走 webapi/auth.logoutApi + 清本地 token, v3.0+ 新增)')
|
||||
.option('--tenant <t>', '期望登出的租户号 (**仅二次确认**; token.json 是单文件, 实际清的是当前登录态那个租户)')
|
||||
.option('--no-remote-logout', '跳过 web logoutApi, 仅清本地 token (断网/无后端场景)')
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: LogoutOpts) => {
|
||||
@@ -53,9 +56,18 @@ export function buildAppLogoutCommand(): Command {
|
||||
let c: Awaited<ReturnType<typeof JnpfClient.fromToken>> | null = null
|
||||
let hasRemoteLogout = !opts.noRemoteLogout
|
||||
|
||||
// --tenant 只做二次确认: token.json 是**单文件**, 里面存着当前租户的登录态,
|
||||
// 清掉就是当前租户被登出了, 不存在"只登出别的租户"这回事。
|
||||
// 传了且对不上时提醒一句, 免得以为登出的是另一个租户。
|
||||
let tenantMismatch = false
|
||||
try {
|
||||
c = await JnpfClient.fromToken()
|
||||
log.dim(`当前登录: ${c.account} @ ${c.appCode}`)
|
||||
if (c.tenant) log.dim(`当前租户: ${c.tenant}`)
|
||||
if (opts.tenant && opts.tenant !== c.tenant) {
|
||||
tenantMismatch = true
|
||||
log.warn(` ⚠ 你指定的租户是 "${opts.tenant}", 但当前登录态是 "${c.tenant || '(无租户)'}". 将登出后者.`)
|
||||
}
|
||||
} catch (e) {
|
||||
if (hasRemoteLogout) {
|
||||
log.warn(` ⚠ 无 token, 无法调 web logoutApi (用 --no-remote-logout 仅清本地)`)
|
||||
@@ -96,23 +108,27 @@ export function buildAppLogoutCommand(): Command {
|
||||
ok: true,
|
||||
remoteLogout: hasRemoteLogout,
|
||||
tokenPath,
|
||||
nextLoginCmd: 'dacli app login --appCode=<code>',
|
||||
// log.warn 默认被输出过滤器丢进 buffer (quiet 模式), 所以提醒必须同时进 JSON 才看得见
|
||||
tenant: c?.tenant || undefined,
|
||||
tenantMismatch,
|
||||
nextLoginCmd: 'dacli app login --tenant <租户号> --account <账号> --appCode=<code>',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
log.info(` 下一步: dacli app login --account=admin --password=123456 --appCode=<code>`)
|
||||
log.info(` 或: dacli app login (默认 admin/123456@testspace, 统一测试场)`)
|
||||
log.info(` 下一步: dacli app login --tenant <租户号> --account=admin --password=123456 --appCode=<code>`)
|
||||
log.info(` 或: dacli app login (默认 host@admin/123456@mainSystem)`)
|
||||
}
|
||||
ctx.success({ remoteLogout: hasRemoteLogout, tokenPath })
|
||||
ctx.success({ remoteLogout: hasRemoteLogout, tokenPath, tenant: c?.tenant || undefined, tenantMismatch })
|
||||
})
|
||||
})
|
||||
|
||||
installHelpHook(cmd, {
|
||||
purpose: '退出登录 (走 webapi/auth.logoutApi + 清本地 token). v3.0+ 新增 (审计 P2 补缺)',
|
||||
optional: {
|
||||
'--tenant': '期望登出的租户号 (**仅二次确认**; token.json 单文件存一个登录态, 清掉就是当前租户被登出)',
|
||||
'--no-remote-logout': '跳过 web logoutApi, 仅清本地 token',
|
||||
'--json': '原始 JSON 输出',
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* - menuIntegrity (menuList.urlAddress 不空, 防 SPA 路由 404)
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { loadToken, getTokenPath, currentBaseUrl } from '../../core/config.ts'
|
||||
import { loadToken, getTokenPath, currentBaseUrl, splitAccount } from '../../core/config.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
@@ -120,7 +120,7 @@ async function runHealthChecks(c: JnpfClient | null): Promise<Array<{ name: stri
|
||||
|
||||
export function buildAppStatusCommand(): Command {
|
||||
const cmd = new Command('status')
|
||||
.description('显示当前登录状态 + baseUrl + appCode + dbLinkId + token 路径 + base_system 存在性')
|
||||
.description('显示当前登录状态 + 租户 + baseUrl + appCode + dbLinkId + token 路径 + base_system 存在性')
|
||||
.option('--json', '以 JSON 输出 (便于脚本)', false)
|
||||
.option('--no-check-system', '跳过 base_system 存在性检测 (默认 ON, v0.11e+ Phase E)')
|
||||
.option('--fix-menu-url', '自动重建 menuIntegrity 报出的 urlAddress 空菜单 (BS-56 修复路径)', false)
|
||||
@@ -217,6 +217,7 @@ export function buildAppStatusCommand(): Command {
|
||||
baseUrl: t?.baseUrl || currentBaseUrl(),
|
||||
loggedIn: !!t,
|
||||
account: t?.account,
|
||||
tenant: t?.tenant || splitAccount(t?.account || '').tenant || undefined,
|
||||
appCode: t?.appCode,
|
||||
dbLinkId: t?.dbLinkId,
|
||||
loginAt: t?.loginAt,
|
||||
@@ -247,6 +248,9 @@ export function buildAppStatusCommand(): Command {
|
||||
}
|
||||
|
||||
log.ok(`已登录: ${t.account} @ ${t.appCode}`)
|
||||
// 老 token.json (2026-10-15 之前写的) 没有 tenant 字段, 回落到从 account 拆
|
||||
const curTenant = t.tenant || splitAccount(t.account).tenant
|
||||
if (curTenant) log.dim(`租户 : ${curTenant}`)
|
||||
log.dim(`baseUrl : ${t.baseUrl}`)
|
||||
log.dim(`dbLinkId : ${t.dbLinkId || '(unknown)'}`)
|
||||
log.dim(`loginAt : ${t.loginAt}`)
|
||||
|
||||
@@ -3,33 +3,61 @@
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { DEFAULT_ACCOUNT, DEFAULT_PASSWORD, loadToken } from '../../core/config.ts'
|
||||
import {
|
||||
DEFAULT_ACCOUNT,
|
||||
DEFAULT_APP_CODE,
|
||||
DEFAULT_PASSWORD,
|
||||
DEFAULT_TENANT,
|
||||
loadToken,
|
||||
} from '../../core/config.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
|
||||
export function buildAppSwitchCommand(): Command {
|
||||
const cmd = new Command('switch')
|
||||
.description('切换当前应用 (重新登录新 appCode 并覆盖 token)')
|
||||
.requiredOption('--appCode <c>', '目标应用代码')
|
||||
.description('切换当前租户/应用 (重新登录并覆盖 token; --tenant 与 --appCode 至少给一个)')
|
||||
.option('--tenant <t>', '目标租户号 (省略则沿用当前 token 的租户)')
|
||||
.option('--appCode <c>', '目标应用代码 (省略则沿用当前 token 的 appCode)')
|
||||
.option('--account <a>', '账号')
|
||||
.option('--password <p>', '密码')
|
||||
.action(async (opts: { appCode: string; account?: string; password?: string }) => {
|
||||
.action(async (opts: { tenant?: string; appCode?: string; account?: string; password?: string }) => {
|
||||
if (!opts.tenant && !opts.appCode) {
|
||||
log.error('--tenant 与 --appCode 至少要给一个 (都不给就没有东西可切)')
|
||||
log.dim(` 例: dacli app switch --tenant zhangsan`)
|
||||
log.dim(` dacli app switch --appCode myTestApp`)
|
||||
process.exit(1)
|
||||
}
|
||||
const cached = loadToken()
|
||||
const c = await JnpfClient.login({
|
||||
tenant: opts.tenant || cached?.tenant || DEFAULT_TENANT,
|
||||
account: opts.account || cached?.account || DEFAULT_ACCOUNT,
|
||||
password: opts.password || DEFAULT_PASSWORD,
|
||||
appCode: opts.appCode,
|
||||
appCode: opts.appCode || cached?.appCode || DEFAULT_APP_CODE,
|
||||
baseUrl: cached?.baseUrl,
|
||||
forceLogin: true,
|
||||
})
|
||||
log.ok(`切换成功: ${c.account} @ ${c.appCode}`)
|
||||
if (c.tenant) log.dim(`租户 : ${c.tenant}`)
|
||||
log.dim(`dbLinkId : ${c.dbLinkId || '(unknown)'}`)
|
||||
})
|
||||
|
||||
installHelpHook(cmd, {
|
||||
purpose: '切换当前应用, 重新登录并覆盖本地 token. baseline 复刻常用',
|
||||
required: { '--appCode': '目标应用 (testspace=测试场 | jxcj=业务 | developSystem/workSystem=只读 baseline, 禁止改)' },
|
||||
example: ['dacli app switch --appCode=testspace', 'dacli app switch --appCode=jxcj'],
|
||||
purpose: '切换当前租户/应用, 重新登录并覆盖本地 token. token 是**单文件**, 切了就回不去上一个租户',
|
||||
optional: {
|
||||
'--tenant': '目标租户号 (省略沿用当前; JNPF 多租户下账号要带租户号, 切换 = 用新租户重新登录)',
|
||||
'--appCode': '目标应用 (省略沿用当前; 默认 mainSystem=平台占位 | jxcj=业务 | developSystem/workSystem=只读 baseline, 禁止改)',
|
||||
'--account': '账号 (省略沿用当前 token 里的)',
|
||||
'--password': '密码 (省略用默认值 123456 —— 切租户时通常需要重新给)',
|
||||
},
|
||||
example: [
|
||||
'dacli app switch --tenant zhangsan # 只切租户, appCode 沿用',
|
||||
'dacli app switch --appCode=myTestApp # 只切应用, 租户沿用',
|
||||
'dacli app switch --tenant zhangsan --appCode=myTestApp # 两个都切',
|
||||
].join('\n'),
|
||||
notes: [
|
||||
'租户和应用可以分别切, 至少给一个',
|
||||
'切换 = 重新走一次 POST /oauth/Login (密码密码默认 123456, 切租户记得带 --password)',
|
||||
],
|
||||
})
|
||||
|
||||
return cmd
|
||||
|
||||
@@ -41,7 +41,7 @@ interface UseOpts {
|
||||
export function buildAppUseCommand(): Command {
|
||||
const cmd = new Command('use')
|
||||
.description('一体化命令: switch + context + CurrentUser (v3.0+ 新增, AI 工作流一步到位)')
|
||||
.argument('<appCode>', '目标应用代码 (testspace=测试场 | jxcj=业务 | developSystem/workSystem=只读 baseline, 禁止改)')
|
||||
.argument('<appCode>', '目标应用代码 (jxcj=业务 | developSystem/workSystem=只读 baseline, 禁止改)')
|
||||
.option('--account <a>', '账号 (默认从当前 token 读, 否则 admin)')
|
||||
.option('--password <p>', '密码 (默认 123456)')
|
||||
.option('--no-current-user', '跳过 CurrentUser 验证 (默认走, 服务器端确认 token+appCode+用户)')
|
||||
@@ -181,7 +181,7 @@ export function buildAppUseCommand(): Command {
|
||||
'dacli app use jxcj # 切到 jxcj, 拉 context, 验证 CurrentUser',
|
||||
'dacli app use jxcj --json # 同上, 输出完整 JSON (供 AI)',
|
||||
'dacli app use jxcj --no-current-user # 跳过 CurrentUser (快但弱验证)',
|
||||
'dacli app use testspace # 切到 testspace 统一测试场 (新会话默认)',
|
||||
'dacli app use myTestApp # 切到自建测试应用',
|
||||
].join('\n'),
|
||||
source: {
|
||||
web: 'web/apps/jnpf-web-apps-main/src/api/core/user.ts:10-15 getUserInfoApi + web/apps/jnpf-web-apps-main/src/api/system/system.ts + web/apps/jnpf-web-apps-main/src/api/visualdev/Base',
|
||||
|
||||
@@ -171,9 +171,14 @@ export function buildDiCreateCommand(): Command {
|
||||
sortCode: Number(opts.sortCode || '0'),
|
||||
enabledMark: Number(opts.enabledMark || '1'),
|
||||
isPostPosition: Number(opts.isPostPosition || '0'),
|
||||
// web 端 MyBatis-Plus 拦截器用 f_delete_mark 列做 tenant 隔离,
|
||||
// 默认填 0 (不删除). dacli 必须显式给, 否则 mapper insertOrUpdate 后 list 看不见
|
||||
// f_delete_mark 是 MyBatis-Plus @TableLogic 的逻辑删除列, 默认 0 = 未删除。
|
||||
// dacli 必须显式给, 否则 insertOrUpdate 后 list 看不见自己刚建的。
|
||||
deleteMark: 0,
|
||||
// tenantId 在 schema 隔离模式下**恒为 '0'**, 不是"当前租户"。
|
||||
// 实测 public 与 jnpf_tenant_l1d9xv905q31 两个 schema 里 base_visual_dev
|
||||
// 各 119 行, f_tenant_id 全是 '0' —— JNPF 自己的种子数据也这么写。
|
||||
// 只有列隔离模式 (base_tenant.f_type=1, 查询拼 WHERE f_tenant_id=?)
|
||||
// 才拿它当隔离键; 本部署是 schema 隔离 (f_type=0)。别照着旧注释以为该填租户号。
|
||||
tenantId: '0',
|
||||
}
|
||||
if (opts.action !== undefined) body.action = Number(opts.action)
|
||||
|
||||
+27
-4
@@ -7,7 +7,7 @@
|
||||
* 例: baseUrl='http://nginx/api' + path='/visualdev/Base/list' → 'http://nginx/api/visualdev/Base/list'
|
||||
*/
|
||||
import { encryptPassword, isEncrypted } from './crypto.ts'
|
||||
import { loadToken, saveToken, baseUrlCandidates } from './config.ts'
|
||||
import { loadToken, saveToken, baseUrlCandidates, loginAccount } from './config.ts'
|
||||
import { DacliError } from './types.ts'
|
||||
import type { AppContext, FormSummary, JnpfResp, LoginResp, TokenFile } from './types.ts'
|
||||
import { log } from './log.ts'
|
||||
@@ -18,6 +18,14 @@ export interface ClientOptions {
|
||||
appCode?: string
|
||||
account?: string
|
||||
password?: string
|
||||
/**
|
||||
* 租户号 (JNPF 多租户)。登录时与 account 拼成 `租户号@账号` 发给后端,
|
||||
* 后端据此切数据源 (schema 隔离)。account 自带 '@' 时忽略本字段。
|
||||
*
|
||||
* 注意租户**只影响登录**: 签发的 token 里已带租户上下文, 之后每个请求
|
||||
* 都自动落在该租户, 所以不需要 (也不该) 给每个 API 加租户参数。
|
||||
*/
|
||||
tenant?: string
|
||||
/** true=强制不读 token, 重新登录 */
|
||||
forceLogin?: boolean
|
||||
}
|
||||
@@ -25,7 +33,10 @@ export interface ClientOptions {
|
||||
export class JnpfClient {
|
||||
baseUrl: string
|
||||
appCode: string
|
||||
/** 账号 (不含租户号), 保持用户输入的原样便于展示 */
|
||||
account: string
|
||||
/** 租户号; 老 token.json 里可能没有, 回落从 account 拆 */
|
||||
tenant: string
|
||||
password: string
|
||||
token = ''
|
||||
/** 业务库 id, login 后自动拉 */
|
||||
@@ -43,6 +54,12 @@ export class JnpfClient {
|
||||
this.appCode = opt.appCode || ''
|
||||
this.account = opt.account || ''
|
||||
this.password = opt.password || ''
|
||||
// 租户号: account 自带 '@' 时以 account 为准 (与 loginAccount 的优先级一致),
|
||||
// 否则用 opt.tenant。反过来会让 `--account 'zhangsan@admin'` 配上 --tenant 的
|
||||
// 默认值 host 时, 登录串对了但 token.json 把租户记成 host。
|
||||
const at = this.account.indexOf('@')
|
||||
const fromAccount = at >= 0 ? this.account.slice(0, at).trim() : ''
|
||||
this.tenant = (fromAccount || opt.tenant || '').trim()
|
||||
}
|
||||
|
||||
/** 走 token 缓存, 没就登录 */
|
||||
@@ -53,17 +70,19 @@ export class JnpfClient {
|
||||
// 多次会话后 cached.appCode 是上次的, 如果调用方传了 --appCode=<target> 不一致则警告
|
||||
if (opt.appCode && opt.appCode !== cached.appCode) {
|
||||
log.warn(
|
||||
`BS-新10: token 残留到上次 app "${cached.appCode}", 但本次要求 "${opt.appCode}". 建议先 \`dacli app login --account=admin --password=123456 --appCode=${opt.appCode}\``,
|
||||
`BS-新10: token 残留到上次 app "${cached.appCode}", 但本次要求 "${opt.appCode}". 建议先 \`dacli app login --tenant ${cached.tenant || '<租户号>'} --account ${cached.account} --password=*** --appCode=${opt.appCode}\``,
|
||||
)
|
||||
}
|
||||
// BS-新10 主动提示当前 token 状态 (不传 --appCode 时也有用, 让用户知道当前是哪个 app)
|
||||
else if (process.env.DACLI_SHOW_TOKEN === '1') {
|
||||
log.dim(`[token] appCode=${cached.appCode} dbLinkId=${cached.dbLinkId || '(none)'} (set DACLI_SHOW_TOKEN=0 to disable)`)
|
||||
log.dim(`[token] tenant=${cached.tenant || '(none)'} appCode=${cached.appCode} dbLinkId=${cached.dbLinkId || '(none)'} (set DACLI_SHOW_TOKEN=0 to disable)`)
|
||||
}
|
||||
const c = new JnpfClient({
|
||||
baseUrl: opt.baseUrl || cached.baseUrl,
|
||||
appCode: opt.appCode || cached.appCode,
|
||||
account: opt.account || cached.account,
|
||||
// 老 token.json 没有 tenant 字段, 留空让构造函数从 account 里拆
|
||||
tenant: opt.tenant || cached.tenant,
|
||||
password: opt.password || '',
|
||||
})
|
||||
c.token = cached.token
|
||||
@@ -96,7 +115,8 @@ export class JnpfClient {
|
||||
private async doLogin(): Promise<void> {
|
||||
const encrypted = isEncrypted(this.password) ? this.password : encryptPassword(this.password)
|
||||
const body = new URLSearchParams({
|
||||
account: this.account,
|
||||
// 租户在这里一次性并进账号串; 后端拿前缀切数据源, 之后 token 自带上下文
|
||||
account: loginAccount(this.tenant, this.account),
|
||||
password: encrypted,
|
||||
code: '',
|
||||
origin: 'hash',
|
||||
@@ -140,7 +160,10 @@ export class JnpfClient {
|
||||
const t: TokenFile = {
|
||||
baseUrl: this.baseUrl,
|
||||
appCode: this.appCode,
|
||||
// account 存**原样输入**而不是拼好的串: 老 token.json 读出来仍可用,
|
||||
// 且 tenant 字段独立, 不必再从 account 里猜
|
||||
account: this.account,
|
||||
tenant: this.tenant || undefined,
|
||||
token: this.token,
|
||||
loginAt: new Date().toISOString(),
|
||||
dbLinkId: this.dbLinkId,
|
||||
|
||||
+41
-1
@@ -189,7 +189,47 @@ export function currentDatascreenSrc(): string {
|
||||
/** 默认凭据 (供 login 默认值用) */
|
||||
export const DEFAULT_ACCOUNT = process.env.JNPF_ACCOUNT || 'admin'
|
||||
export const DEFAULT_PASSWORD = process.env.JNPF_PASSWORD || '123456'
|
||||
export const DEFAULT_APP_CODE = process.env.JNPF_APP_CODE || 'testspace' // 统一测试场 (developSystem/workSystem 是 JNPF 只读 baseline, 禁止当默认/测试场)
|
||||
// 默认应用代码。
|
||||
//
|
||||
// 曾经默认 'testspace'(公司 JNPF 环境的统一测试场),但只有那套环境里才有这个应用。
|
||||
// 本地/测试集群的 base_system 里没有它,登录后所有 app 命令都会报
|
||||
// 「appCode=xxx 不存在 (base_system 查不到)」。改成 mainSystem —— 它是每个租户
|
||||
// schema 初始化时就带的平台级应用,当「占位 appCode」够用。
|
||||
//
|
||||
// developSystem / workSystem 仍是 JNPF 只读 baseline,不能拿来当默认/测试场。
|
||||
// 要操作具体应用,用 --appCode <code> 或 JNPF_APP_CODE 显式指定。
|
||||
export const DEFAULT_APP_CODE = process.env.JNPF_APP_CODE || 'mainSystem'
|
||||
|
||||
// 默认租户号。
|
||||
//
|
||||
// JNPF 开 MultiTenancy 后, 账号必须写成 `租户号@账号`, 后端拿前半段去问
|
||||
// jnpf-tenant 要 dbName, 再按租户切数据源。缺 '@' 时它把整个账号当租户号去查,
|
||||
// 报「租户不存在」。
|
||||
//
|
||||
// 宿主租户固定是 'host' (02-seed-db.sh 种进 j7tenant.base_tenant, 映射到 j7 的
|
||||
// public schema), 所以默认值取它。
|
||||
export const DEFAULT_TENANT = process.env.JNPF_TENANT || 'host'
|
||||
|
||||
/**
|
||||
* 拼出发给后端的账号: `租户号@账号`。
|
||||
*
|
||||
* account 自带 '@' 时原样返回 —— 这样 `dacli app login --account 'zhangsan@admin'`
|
||||
* 这种既有写法继续能用, 不会拼成 `zhangsan@zhangsan@admin`。
|
||||
*/
|
||||
export function loginAccount(tenant: string | undefined | null, account: string): string {
|
||||
const a = (account || '').trim()
|
||||
if (a.includes('@')) return a
|
||||
const t = (tenant || '').trim()
|
||||
return t ? `${t}@${a}` : a
|
||||
}
|
||||
|
||||
/** 从 `租户号@账号` 拆出两部分; 不含 '@' 时 tenant 为空串 (不是 DEFAULT_TENANT) */
|
||||
export function splitAccount(loginAcc: string): { tenant: string; account: string } {
|
||||
const s = (loginAcc || '').trim()
|
||||
const i = s.indexOf('@')
|
||||
if (i < 0) return { tenant: '', account: s }
|
||||
return { tenant: s.slice(0, i).trim(), account: s.slice(i + 1).trim() }
|
||||
}
|
||||
|
||||
/** baseUrl 兜底列表 (按优先级) */
|
||||
export function baseUrlCandidates(): string[] {
|
||||
|
||||
@@ -24,7 +24,16 @@ export interface LoginResp {
|
||||
export interface TokenFile {
|
||||
baseUrl: string
|
||||
appCode: string
|
||||
/** 发给后端的账号, 多租户下是 `租户号@账号`, 原样保存 */
|
||||
account: string
|
||||
/**
|
||||
* 租户号 (登录态的属性, **不是**请求参数)。
|
||||
*
|
||||
* 单独存一份而不在每次从 account 里拆, 是为了老 token.json (只有 account
|
||||
* 没有 tenant) 仍可用 —— 见 config.ts 的 loginAccount(), 它见到 '@' 就
|
||||
* 不重复拼租户号。
|
||||
*/
|
||||
tenant?: string
|
||||
token: string
|
||||
/** ISO 时间, token 7 天过期 */
|
||||
loginAt: string
|
||||
|
||||
Reference in new issue
Block a user