Files
ai-agent/web/components/auth-provider.tsx
T

136 lines
3.2 KiB
TypeScript
Raw Normal View History

2026-04-09 10:01:23 +08:00
"use client"
import {
createContext,
startTransition,
useContext,
useCallback,
useEffect,
useState,
type ReactNode,
} from "react"
import { usePathname, useRouter } from "next/navigation"
import { fetchProfile, logout } from "@/lib/api/auth"
import {
2026-04-30 18:10:01 +08:00
AUTH_SESSION_EXPIRED_EVENT,
2026-04-09 10:01:23 +08:00
clearSession,
readSession,
writeSession,
type AuthSession,
} from "@/lib/auth"
type AuthContextValue = {
session: AuthSession | null
ready: boolean
refreshProfile: () => Promise<void>
signOut: () => Promise<void>
}
const AuthContext = createContext<AuthContextValue | null>(null)
export function AuthProvider({ children }: { children: ReactNode }) {
const pathname = usePathname()
const router = useRouter()
const [session, setSession] = useState<AuthSession | null>(null)
const [ready, setReady] = useState(false)
const isDashboardLoginRoute = pathname?.startsWith("/dashboard/login") ?? false
const requiresAuth =
((pathname?.startsWith("/dashboard") ?? false) ||
(pathname?.startsWith("/workbench") ?? false)) &&
!isDashboardLoginRoute
2026-04-09 10:01:23 +08:00
const refreshProfile = useCallback(async () => {
const stored = readSession()
if (!stored) {
setSession(null)
setReady(true)
return
}
try {
const profile = await fetchProfile()
const nextSession: AuthSession = {
...stored,
user: profile.user,
permissions: profile.permissions,
roles: profile.roles,
accessToken: profile.accessToken || stored.accessToken,
expiresAt: profile.expiresAt || stored.expiresAt,
2026-04-09 10:01:23 +08:00
}
writeSession(nextSession)
setSession(nextSession)
} catch (error) {
const errorCode = (error as Error & { errorCode?: number }).errorCode
if (errorCode === 3000 || errorCode === 3002) {
clearSession()
setSession(null)
if (requiresAuth) {
startTransition(() => {
router.replace("/dashboard/login")
})
}
2026-04-09 10:01:23 +08:00
}
} finally {
setReady(true)
}
2026-04-24 11:27:49 +08:00
}, [requiresAuth, router])
2026-04-09 10:01:23 +08:00
async function signOut() {
2026-04-30 18:10:01 +08:00
try {
await logout()
} finally {
setSession(null)
startTransition(() => {
router.replace("/dashboard/login")
})
}
2026-04-09 10:01:23 +08:00
}
2026-04-30 18:10:01 +08:00
useEffect(() => {
function handleAuthExpired() {
setSession(null)
if (requiresAuth) {
startTransition(() => {
router.replace("/dashboard/login")
})
}
}
window.addEventListener(AUTH_SESSION_EXPIRED_EVENT, handleAuthExpired)
return () => {
window.removeEventListener(AUTH_SESSION_EXPIRED_EVENT, handleAuthExpired)
}
}, [requiresAuth, router])
2026-04-09 10:01:23 +08:00
useEffect(() => {
const stored = readSession()
2026-04-30 18:10:01 +08:00
setSession(stored)
2026-04-09 10:01:23 +08:00
if (stored) {
void refreshProfile()
return
}
setReady(true)
2026-04-24 11:27:49 +08:00
if (requiresAuth) {
2026-04-09 10:01:23 +08:00
startTransition(() => {
router.replace("/dashboard/login")
2026-04-09 10:01:23 +08:00
})
}
2026-04-24 11:27:49 +08:00
}, [requiresAuth, refreshProfile, router])
2026-04-09 10:01:23 +08:00
return (
<AuthContext.Provider value={{ session, ready, refreshProfile, signOut }}>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) {
throw new Error("useAuth must be used within AuthProvider")
}
return ctx
}