2025-10-13 14:57:11 +02:00
|
|
|
import { useAuth } from '@/context/AuthContext';
|
|
|
|
|
import React, { useEffect, useState } from 'react';
|
2025-10-13 20:22:47 +02:00
|
|
|
import { useLocation, useNavigate } from "react-router"
|
2025-10-13 14:57:11 +02:00
|
|
|
|
|
|
|
|
// Optional Loading spinner component to display while loading
|
|
|
|
|
const LoadingSpinner = () => (
|
|
|
|
|
<div className="flex justify-center items-center min-h-screen">
|
|
|
|
|
<div className="animate-spin w-10 h-10 border-4 border-blue-500 border-t-transparent rounded-full"></div>
|
|
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
|
|
|
|
const { isAuthenticated } = useAuth(); // Access the authentication state from AuthContext
|
2025-10-13 20:22:47 +02:00
|
|
|
const navigate = useNavigate();
|
2025-10-13 14:57:11 +02:00
|
|
|
const [loading, setLoading] = useState(true);
|
2025-10-13 20:22:47 +02:00
|
|
|
const location = useLocation();
|
2025-10-13 14:57:11 +02:00
|
|
|
|
|
|
|
|
const publicRoutes = ['/login', '/register'];
|
2025-10-13 20:22:47 +02:00
|
|
|
const isPublic = publicRoutes.includes(location.pathname);
|
2025-10-13 14:57:11 +02:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
// Determine behavior based on auth state and route type
|
|
|
|
|
if (isAuthenticated === null) {
|
|
|
|
|
// Await authentication resolution (e.g., token check)
|
|
|
|
|
setLoading(true);
|
|
|
|
|
} else if (isAuthenticated && isPublic) {
|
|
|
|
|
// Redirect authenticated users away from public pages
|
2025-10-13 20:22:47 +02:00
|
|
|
navigate('/', { replace: true });
|
2025-10-13 14:57:11 +02:00
|
|
|
} else if (!isAuthenticated && !isPublic) {
|
|
|
|
|
// Redirect unauthenticated users trying to access protected pages
|
2025-10-13 20:22:47 +02:00
|
|
|
navigate('/login', { replace: true });
|
2025-10-13 14:57:11 +02:00
|
|
|
} else {
|
|
|
|
|
// Otherwise, stop loading since the state is resolved
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
2025-10-13 20:22:47 +02:00
|
|
|
}, [isAuthenticated, location.pathname, isPublic, navigate]);
|
2025-10-13 14:57:11 +02:00
|
|
|
|
|
|
|
|
// Show a spinner while authentication state is loading
|
|
|
|
|
if (loading) {
|
|
|
|
|
return <LoadingSpinner />;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Render children only when the authentication state and path are valid
|
|
|
|
|
return <>{children}</>;
|
|
|
|
|
}
|