36 lines
1.0 KiB
TypeScript
36 lines
1.0 KiB
TypeScript
"use client";
|
|
|
|
import React, { useEffect } from "react";
|
|
import { useRouter, usePathname } from "next/navigation";
|
|
import { useAuth } from "@/hooks/useAuth";
|
|
|
|
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
|
const { user, loading } = useAuth();
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
|
|
useEffect(() => {
|
|
if (!loading) {
|
|
if (!user && !pathname.startsWith("/login") && !pathname.startsWith("/register")) {
|
|
router.push("/login");
|
|
}
|
|
}
|
|
}, [user, loading, router, pathname]);
|
|
|
|
if (loading) {
|
|
return (
|
|
<div className="flex items-center justify-center min-h-screen bg-background">
|
|
<div className="text-primary font-display text-2xl animate-pulse">A carregar...</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Se não estiver logado e não estiver numa rota pública, não renderiza nada
|
|
// (o useEffect vai redirecionar)
|
|
if (!user && !pathname.startsWith("/login") && !pathname.startsWith("/register")) {
|
|
return null;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|