Files
sushub f403a7e80e import: ssw/dacli@eea0ebc (2026-08-12) 起点版本
本仓 2026-08-12 从 ssw main (192.168.1.18:13300/ssw/ssw-mvp) 的
dacli/ subpath 抽取,作为独立仓托管到 gitea:3000/ssw/dacli.git。

- 工作树为 ssw main dacli subpath 最新版 (110 commit, 08-12)
- 历史未带 ssw main 整体历史(避免大仓污染)
- 此为新仓基线 commit,未来以本仓历史为主
2026-08-12 15:58:06 +08:00

101 lines
3.9 KiB
TypeScript

/**
* tests/e2e/_helpers/auth.ts — 浏览器会话管理 helper
*
* 提供 ensureAuth(): 检查 .auth/admin.json 是否新鲜 (≤ TTL),
* 不新鲜则触发完整 UI 登录, 把 cookie + localStorage 写到该文件.
*
* 用法 (spec 内):
* import { ensureAuth, BASE_URL_TDS } from '../_helpers/auth'
* const state = await ensureAuth() // 返回 storageState 路径
* const context = await browser.newContext({ storageState: state })
*
* 或用 Playwright `projects.setup` 模式 (推荐):
* 见 tests/e2e/auth.setup.ts + playwright.config.ts
*
* 关键配置:
* - 登录入口: `${JNPF_BASE}/jnpf_app_tds/login` (即 http://nginx/jnpf_app_tds/login)
* - 字段 id : #form_item_account + #form_item_password
* - 提交按钮: button:has-text("登 录") (注意中间空格)
* - 登录成功: URL 跳到 /home (page.waitForURL '**\/home**')
* - token 全局共享: 在 tds 登录后, 同会话访问 /jnpf_app_workSystem/model/X 也复用 (浏览器层 cookie + storage 全 host 共享)
*
* TTL 策略 (避开 7 天 token 过期):
* - 默认 6 小时 (远短于 dacli 7 天 token TTL, 留容错)
* - .auth/admin.json modtime 超过则重登
*/
import { existsSync, statSync, mkdirSync } from 'node:fs'
import { dirname } from 'node:path'
import type { Page, BrowserContext } from '@playwright/test'
export const AUTH_FILE = '.auth/admin.json'
export const TTL_HOURS = 6
// JNPF_BASE_URL 配套 playwright.config.ts use.baseURL, 默认 http://nginx/
// 注: tests 内部不需要直接拼路径, 用 page.goto('/jnpf_app_tds/login') 走相对路径即可
export const APP_LOGIN_PATH = (appCode: string) => `/jnpf_app_${appCode}/login`
export const APP_HOME_PATH = (appCode: string) => `/jnpf_app_${appCode}/home`
export const APP_MODEL_PATH = (appCode: string, enCode: string) =>
`/jnpf_app_${appCode}/model/${enCode}`
/**
* 判断 .auth/admin.json 是否仍新鲜 (在 TTL 内).
*/
export function isAuthFresh(file = AUTH_FILE, ttlHours = TTL_HOURS): boolean {
if (!existsSync(file)) return false
const ageMs = Date.now() - statSync(file).mtimeMs
return ageMs < ttlHours * 60 * 60 * 1000
}
/**
* 在 page 内完成 admin/123456 UI 登录, 返回 true=成功.
* 不写文件 — 调用方决定是否 saveStorageState.
*/
export async function loginAsAdmin(
page: Page,
opts: { appCode?: string; account?: string; password?: string } = {}
): Promise<boolean> {
const appCode = opts.appCode ?? 'workSystem' // v17 默认改 workSystem (tds DB 已重置)
const account = opts.account ?? 'admin'
const password = opts.password ?? '123456'
await page.goto(APP_LOGIN_PATH(appCode))
await page.waitForLoadState('domcontentloaded')
// 字段 id 是 jnpf 平台稳定契约 (来自 ssw-e2e-test scripts/jnpf_client.py)
await page.fill('#form_item_account', account)
await page.fill('#form_item_password', password)
await page.click('button:has-text("登 录")')
// 等跳到 /home (jnpf 登录成功标志)
try {
await page.waitForURL('**/home**', { timeout: 15_000 })
await page.waitForLoadState('networkidle')
return true
} catch {
return false
}
}
/**
* 全套: 检查 cache → 没 / 过期则用一个临时 context UI 登录 → saveStorageState → 返回路径.
* 用于不走 Playwright `projects.setup` 模式的场景 (单 spec 自给自足).
*/
export async function ensureAuth(
newContext: () => Promise<BrowserContext>,
opts: { appCode?: string; force?: boolean } = {}
): Promise<string> {
if (!opts.force && isAuthFresh()) return AUTH_FILE
mkdirSync(dirname(AUTH_FILE), { recursive: true })
const ctx = await newContext()
const page = await ctx.newPage()
const ok = await loginAsAdmin(page, { appCode: opts.appCode })
if (!ok) {
await ctx.close()
throw new Error(`UI 登录失败 (appCode=${opts.appCode ?? 'tds'})`)
}
await ctx.storageState({ path: AUTH_FILE })
await ctx.close()
return AUTH_FILE
}