Files
maternal-app/maternal-web/components/common/ProtectedRoute.tsx
2025-10-01 19:01:52 +00:00

42 lines
1.0 KiB
TypeScript

'use client';
import { useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { Box, CircularProgress } from '@mui/material';
import { useAuth } from '@/lib/auth/AuthContext';
const PUBLIC_ROUTES = ['/login', '/register', '/forgot-password'];
export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useAuth();
const router = useRouter();
const pathname = usePathname();
useEffect(() => {
if (!isLoading && !isAuthenticated && !PUBLIC_ROUTES.includes(pathname)) {
router.push('/login');
}
}, [isAuthenticated, isLoading, router, pathname]);
if (isLoading) {
return (
<Box
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
}}
>
<CircularProgress size={48} />
</Box>
);
}
if (!isAuthenticated && !PUBLIC_ROUTES.includes(pathname)) {
return null;
}
return <>{children}</>;
}