This repository has no description
1import React, { useEffect } from 'react';
2import { useLocation } from 'react-router-dom';
3import { useAuth } from '../contexts/AuthContext';
4
5const ProtectedRoute = ({ children }) => {
6 const { isAuthenticated, loading } = useAuth();
7 const location = useLocation();
8
9 // Use a side effect to check authentication and redirect if needed
10 useEffect(() => {
11 // If we're still loading, wait
12 if (loading) {
13 console.log('ProtectedRoute: Waiting for auth to complete...');
14 return;
15 }
16
17 // If not authenticated, redirect immediately
18 if (!isAuthenticated) {
19 console.log('ProtectedRoute: Not authenticated, forcing redirect to login...');
20 const redirectUrl = `/login?returnUrl=${encodeURIComponent(location.pathname + location.search)}`;
21
22 // Force redirect - this is the simplest, most reliable approach
23 window.location.replace(redirectUrl);
24 } else {
25 console.log('ProtectedRoute: User is authenticated, allowing access');
26 }
27 }, [isAuthenticated, loading, location.pathname, location.search]);
28
29 // Keep the component simple - only render children if authenticated
30 if (loading) {
31 return <div className="auth-loading">Checking authentication...</div>;
32 }
33
34 if (!isAuthenticated) {
35 return <div className="auth-redirecting">Not authenticated - redirecting to login...</div>;
36 }
37
38 return children;
39};
40
41export default ProtectedRoute;