dishplanner/frontend-old/app/components/layout/AuthGuard.tsx

26 lines
1 KiB
TypeScript
Raw Permalink Normal View History

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';
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();
const navigate = useNavigate();
const location = useLocation();
2025-10-13 14:57:11 +02:00
const publicRoutes = ['/login', '/register'];
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
navigate('/', { replace: true });
2025-10-13 14:57:11 +02:00
} else if (!isAuthenticated && !isPublic) {
// Redirect unauthenticated users trying to access protected pages
navigate('/login', { replace: true });
2025-10-13 14:57:11 +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}</>;
}