File size: 1,686 Bytes
86d71bd
 
 
 
 
 
7fff83a
 
 
 
 
 
 
 
 
 
 
 
86d71bd
 
7fff83a
86d71bd
7fff83a
86d71bd
 
 
7fff83a
 
 
 
 
 
 
 
86d71bd
7fff83a
 
 
86d71bd
 
 
7fff83a
 
86d71bd
 
 
7fff83a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * ProtectedRoute Component
 * 
 * Wrapper component that protects routes requiring authentication.
 * Redirects to login if user is not authenticated.
 * 
 * Per MASTER CONSTRAINTS:
 * - All features are locked behind authentication
 * - No access without login
 * - Clear, user-friendly error handling
 * 
 * CRITICAL FIX FOR PAGE RELOAD:
 * - ONLY checks localStorage for token + user
 * - Does NOT wait for backend verification
 * - If token is invalid, the next API call will handle 401 redirect
 * - This ensures page reload NEVER redirects to login incorrectly
 * 
 * Note: Maintenance mode is now handled at App.jsx level
 */

import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { getToken, getStoredUser } from '../services/api';

function ProtectedRoute({ children }) {
    const location = useLocation();
    
    // SIMPLE CHECK: Only look at localStorage
    // If token AND user exist locally, allow access immediately
    // No async verification - that's handled by AuthContext in background
    // If token is actually invalid, API calls will return 401 and handle redirect
    const token = getToken();
    const storedUser = getStoredUser();
    const hasLocalAuth = !!(token && storedUser);

    // Only redirect if there's NO local auth at all
    if (!hasLocalAuth) {
        console.log('[ProtectedRoute] No local auth found, redirecting to login');
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    // Has local auth - render protected content immediately
    // Trust localStorage, let API calls handle invalid tokens via 401
    return children;
}

export default ProtectedRoute;