Files
stu-ai-demo/src/components/providers/session-provider.tsx

33 lines
1.0 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.
'use client'
import { SessionProvider as NextAuthSessionProvider, signOut, useSession } from "next-auth/react"
import { useEffect, useRef } from "react"
import { usePathname } from "next/navigation"
/** 检测会话失效并自动登出 */
function SessionInvalidationGuard({ children }: { children: React.ReactNode }) {
const { data: session, status } = useSession()
const pathname = usePathname()
const signingOut = useRef(false)
useEffect(() => {
// 已认证但 session 中没有 user会话被标记失效自动登出清除 cookie
if (status === 'authenticated' && !(session as any)?.user?.id && !signingOut.current && pathname !== '/login') {
signingOut.current = true
signOut({ callbackUrl: '/login' })
}
}, [status, session, pathname])
return <>{children}</>
}
export function SessionProvider({ children }: { children: React.ReactNode }) {
return (
<NextAuthSessionProvider>
<SessionInvalidationGuard>
{children}
</SessionInvalidationGuard>
</NextAuthSessionProvider>
)
}