Skip to content

Commit d9bbf90

Browse files
authored
Merge pull request #96 from Someup/feature/protected-route
protected route 추가
2 parents a0d09f7 + b6fdd94 commit d9bbf90

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

components/auth/auth-provider.tsx

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use client';
2+
import { protectedRoutes } from '@/lib/service/auth/constants';
3+
import { useUserProfile } from '@/lib/service/user/use-user-service';
4+
import { usePathname, useRouter } from 'next/navigation';
5+
import React, { useEffect } from 'react';
6+
7+
const isPrivateRoute = (path: string) => {
8+
return protectedRoutes.some((route) => path.startsWith(route));
9+
};
10+
11+
export default function AuthProvider({
12+
children,
13+
}: {
14+
children: React.ReactNode;
15+
}) {
16+
const { data: user, isLoading } = useUserProfile();
17+
const path = usePathname();
18+
const router = useRouter();
19+
const isPrivate = isPrivateRoute(path);
20+
21+
useEffect(() => {
22+
if (isLoading || !isPrivate) return;
23+
if (!user) {
24+
router.push('/');
25+
}
26+
}, [user, router, isLoading, isPrivate]);
27+
28+
if (isPrivate && !user) {
29+
return null;
30+
}
31+
32+
return children;
33+
}

components/utils/Providers.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
'use client';
2+
import AuthProvider from '@/components/auth/auth-provider';
23
import { Toaster } from '@/components/ui/Toster';
34
import {
45
isServer,
@@ -49,8 +50,10 @@ export default function Providers({ children }: ProvidersProps) {
4950

5051
return (
5152
<QueryClientProvider client={queryClient}>
52-
<Toaster />
53-
{children}
53+
<AuthProvider>
54+
<Toaster />
55+
{children}
56+
</AuthProvider>
5457
<ReactQueryDevtools initialIsOpen={false} />
5558
</QueryClientProvider>
5659
);

lib/service/auth/constants.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@ export const accessTokenConfig = {
22
expiration: 60 * 60 * 24, // 1 day
33
name: 'accessToken',
44
} as const;
5+
6+
export const protectedRoutes = ['/archive', '/posts'] as const;

0 commit comments

Comments
 (0)