39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
"use client"
|
|
|
|
import { Button } from "@/components/ui/button"
|
|
import { useAuthStore } from "@/store/auth"
|
|
import { useLoginDialogStore } from "@/store/login-dialog"
|
|
import { useEffect, useRef } from "react"
|
|
|
|
interface AuthGuardProps {
|
|
children: React.ReactNode
|
|
}
|
|
|
|
export function AuthGuard({ children }: AuthGuardProps) {
|
|
const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
|
|
const openLoginDialog = useLoginDialogStore((s) => s.openLoginDialog)
|
|
const hasTriggered = useRef(false)
|
|
|
|
useEffect(() => {
|
|
if (isAuthenticated) {
|
|
hasTriggered.current = false
|
|
return
|
|
}
|
|
if (!hasTriggered.current) {
|
|
hasTriggered.current = true
|
|
openLoginDialog()
|
|
}
|
|
}, [isAuthenticated, openLoginDialog])
|
|
|
|
if (isAuthenticated) {
|
|
return <>{children}</>
|
|
}
|
|
|
|
return (
|
|
<div className="flex min-h-[50vh] flex-col items-center justify-center gap-4 text-center">
|
|
<p className="text-sm text-muted-foreground">请先登录后继续访问此页面</p>
|
|
<Button onClick={() => openLoginDialog()}>登录</Button>
|
|
</div>
|
|
)
|
|
}
|