Files
knowledge-governance/web/src/DWSAccount.tsx
T
姚章浩 3825859da6
build / build (push) Successful in 2m20s
feat(settings): 打通 PP 认证配置并统一 DWS 来源授权
PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。
钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。
认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。

验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。
尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
2026-11-17 19:08:46 +08:00

314 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useRef, useState } from 'react'
import {
cancelDWSLogin,
checkDWSConnection,
dwsLoginActive,
fetchDWSCredentials,
fetchDWSLogin,
startDWSLogin,
} from './dwsLogin'
import type { DWSCredentials, DWSLogin } from './dwsLogin'
const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : '请求失败,请重试')
const moment = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
export function DWSAccount({
autoStart = false,
onAuthorized,
onCredentials,
onCancel,
}: {
autoStart?: boolean
onAuthorized?: (credentials: DWSCredentials) => void
onCredentials?: (credentials: DWSCredentials) => void
onCancel?: () => void
} = {}) {
const callbacks = useRef({ onAuthorized, onCredentials, onCancel })
callbacks.current = { onAuthorized, onCredentials, onCancel }
const startedAutomatically = useRef(false)
const [credentials, setCredentials] = useState<DWSCredentials | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [notice, setNotice] = useState('')
const [connection, setConnection] = useState<Awaited<ReturnType<typeof checkDWSConnection>> | null>(null)
const [checking, setChecking] = useState(false)
const [session, setSession] = useState<DWSLogin | null>(null)
const [open, setOpen] = useState(false)
const [starting, setStarting] = useState(false)
const [loginError, setLoginError] = useState('')
const id = useRef('')
const generation = useRef(0)
const mounted = useRef(false)
const handled = useRef('')
const action = useRef<AbortController | null>(null)
const checkAction = useRef<AbortController | null>(null)
useEffect(() => {
mounted.current = true
const controller = new AbortController()
void fetchDWSCredentials(controller.signal)
.then((fresh) => {
setCredentials(fresh)
callbacks.current.onCredentials?.(fresh)
})
.catch((cause) => {
if (!controller.signal.aborted) setError(messageOf(cause))
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => {
mounted.current = false
controller.abort()
action.current?.abort()
checkAction.current?.abort()
generation.current++
if (id.current) void cancelDWSLogin(id.current).catch(() => undefined)
}
}, [])
const check = useCallback(async () => {
checkAction.current?.abort()
const controller = new AbortController()
checkAction.current = controller
setChecking(true)
setConnection(null)
setError('')
try {
const result = await checkDWSConnection(controller.signal)
const fresh = await fetchDWSCredentials(controller.signal)
if (!controller.signal.aborted && mounted.current) {
setConnection(result)
setCredentials(fresh)
}
} catch (cause) {
if (!controller.signal.aborted && mounted.current) setError(`目录连接检查未通过:${messageOf(cause)}`)
} finally {
if (!controller.signal.aborted && mounted.current) setChecking(false)
}
}, [])
const start = async () => {
const current = ++generation.current
action.current?.abort()
checkAction.current?.abort()
setChecking(false)
const controller = new AbortController()
action.current = controller
setOpen(true)
setStarting(true)
setSession(null)
setLoginError('')
setNotice('')
setConnection(null)
setError('')
try {
const next = await startDWSLogin(controller.signal)
if (!mounted.current || current !== generation.current) {
void cancelDWSLogin(next.id).catch(() => undefined)
return
}
id.current = next.id
setSession(next)
} catch (cause) {
if (mounted.current && current === generation.current) setLoginError(messageOf(cause))
} finally {
if (mounted.current && current === generation.current) setStarting(false)
}
}
useEffect(() => {
if (autoStart && !startedAutomatically.current) {
startedAutomatically.current = true
void start()
}
}, [autoStart])
const close = async () => {
const current = generation.current
const sessionID = id.current
setLoginError('')
if (!sessionID && starting) {
// Keep the POST alive so its returned session can be cancelled by ID.
++generation.current
setOpen(false)
setStarting(false)
callbacks.current.onCancel?.()
return
}
if (sessionID && session && dwsLoginActive(session.state)) {
try {
await cancelDWSLogin(sessionID)
} catch (cause) {
if (mounted.current && generation.current === current) setLoginError(`取消未完成:${messageOf(cause)}`)
return
}
}
if (mounted.current && generation.current === current) {
++generation.current
id.current = ''
setOpen(false)
setSession(null)
callbacks.current.onCancel?.()
}
}
useEffect(() => {
if (!session || !dwsLoginActive(session.state) || loginError) return
const controller = new AbortController()
const current = generation.current
const timer = window.setTimeout(() => {
void fetchDWSLogin(session.id, controller.signal)
.then((next) => {
if (!controller.signal.aborted && current === generation.current) setSession(next)
})
.catch((cause) => {
if (!controller.signal.aborted && current === generation.current) setLoginError(messageOf(cause))
})
}, 1500)
return () => {
window.clearTimeout(timer)
controller.abort()
}
}, [session, loginError])
useEffect(() => {
if (session?.state !== 'succeeded' || handled.current === session.id) return
handled.current = session.id
const current = generation.current
id.current = ''
setOpen(false)
setNotice('DWS 登录成功,正在检查目录连接…')
void fetchDWSCredentials()
.then((fresh) => {
if (!mounted.current || current !== generation.current) return
setCredentials(fresh)
setNotice('DWS 登录成功')
callbacks.current.onCredentials?.(fresh)
void check()
callbacks.current.onAuthorized?.(fresh)
})
.catch((cause) => {
if (mounted.current && current === generation.current) setError(`授权成功,状态刷新失败:${messageOf(cause)}`)
})
}, [session, check])
const status = loading
? '读取中…'
: error && !credentials
? '状态读取失败'
: !credentials?.status_known
? '登录状态待核验'
: !credentials.authenticated
? '未登录'
: credentials.refresh_token_valid
? '已登录'
: '凭证需更新'
const busy = starting || Boolean(session && dwsLoginActive(session.state))
const labels: Record<DWSLogin['state'], string> = {
starting: '正在生成授权入口…',
waiting: '请打开钉钉授权页,确认本次登录。完成后此页会自动更新。',
verifying: '已收到授权,正在验证并保存登录状态…',
succeeded: '登录成功',
expired: '授权已过期,请重新发起。',
failed: '授权未完成,请重试。',
cancelled: '授权已取消。',
}
return (
<section className="source-account" aria-label="钉钉账号(DWS)">
<div className="dws-account-heading">
<div>
<strong>钉钉账号(DWS) · {status}</strong>
{credentials?.authenticated ? (
<div>
{[credentials.user_name, credentials.corp_name].filter(Boolean).join(' · ') || '账号信息暂未返回'}
</div>
) : null}
{credentials?.authenticated && credentials.refresh_expires_at ? (
<small>授权有效期至 {moment(credentials.refresh_expires_at)}</small>
) : null}
</div>
<div className="row-actions">
<button onClick={() => void start()} disabled={busy}>
{busy ? '授权进行中…' : credentials?.authenticated ? '重新授权' : '登录授权'}
</button>
<button className="secondary" onClick={() => void check()} disabled={checking || busy}>
{checking ? '检查中…' : '检查连接'}
</button>
</div>
</div>
<small>所有钉钉来源共用此账号。登录后检查知识库与钉盘的实际访问权限。</small>
{notice ? (
<p role="status" className="success-message">
{notice}
</p>
) : null}
{error ? (
<p role="alert" className="error-message">
{error}
</p>
) : null}
{connection ? (
<div role="status">
<p className={connection.notices.length ? 'hint' : 'success-message'}>
{connection.notices.length ? '目录部分可用' : '目录连接正常'}:{connection.message} · 检查于{' '}
{moment(connection.checkedAt)}
</p>
{connection.notices.map((value) => (
<p className="hint" key={value}>
{value}
</p>
))}
</div>
) : null}
{open ? (
<div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="DWS 登录授权">
<div className="modal-card dws-login-card">
<h3>DWS 登录授权</h3>
<p role="status">{starting ? '正在生成授权入口…' : session ? labels[session.state] : '授权入口生成失败'}</p>
{session?.state === 'waiting' && session.verification_url ? (
<>
<a
className="primary-action dws-authorize-link"
href={session.verification_url}
target="_blank"
rel="noopener noreferrer"
referrerPolicy="no-referrer"
>
打开钉钉授权页
</a>
<p>
若授权页要求输入授权码:<code className="dws-user-code">{session.user_code}</code>
</p>
<small>本次授权有效期至 {moment(session.expires_at)}</small>
</>
) : null}
{session?.error ? (
<p role="alert" className="error-message">
{session.error}
</p>
) : null}
{loginError ? (
<p role="alert" className="error-message">
{loginError}
</p>
) : null}
<div className="row-actions">
{session && !dwsLoginActive(session.state) ? (
<button onClick={() => void start()}>重新发起授权</button>
) : null}
{loginError && session && dwsLoginActive(session.state) ? (
<button onClick={() => setLoginError('')}>重试读取状态</button>
) : null}
{!starting && !session ? <button onClick={() => void start()}>重试</button> : null}
<button className="secondary" onClick={() => void close()}>
{busy ? '取消授权' : '关闭'}
</button>
</div>
</div>
</div>
) : null}
</section>
)
}