mirror of
https://github.com/lucasrcsantana/story-generator.git
synced 2025-12-18 22:37:51 +00:00
56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import React from 'react';
|
|
import { Navigate, useLocation } from 'react-router-dom';
|
|
import { useAuth } from '../../hooks/useAuth';
|
|
import type { AuthContextType } from '../../hooks/useAuth';
|
|
import type { UserRole } from '../../types/supabase';
|
|
|
|
interface ProtectedRouteProps {
|
|
children: React.ReactNode;
|
|
allowedRoles?: UserRole[];
|
|
}
|
|
|
|
export function ProtectedRoute({ children, allowedRoles = [] }: ProtectedRouteProps) {
|
|
const { user, loading, userRole } = useAuth();
|
|
const location = useLocation();
|
|
|
|
console.log('ProtectedRoute - User:', user?.user_metadata);
|
|
console.log('ProtectedRoute - UserRole do contexto:', userRole);
|
|
console.log('ProtectedRoute - Roles permitidas:', allowedRoles);
|
|
|
|
if (loading) {
|
|
return <div>Carregando...</div>;
|
|
}
|
|
|
|
// Se não houver usuário, redireciona para login
|
|
if (!user) {
|
|
return <Navigate to="/login/school" state={{ from: location }} replace />;
|
|
}
|
|
|
|
// Pegar o role diretamente dos metadados do usuário
|
|
const currentRole = user.user_metadata?.role;
|
|
console.log('ProtectedRoute - Role dos metadados:', currentRole);
|
|
|
|
// Se não houver roles requeridas, permite acesso
|
|
if (allowedRoles.length === 0) {
|
|
return <>{children}</>;
|
|
}
|
|
|
|
// Se o usuário não tiver o role necessário
|
|
if (!allowedRoles.includes(currentRole)) {
|
|
console.log('ProtectedRoute - Acesso negado');
|
|
|
|
// Redireciona para a página apropriada
|
|
switch (currentRole) {
|
|
case 'school':
|
|
return <Navigate to="/dashboard" replace />;
|
|
case 'teacher':
|
|
return <Navigate to="/professor" replace />;
|
|
case 'student':
|
|
return <Navigate to="/aluno" replace />;
|
|
default:
|
|
return <Navigate to="/" replace />;
|
|
}
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|