import { Navigate, useLocation } from 'react-router-dom' import { useAuthStore } from '@/store/authStore' import { usePermissions, type EffectiveRole } from '@/hooks/usePermissions' import { Spinner } from '@/components/common/Spinner' interface ProtectedRouteProps { requiredRole?: EffectiveRole children: React.ReactNode } export function ProtectedRoute({ requiredRole, children }: ProtectedRouteProps) { const { isAuthenticated, isLoading, user } = useAuthStore() const location = useLocation() const { effectiveRole } = usePermissions() if (isLoading) { return (
) } if (!isAuthenticated) { return } // Enforce must_change_password — redirect unless already on /change-password if (user?.must_change_password && location.pathname !== '/change-password') { return } if (requiredRole) { const ROLE_HIERARCHY: Record = { super_admin: 4, owner: 3, engineer: 2, viewer: 1, } if (ROLE_HIERARCHY[effectiveRole] < ROLE_HIERARCHY[requiredRole]) { return } } return <>{children} } export default ProtectedRoute