Files
gsfdc/portal/app/composables/useAgentAuth.ts
T
wuzilongandCursor 9c7c80e194 feat: 把估价智能体和部署配置提交到主分支
门户估价对话、会员与智能体账号,以及生产 Docker 部署一直停在工作区,远端主分支还没有这些改动。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 09:42:44 +08:00

104 lines
2.6 KiB
TypeScript

const TOKEN_KEY = "gsfdc_agent_token"
type AgentProfile = {
username: string
displayName: string
canManage?: boolean
}
export function useAgentAuth() {
const token = useState<string | null>("agent-token", () => null)
const username = useState<string | null>("agent-username", () => null)
const displayName = useState<string | null>("agent-display-name", () => null)
const ready = useState("agent-auth-ready", () => false)
const { get } = useSiteApi()
function readStored() {
if (!import.meta.client) return null
return window.localStorage.getItem(TOKEN_KEY)
}
function persist(next: string | null) {
if (!import.meta.client) return
if (next) window.localStorage.setItem(TOKEN_KEY, next)
else window.localStorage.removeItem(TOKEN_KEY)
}
async function refreshProfile() {
if (!token.value) {
username.value = null
displayName.value = null
return null
}
try {
const me = await get<AgentProfile>("/auth/agent/me", token.value)
username.value = me.username
displayName.value = me.displayName || me.username
return me
} catch (exc: any) {
const status = Number(exc?.statusCode || exc?.response?.status || 0)
if (status === 401 || status === 403) {
token.value = null
username.value = null
displayName.value = null
persist(null)
}
return null
}
}
function takeHashToken() {
if (!import.meta.client) return ""
const hash = new URLSearchParams(window.location.hash.replace(/^#/, ""))
const handed = hash.get("agentToken") || ""
if (!handed) return ""
hash.delete("agentToken")
const next = hash.toString()
const url = `${window.location.pathname}${window.location.search}${next ? `#${next}` : ""}`
window.history.replaceState(null, "", url)
return handed
}
async function ensure() {
if (!import.meta.client) return
const handed = takeHashToken()
if (handed) {
await setSession(handed)
return
}
if (ready.value) return
const stored = readStored()
token.value = stored
if (stored) await refreshProfile()
ready.value = true
}
async function setSession(accessToken: string) {
token.value = accessToken
persist(accessToken)
ready.value = true
await refreshProfile()
}
function clearSession() {
token.value = null
username.value = null
displayName.value = null
persist(null)
}
const isAuthed = computed(() => Boolean(token.value))
return {
token,
username,
displayName,
ready,
isAuthed,
ensure,
setSession,
clearSession,
refreshProfile,
}
}