Skip to content

Commit

Permalink
feat: role 별 인가 작업 (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
bear-bear-bear committed Nov 16, 2023
1 parent bc50653 commit 36fc376
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { ChakraProvider } from '@chakra-ui/react';
import { UserRole } from '@/api/@types/@enums';
import AuthLayout from '@/components/layouts/Auth';
import ServiceLayout from '@/components/layouts/Service';
import RequireAuth from '@/components/shared/RequireAuth';
import { useGeoAlert } from '@/hooks/useGeoAlert';
import OAuthRedirectPage from '@/pages/auth/oauth-redirect/page';
import SignInPage from '@/pages/auth/sign-in/page';
Expand Down Expand Up @@ -34,7 +36,11 @@ const router = createBrowserRouter([
},
{
path: 'register',
element: <ProductRegistrationPage />,
element: (
<RequireAuth role={UserRole.SELLER}>
<ProductRegistrationPage />
</RequireAuth>
),
},
{
path: ':id',
Expand All @@ -47,21 +53,37 @@ const router = createBrowserRouter([
children: [
{
index: true,
element: <ChatListPage />,
element: (
<RequireAuth>
<ChatListPage />
</RequireAuth>
),
},
{
path: ':id',
element: <ChatPage />,
element: (
<RequireAuth>
<ChatPage />
</RequireAuth>
),
},
],
},
{
path: 'wishlist',
element: <div>wishlist page</div>,
element: (
<RequireAuth>
<div>wishlist page</div>
</RequireAuth>
),
},
{
path: 'my',
element: <div>my page</div>,
element: (
<RequireAuth>
<div>my page</div>
</RequireAuth>
),
},
],
},
Expand Down
28 changes: 28 additions & 0 deletions src/components/shared/RequireAuth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { FC, PropsWithChildren } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { UserRole } from '@/api/@types/@enums';
import { useRedirect } from '@/hooks/useRedirect';
import { useBoundedStore } from '@/stores';

interface Props extends PropsWithChildren {
role?: UserRole;
}

const RequireAuth: FC<Props> = ({ children, role }) => {
const user = useBoundedStore(state => state.user);
const { navigateWithRedirectPath } = useRedirect();
const navigate = useNavigate();
const { pathname } = useLocation();

if (!user) {
navigateWithRedirectPath('/auth/sign-in', pathname);
return;
}
if (role && user.role !== role) {
navigate('/');
return;
}
return children;
};

export default RequireAuth;

0 comments on commit 36fc376

Please sign in to comment.