37 lines
935 B
TypeScript
37 lines
935 B
TypeScript
"use client";
|
|
|
|
import { useEffect, type ReactNode } from "react";
|
|
import { usePathname, useRouter } from "next/navigation";
|
|
import { useAuth } from "./auth-context";
|
|
|
|
const PUBLIC_PATHS = ["/login"];
|
|
|
|
export function AuthGuard({ children }: { children: ReactNode }) {
|
|
const { isAuthenticated, isLoading } = useAuth();
|
|
const pathname = usePathname();
|
|
const router = useRouter();
|
|
|
|
const isPublic = PUBLIC_PATHS.includes(pathname);
|
|
|
|
useEffect(() => {
|
|
if (isLoading) return;
|
|
if (!isAuthenticated && !isPublic) {
|
|
router.replace("/login");
|
|
}
|
|
}, [isAuthenticated, isLoading, isPublic, router]);
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="h-screen flex items-center justify-center bg-[var(--bg-primary)]">
|
|
<div className="text-[var(--text-secondary)] text-sm">加载中...</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!isAuthenticated && !isPublic) {
|
|
return null;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|