Files
cunkebao_v3/Cunkebao/components/AuthCheck.tsx

43 lines
1.1 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 { useEffect } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { useAuth } from '@/hooks/useAuth'
// 不需要登录的公共页面路径
const PUBLIC_PATHS = [
'/login',
'/register',
'/forgot-password',
'/reset-password',
'/404',
'/500'
]
export function AuthCheck({ children }: { children: React.ReactNode }) {
const router = useRouter()
const pathname = usePathname()
const { isAuthenticated, isLoading } = useAuth()
useEffect(() => {
if (!isLoading && !isAuthenticated && !PUBLIC_PATHS.includes(pathname)) {
// 保存当前URL登录后可以重定向回来
const returnUrl = encodeURIComponent(window.location.href)
router.push(`/login?returnUrl=${returnUrl}`)
}
}, [isAuthenticated, isLoading, pathname, router])
if (isLoading) {
return (
<div className="flex h-screen w-screen items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
)
}
if (!isAuthenticated && !PUBLIC_PATHS.includes(pathname)) {
return null
}
return <>{children}</>
}