- Validação cross-tenant no login e rotas protegidas
- File serving via /api/files/{bucket}/{path} (eliminação DNS)
- Mensagens de erro humanizadas inline (sem pop-ups)
- Middleware tenant detection via headers customizados
- Upload de logos retorna URLs via API
- README atualizado com changelog v1.4 completo
67 lines
2.2 KiB
TypeScript
67 lines
2.2 KiB
TypeScript
'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<boolean | null>(null);
|
|
const [mounted, setMounted] = useState(false);
|
|
|
|
useEffect(() => {
|
|
setMounted(true);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!mounted) return;
|
|
|
|
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, mounted]);
|
|
|
|
// Enquanto verifica (ou não está montado), mostra um loading simples
|
|
// Isso evita problemas de hidratação mantendo a estrutura DOM consistente
|
|
if (!mounted || authorized === null) {
|
|
return (
|
|
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!authorized) {
|
|
return (
|
|
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-purple-600" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|