forked from admin/hair-keeper
基于Redis失效标记,实现用户权限变更后强制重新登录
This commit is contained in:
@@ -1,7 +1,32 @@
|
||||
'use client'
|
||||
|
||||
import { SessionProvider as NextAuthSessionProvider } from "next-auth/react"
|
||||
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>{children}</NextAuthSessionProvider>
|
||||
}
|
||||
return (
|
||||
<NextAuthSessionProvider>
|
||||
<SessionInvalidationGuard>
|
||||
{children}
|
||||
</SessionInvalidationGuard>
|
||||
</NextAuthSessionProvider>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user