75 lines
2.7 KiB
TypeScript
75 lines
2.7 KiB
TypeScript
'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}</>;
|
|
}
|