feat: Implementação de submenus laterais (flyout), correções de UI e proteção de rotas (AuthGuard)
This commit is contained in:
47
front-end-agency/components/auth/AuthGuard.tsx
Normal file
47
front-end-agency/components/auth/AuthGuard.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter, usePathname } from 'next/navigation';
|
||||
import { isAuthenticated } from '@/lib/auth';
|
||||
|
||||
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [authorized, setAuthorized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = () => {
|
||||
const isAuth = isAuthenticated();
|
||||
|
||||
if (!isAuth) {
|
||||
setAuthorized(false);
|
||||
// Evitar redirect loop se já estiver no login (embora o AuthGuard deva ser usado apenas em rotas protegidas)
|
||||
if (pathname !== '/login') {
|
||||
router.push('/login');
|
||||
}
|
||||
} else {
|
||||
setAuthorized(true);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
|
||||
// Opcional: Adicionar listener para storage events para logout em outras abas
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === 'token' || e.key === 'user') {
|
||||
checkAuth();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [router, pathname]);
|
||||
|
||||
// Enquanto verifica, não renderiza nada ou um loading
|
||||
// Para evitar "flash" de conteúdo não autorizado
|
||||
if (!authorized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
Reference in New Issue
Block a user