mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-14 10:53:50 +08:00
Query user profile via intranet direct HTTP; upgrade/clear trust sessions without department.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
74a86ff832
commit
9ff9635624
5 changed files with 262 additions and 148 deletions
|
|
@ -1,15 +1,16 @@
|
|||
import { UdsClient } from '../uds/client.js'
|
||||
import { UdsValidator } from '../uds/validator.js'
|
||||
import { ROLES, computePermissions } from '../roles.js'
|
||||
import { searchUserByEmpNoToken } from '../uds/user-search.js'
|
||||
|
||||
/**
|
||||
* auth-middleware
|
||||
*
|
||||
* 正常登录:Cookie 中必须同时有 empNo + token,并用 userSearchUrl
|
||||
* (带 X-Emp-No / X-Auth-Value)拉用户详情;两者都成功才建会话。
|
||||
* (带 X-Emp-No / X-Auth-Value)直连内网拉用户详情;成功才建会话。
|
||||
* 出站请求绕过 HTTP(S)_PROXY。
|
||||
*
|
||||
* 兜底登录:仅认可已由 /api/fallback/login 写好的 administrator 会话;
|
||||
* 禁止仅靠伪造 UDS_FALLBACK_USER Cookie 提权。
|
||||
* 兜底登录:仅认可已由 /api/fallback/login 写好的 administrator 会话。
|
||||
*/
|
||||
export function createAuthMiddleware(config, sessionStore, rolesStore) {
|
||||
const udsClient = new UdsClient(config.udsAuth)
|
||||
|
|
@ -30,99 +31,46 @@ export function createAuthMiddleware(config, sessionStore, rolesStore) {
|
|||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* empNo + token → 调用户搜索接口;返回解析后的 profile 或 null
|
||||
*/
|
||||
function applyProfile(userContext, profile, credentials) {
|
||||
userContext.userId = profile.empNo
|
||||
userContext.empNo = profile.empNo
|
||||
userContext.username = profile.username
|
||||
userContext.displayName = profile.username
|
||||
userContext.department = profile.department
|
||||
userContext.organization = profile.organization || profile.department || ''
|
||||
userContext.email = profile.email
|
||||
userContext.phone = profile.phone
|
||||
userContext.token = credentials.token
|
||||
userContext.lang = credentials.lang || userContext.lang || 'zh-CN'
|
||||
userContext.isAuthenticated = true
|
||||
userContext.authMode = 'token+profile'
|
||||
userContext.lastActiveAt = new Date().toISOString()
|
||||
return userContext
|
||||
}
|
||||
|
||||
async function verifyEmpNoAndToken(empNo, token) {
|
||||
if (!userSearchUrl || !empNo || !token) {
|
||||
console.warn('[uds-auth] verifyEmpNoAndToken skipped: missing', {
|
||||
hasUrl: !!userSearchUrl, hasEmpNo: !!empNo, hasToken: !!token,
|
||||
})
|
||||
const out = await searchUserByEmpNoToken({
|
||||
userSearchUrl,
|
||||
empNo,
|
||||
token,
|
||||
empNoHeader: config.udsAuth?.empNoHeader || 'X-Emp-No',
|
||||
authValueHeader: config.udsAuth?.authValueHeader || 'X-Auth-Value',
|
||||
origin: uacBaseUrl || undefined,
|
||||
})
|
||||
if (!out.ok) {
|
||||
console.warn('[uds-auth] verifyEmpNoAndToken failed:', out)
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const targetUrl = new URL(userSearchUrl)
|
||||
const body = JSON.stringify({
|
||||
employeeShortId: empNo,
|
||||
enableLabel: true,
|
||||
keyword: empNo,
|
||||
})
|
||||
const headers = {
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
[config.udsAuth?.empNoHeader || 'X-Emp-No']: empNo,
|
||||
[config.udsAuth?.authValueHeader || 'X-Auth-Value']: token,
|
||||
}
|
||||
if (uacBaseUrl) {
|
||||
headers.Origin = uacBaseUrl
|
||||
headers.Referer = uacBaseUrl.replace(/\/?$/, '/')
|
||||
}
|
||||
return out.profile
|
||||
}
|
||||
|
||||
const isHttps = targetUrl.protocol === 'https:'
|
||||
const mod = await import(isHttps ? 'node:https' : 'node:http')
|
||||
const { statusCode, result } = await new Promise((resolve, reject) => {
|
||||
const req = mod.request({
|
||||
hostname: targetUrl.hostname,
|
||||
port: targetUrl.port || (isHttps ? 443 : 80),
|
||||
path: targetUrl.pathname + targetUrl.search,
|
||||
method: 'POST',
|
||||
headers,
|
||||
timeout: 8000,
|
||||
}, (res) => {
|
||||
let data = ''
|
||||
res.on('data', (c) => { data += c })
|
||||
res.on('end', () => {
|
||||
let parsed = null
|
||||
try { parsed = JSON.parse(data) } catch { parsed = { raw: String(data).slice(0, 300) } }
|
||||
resolve({ statusCode: res.statusCode, result: parsed })
|
||||
})
|
||||
})
|
||||
req.on('error', reject)
|
||||
req.on('timeout', () => { req.destroy(); reject(new Error('user-info timeout')) })
|
||||
req.write(body)
|
||||
req.end()
|
||||
})
|
||||
|
||||
const code = result?.code?.code ?? result?.code
|
||||
if (code !== '0000' && code !== 0 && code !== '0') {
|
||||
console.warn('[uds-auth] userSearch failed:', {
|
||||
empNo, statusCode, code, msg: result?.code?.msg || result?.msg || result?.raw,
|
||||
})
|
||||
return null
|
||||
}
|
||||
const list = Array.isArray(result?.bo) ? result.bo
|
||||
: Array.isArray(result?.bo?.rows) ? result.bo.rows
|
||||
: Array.isArray(result?.bo?.list) ? result.bo.list
|
||||
: []
|
||||
if (!list.length) {
|
||||
console.warn('[uds-auth] userSearch empty bo:', { empNo, statusCode, keys: result && Object.keys(result) })
|
||||
return null
|
||||
}
|
||||
const emp = list[0]
|
||||
const resolvedEmpNo = String(
|
||||
emp.employeeShortId || emp.employeeNO || emp.empUIID || emp.empNo || empNo,
|
||||
).trim()
|
||||
// 工号必须对得上(防 token 有效但查了别人)
|
||||
if (resolvedEmpNo && resolvedEmpNo !== String(empNo).trim()
|
||||
&& !String(empNo).includes(resolvedEmpNo)
|
||||
&& !resolvedEmpNo.includes(String(empNo).trim())) {
|
||||
// 宽松:短工号/长工号互含即通过;完全无关则拒绝
|
||||
const a = String(empNo).replace(/\D/g, '')
|
||||
const b = resolvedEmpNo.replace(/\D/g, '')
|
||||
if (!a || !b || !(a.includes(b) || b.includes(a))) return null
|
||||
}
|
||||
return {
|
||||
empNo: String(empNo).trim(),
|
||||
username: emp.name || emp.empName || emp.userName || empNo,
|
||||
department: emp.deptName || emp.deptShortName || emp.orgName || emp.department || '',
|
||||
email: emp.email || emp.mail || '',
|
||||
phone: emp.mobile || emp.phone || '',
|
||||
token,
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[uds-auth] verifyEmpNoAndToken failed:', err.message)
|
||||
return null
|
||||
}
|
||||
function needsProfileUpgrade(userContext) {
|
||||
if (!userContext) return true
|
||||
if (userContext.authMode === 'trust') return true
|
||||
if (userContext.authMode !== 'token+profile') return true
|
||||
const name = userContext.displayName || userContext.username || ''
|
||||
if (!name || name === userContext.empNo) return true
|
||||
return false
|
||||
}
|
||||
|
||||
async function authMiddleware(ctx, next) {
|
||||
|
|
@ -132,8 +80,31 @@ export function createAuthMiddleware(config, sessionStore, rolesStore) {
|
|||
|
||||
if (!extracted) return next()
|
||||
|
||||
// 1. 已有会话 → 滑动续期
|
||||
let userContext = await sessionStore.get(extracted.empNo)
|
||||
|
||||
// 旧 trust 会话 / 无姓名部门:强制用 token 重查用户信息
|
||||
if (userContext && extracted.kind === 'uds' && needsProfileUpgrade(userContext)) {
|
||||
const credentials = udsValidator.extractCredentials(req)
|
||||
if (credentials && credentials.empNo === extracted.empNo && udsValidator.validateCredentials(credentials)) {
|
||||
const profile = await verifyEmpNoAndToken(credentials.empNo, credentials.token)
|
||||
if (profile) {
|
||||
userContext = applyProfile(userContext, profile, credentials)
|
||||
await sessionStore.setex(
|
||||
profile.empNo,
|
||||
Math.floor(cookieMaxAge / 1000),
|
||||
userContext,
|
||||
)
|
||||
} else {
|
||||
// 查不到资料则作废 trust 会话,避免“假登录”
|
||||
await sessionStore.delete(extracted.empNo)
|
||||
userContext = null
|
||||
}
|
||||
} else if (userContext.authMode === 'trust') {
|
||||
await sessionStore.delete(extracted.empNo)
|
||||
userContext = null
|
||||
}
|
||||
}
|
||||
|
||||
if (userContext) {
|
||||
if (slidingExpiration) {
|
||||
userContext.lastActiveAt = new Date().toISOString()
|
||||
|
|
@ -151,13 +122,10 @@ export function createAuthMiddleware(config, sessionStore, rolesStore) {
|
|||
return next()
|
||||
}
|
||||
|
||||
// 2. 无会话
|
||||
// 兜底 Cookie:绝不在这里建会话(必须走密码登录)
|
||||
if (extracted.kind === 'fallback') {
|
||||
return next()
|
||||
}
|
||||
|
||||
// UDS:必须 empNo + token,且用户详情接口校验通过
|
||||
const credentials = udsValidator.extractCredentials(req)
|
||||
if (!credentials || !udsValidator.validateCredentials(credentials)) {
|
||||
return next()
|
||||
|
|
@ -176,19 +144,15 @@ export function createAuthMiddleware(config, sessionStore, rolesStore) {
|
|||
token: credentials.token,
|
||||
lang: credentials.lang,
|
||||
username: profile.username,
|
||||
displayName: profile.username,
|
||||
department: profile.department,
|
||||
organization: profile.organization,
|
||||
email: profile.email,
|
||||
phone: profile.phone,
|
||||
}, false)
|
||||
userContext.username = profile.username
|
||||
userContext.displayName = profile.username
|
||||
userContext.department = profile.department
|
||||
userContext.email = profile.email
|
||||
userContext.phone = profile.phone
|
||||
applyProfile(userContext, profile, credentials)
|
||||
userContext.authenticatedAt = new Date().toISOString()
|
||||
userContext.lastActiveAt = new Date().toISOString()
|
||||
userContext.isAuthenticated = true
|
||||
userContext.authMode = 'token+profile'
|
||||
userContext.sessionCreatedAt = new Date().toISOString()
|
||||
|
||||
await sessionStore.setex(
|
||||
profile.empNo,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue