File size: 2,366 Bytes
d3ec6da
d96d2a2
d3ec6da
d96d2a2
 
 
 
 
 
 
 
d3ec6da
 
d96d2a2
d3ec6da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d96d2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import React, { useEffect, useState } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { supabase } from '../../lib/supabaseClient';
import useAuthStore from '../../store/authStore';

/**
 * ProtectedRoute Component
 * Restricts access to routes to only authenticated users.
 * Redirects to the login page if not authenticated.
 */
const ProtectedRoute = () => {
    const { user, profile, loading, getCurrentUser } = useAuthStore();
    const [isChecking, setIsChecking] = useState(true);

    useEffect(() => {
        const checkSession = async () => {
            // Re-verify the session via Supabase as requested
            const { data: { session } } = await supabase.auth.getSession();

            if (!session) {
                // If no session found, ensure our store also knows there's no user
                setIsChecking(false);
                return;
            }

            // If session exists, also sync the store if needed
            if (!user) {
                await getCurrentUser();
            }
            setIsChecking(false);
        };

        checkSession();
    }, [user, getCurrentUser]);

    if (loading || isChecking) {
        return (
            <div className="flex h-screen w-screen items-center justify-center bg-white">
                <div className="h-12 w-12 animate-spin rounded-full border-4 border-emerald-600 border-t-transparent"></div>
            </div>
        );
    }

    if (!user) {
        return <Navigate to="/login" replace />;
    }

    // Redirect specific roles to their dedicated portals if they hit a generic protected route,
    // BUT prevent infinite loops if they are already on those routes.
    const currentPath = window.location.pathname;

    if (profile) {
        if (profile.role === 'master_admin' && !currentPath.startsWith('/master-admin')) {
            return <Navigate to="/master-admin/dashboard" replace />;
        }
        if (profile.role === 'admin' && profile.status === 'active' && !currentPath.startsWith('/admin')) {
            return <Navigate to="/admin/dashboard" replace />;
        }
        if (profile.role === 'user' && profile.status !== 'active' && !currentPath.startsWith('/user-lobby')) {
            return <Navigate to="/user-lobby" replace />;
        }
    }

    return <Outlet />;
};

export default ProtectedRoute;