私域操盘手 - 增加路由守卫,拦截所有未登录的页面及页面请求
This commit is contained in:
27
Cunkebao/app/components/auth-check.tsx
Normal file
27
Cunkebao/app/components/auth-check.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
"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}</>
|
||||
}
|
||||
14
Cunkebao/app/components/ui/toast.ts
Normal file
14
Cunkebao/app/components/ui/toast.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
Reference in New Issue
Block a user