diff --git a/src/components/ProtectedRoute.tsx b/src/components/ProtectedRoute.tsx index e77545c..d8e5178 100644 --- a/src/components/ProtectedRoute.tsx +++ b/src/components/ProtectedRoute.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAuth } from '@/hooks/useAuth'; import { Skeleton } from '@/components/ui/skeleton'; @@ -11,29 +11,22 @@ interface ProtectedRouteProps { export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) { const { user, loading: authLoading } = useAuth(); const navigate = useNavigate(); - const hasCheckedRef = useRef(false); useEffect(() => { - // Only run effect once per component mount - if (!authLoading && !hasCheckedRef.current) { - hasCheckedRef.current = true; + if (!authLoading && !user) { + // Save current URL to redirect back after login + const currentPath = window.location.pathname + window.location.search; + sessionStorage.setItem('redirectAfterLogin', currentPath); + navigate('/auth'); + return; + } - if (!user) { - // Save current URL to redirect back after login - const currentPath = window.location.pathname + window.location.search; - sessionStorage.setItem('redirectAfterLogin', currentPath); - navigate('/auth'); - return; - } - - // Check for admin role if required - if (requireAdmin) { - const userRole = user.user_metadata?.role; - if (userRole !== 'admin') { - // Redirect non-admin users to member dashboard - navigate('/dashboard'); - return; - } + // Check for admin role if required (only after user is loaded) + if (!authLoading && user && requireAdmin) { + const userRole = user.user_metadata?.role; + if (userRole !== 'admin') { + // Redirect non-admin users to member dashboard + navigate('/dashboard'); } } }, [user, authLoading, navigate, requireAdmin]);