saveinmed/frontend/src/components/ProtectedRoute.tsx

41 lines
945 B
TypeScript

import { Navigate } from 'react-router-dom'
import { ReactNode } from 'react'
import { useAuth, UserRole } from '../context/AuthContext'
interface ProtectedRouteProps {
children: ReactNode
allowedRoles?: UserRole[]
}
const getFallbackRoute = (role?: UserRole) => {
switch (role) {
case 'admin':
return '/dashboard'
case 'owner':
return '/seller'
case 'employee':
return '/colaborador'
case 'delivery':
return '/entregas'
default:
return '/login'
}
}
export function ProtectedRoute({ children, allowedRoles }: ProtectedRouteProps) {
const { user, loading } = useAuth()
if (loading) {
return <div className="p-6 text-center">Carregando sessao...</div>
}
if (!user) {
return <Navigate to="/login" replace />
}
if (allowedRoles && !allowedRoles.includes(user.role)) {
return <Navigate to={getFallbackRoute(user.role)} replace />
}
return <>{children}</>
}