Fix navigation for logged-out users

Fixes a bug where clicking on Profile Management, Notification Settings, or Security & Privacy in Settings while logged out resulted in a 404 error.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 23:15:14 +00:00
parent a0866492ac
commit dc447c0baa
4 changed files with 163 additions and 23 deletions

View File

@@ -0,0 +1,40 @@
import { ReactNode, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/auth';
import { useToast } from '@/hooks/useToast.wrapper';
interface PrivateRouteProps {
children: ReactNode;
requireAuth?: boolean;
}
/**
* 인증이 필요한 라우트를 보호하는 컴포넌트
*/
const PrivateRoute = ({ children, requireAuth = true }: PrivateRouteProps) => {
const { user, loading } = useAuth();
const navigate = useNavigate();
const { toast } = useToast();
useEffect(() => {
// 로딩 중이 아니고, 인증이 필요한데 사용자가 로그인되어 있지 않은 경우
if (!loading && requireAuth && !user) {
toast({
title: "로그인 필요",
description: "이 페이지에 접근하려면 로그인이 필요합니다.",
variant: "destructive",
});
navigate('/login', { replace: true });
}
}, [user, loading, navigate, requireAuth, toast]);
// 로딩 중이거나 인증이 필요하지만 사용자가 로그인되어 있지 않은 경우 아무것도 렌더링하지 않음
if (loading || (requireAuth && !user)) {
return null;
}
return <>{children}</>;
};
export default PrivateRoute;