2025-10-13 14:57:11 +02:00
|
|
|
import { useAuth } from '@/context/AuthContext';
|
2025-11-09 13:09:22 +01:00
|
|
|
import React, { useEffect } from 'react';
|
2025-10-13 20:22:47 +02:00
|
|
|
import { useLocation, useNavigate } from "react-router"
|
2025-10-13 14:57:11 +02:00
|
|
|
|
|
|
|
|
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
2025-11-09 13:09:22 +01:00
|
|
|
const { isAuthenticated } = useAuth();
|
2025-10-13 20:22:47 +02:00
|
|
|
const navigate = useNavigate();
|
|
|
|
|
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(() => {
|
2025-11-09 13:09:22 +01:00
|
|
|
// Handle redirects based on auth state
|
|
|
|
|
if (isAuthenticated && isPublic) {
|
2025-10-13 14:57:11 +02:00
|
|
|
// 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
|
|
|
}
|
2025-10-13 20:22:47 +02:00
|
|
|
}, [isAuthenticated, location.pathname, isPublic, navigate]);
|
2025-10-13 14:57:11 +02:00
|
|
|
|
2025-11-09 13:09:22 +01:00
|
|
|
// Render children for all routes - redirects will happen via useEffect
|
2025-10-13 14:57:11 +02:00
|
|
|
return <>{children}</>;
|
|
|
|
|
}
|