Files
cunkebao_v3/Cunkebao/app/components/auth-check.tsx

27 lines
809 B
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"
export function AuthCheck({ children }: { children: React.ReactNode }) {
const router = useRouter()
const pathname = usePathname()
useEffect(() => {
// 排除不需要登录的页面
const publicPaths = ['/login', '/register', '/forgot-password']
if (publicPaths.includes(pathname)) {
return
}
const token = localStorage.getItem('token')
if (!token) {
// 如果没有token重定向到登录页面并携带当前页面URL作为回调
const currentPath = window.location.pathname + window.location.search
router.push(`/login?redirect=${encodeURIComponent(currentPath)}`)
return
}
}, [router, pathname])
return <>{children}</>
}