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:
40
src/components/auth/PrivateRoute.tsx
Normal file
40
src/components/auth/PrivateRoute.tsx
Normal 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;
|
||||
Reference in New Issue
Block a user