Files
agent-desk-ng/web/components/auth-provider.tsx
mono 63e0457886 fix: harden identity, live access, drafts and setup (review only)
Source-reviewed hardening changes and regression tests. UNBUILT / UNTESTED: not a deployable release. Go formatting, compilation, automated regression tests, full frontend validation and staging acceptance remain required. See docs/hardening/VALIDATION.md. Main remains the original clean snapshot; no upstream Git history imported.
2026-10-16 12:15:20 +00:00

85 lines
2.3 KiB
TypeScript

// Modified in the independent hardening fork; see docs/hardening/README.md.
// Modified for AgentDeskFixes: prevent a late logout from redirecting a newer login.
"use client"
import {
createContext,
startTransition,
useContext,
useCallback,
useEffect,
type ReactNode,
} from "react"
import { usePathname, useRouter } from "next/navigation"
import { SessionProvider, useSession } from "@/components/session-provider"
import { readSession, 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 }) {
return (
<SessionProvider>
<DashboardAuthProvider>{children}</DashboardAuthProvider>
</SessionProvider>
)
}
function DashboardAuthProvider({ children }: { children: ReactNode }) {
const pathname = usePathname()
const router = useRouter()
const { session, ready, refreshSession, signOut: endSession } = useSession()
const isDashboardLoginRoute = pathname?.startsWith("/dashboard/login") ?? false
const requiresAuth =
((pathname?.startsWith("/dashboard") ?? false) ||
(pathname?.startsWith("/workbench") ?? false)) &&
!isDashboardLoginRoute
const refreshProfile = useCallback(() => refreshSession(), [refreshSession])
async function signOut() {
try {
await endSession()
} finally {
// A different tab or login flow may have established a new session meanwhile.
if (!readSession()) {
startTransition(() => {
router.replace("/dashboard/login")
})
}
}
}
useEffect(() => {
if (ready && !session && requiresAuth) {
// A different tab or login flow may have established a new session meanwhile.
if (!readSession()) {
startTransition(() => {
router.replace("/dashboard/login")
})
}
}
}, [ready, requiresAuth, router, session])
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
}