Skip to content

Commit

Permalink
Merge pull request #96 from Someup/feature/protected-route
Browse files Browse the repository at this point in the history
protected route 추가
  • Loading branch information
qaws7791 authored Oct 16, 2024
2 parents a0d09f7 + b6fdd94 commit d9bbf90
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
33 changes: 33 additions & 0 deletions components/auth/auth-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use client';
import { protectedRoutes } from '@/lib/service/auth/constants';
import { useUserProfile } from '@/lib/service/user/use-user-service';
import { usePathname, useRouter } from 'next/navigation';
import React, { useEffect } from 'react';

const isPrivateRoute = (path: string) => {
return protectedRoutes.some((route) => path.startsWith(route));
};

export default function AuthProvider({
children,
}: {
children: React.ReactNode;
}) {
const { data: user, isLoading } = useUserProfile();
const path = usePathname();
const router = useRouter();
const isPrivate = isPrivateRoute(path);

useEffect(() => {
if (isLoading || !isPrivate) return;
if (!user) {
router.push('/');
}
}, [user, router, isLoading, isPrivate]);

if (isPrivate && !user) {
return null;
}

return children;
}
7 changes: 5 additions & 2 deletions components/utils/Providers.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use client';
import AuthProvider from '@/components/auth/auth-provider';
import { Toaster } from '@/components/ui/Toster';
import {
isServer,
Expand Down Expand Up @@ -49,8 +50,10 @@ export default function Providers({ children }: ProvidersProps) {

return (
<QueryClientProvider client={queryClient}>
<Toaster />
{children}
<AuthProvider>
<Toaster />
{children}
</AuthProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
Expand Down
2 changes: 2 additions & 0 deletions lib/service/auth/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export const accessTokenConfig = {
expiration: 60 * 60 * 24, // 1 day
name: 'accessToken',
} as const;

export const protectedRoutes = ['/archive', '/posts'] as const;

0 comments on commit d9bbf90

Please sign in to comment.