chore(release): snapshot 1.4.2
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter, usePathname } from 'next/navigation';
|
||||
import { isAuthenticated } from '@/lib/auth';
|
||||
import { isAuthenticated, clearAuth } from '@/lib/auth';
|
||||
|
||||
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
@@ -22,9 +22,9 @@ export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
|
||||
if (!isAuth) {
|
||||
setAuthorized(false);
|
||||
// Evitar redirect loop se já estiver no login (embora o AuthGuard deva ser usado apenas em rotas protegidas)
|
||||
// Evitar redirect loop se já estiver no login
|
||||
if (pathname !== '/login') {
|
||||
router.push('/login');
|
||||
router.push('/login?error=unauthorized');
|
||||
}
|
||||
} else {
|
||||
setAuthorized(true);
|
||||
@@ -33,7 +33,7 @@ export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
|
||||
checkAuth();
|
||||
|
||||
// Opcional: Adicionar listener para storage events para logout em outras abas
|
||||
// Listener para logout em outras abas
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === 'token' || e.key === 'user') {
|
||||
checkAuth();
|
||||
@@ -44,8 +44,7 @@ export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
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
|
||||
// Enquanto verifica, mostra loading
|
||||
if (!mounted || authorized === null) {
|
||||
return (
|
||||
<div className="flex h-screen w-full items-center justify-center bg-gray-100 dark:bg-zinc-950">
|
||||
|
||||
74
front-end-agency/components/auth/SolutionGuard.tsx
Normal file
74
front-end-agency/components/auth/SolutionGuard.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter, usePathname } from 'next/navigation';
|
||||
import { useToast } from '@/components/layout/ToastContext';
|
||||
|
||||
interface SolutionGuardProps {
|
||||
children: React.ReactNode;
|
||||
requiredSolution: string; // slug da solução (ex: 'crm', 'erp')
|
||||
}
|
||||
|
||||
export function SolutionGuard({ children, requiredSolution }: SolutionGuardProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const { error } = useToast();
|
||||
const [hasAccess, setHasAccess] = useState<boolean | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAccess = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/tenant/solutions', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const solutions = data.solutions || [];
|
||||
const solutionSlugs = solutions.map((s: any) => s.slug.toLowerCase());
|
||||
|
||||
// Dashboard é sempre permitido
|
||||
if (requiredSolution === 'dashboard') {
|
||||
setHasAccess(true);
|
||||
} else {
|
||||
const hasPermission = solutionSlugs.includes(requiredSolution.toLowerCase());
|
||||
|
||||
if (!hasPermission) {
|
||||
// Mostra toast de aviso
|
||||
error('Acesso Negado', 'Você não tem acesso a este módulo. Contate o suporte para mais informações.');
|
||||
|
||||
// Redireciona imediatamente
|
||||
router.replace('/dashboard');
|
||||
return;
|
||||
}
|
||||
|
||||
setHasAccess(hasPermission);
|
||||
}
|
||||
} else {
|
||||
// Em caso de erro, redireciona para segurança
|
||||
error('Erro de Acesso', 'Não foi possível verificar suas permissões. Contate o suporte.');
|
||||
router.replace('/dashboard');
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
// Em caso de erro, redireciona para segurança
|
||||
error('Erro de Acesso', 'Não foi possível verificar suas permissões. Contate o suporte.');
|
||||
router.replace('/dashboard');
|
||||
return;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAccess();
|
||||
}, [requiredSolution, router, pathname, error]);
|
||||
|
||||
if (loading || hasAccess === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
Reference in New Issue
Block a user