Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,16 @@ function App() {
<Route path="/my-page" element={<MyPage />} />
<Route path="/chat" element={<ChatPage />} />
<Route path="/chat-apply" element={<ChatApplyPage />} />
<Route path="/admin" element={<Admin />} />
</Route>

<Route
path="/admin"
element={
<ProtectedRoute requiredRole={'ADMIN'}>
<Admin />
</ProtectedRoute>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>

Expand Down
27 changes: 25 additions & 2 deletions src/assets/components/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,38 @@
import { Navigate } from 'react-router-dom';
import type { ReactNode } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import NotFound from '@/pages/404/NotFoundPage';

interface ProtectedRouteProps {
children: ReactNode;
requiredRole?: string | string[];
}

export default function ProtectedRoute({ children }: ProtectedRouteProps) {
const { isAuthenticated } = useAuth();
export default function ProtectedRoute({
children,
requiredRole,
}: ProtectedRouteProps) {
const { isAuthenticated, user } = useAuth();
if (!isAuthenticated) {
return <Navigate to="/" replace />;
}

if (requiredRole) {
const userRoles: string[] = Array.isArray(user?.role)
? (user?.role as string[])
: user?.role
? [user.role as string]
: [];

const required = Array.isArray(requiredRole)
? requiredRole
: [requiredRole];
Comment on lines +21 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

역할(role)을 배열로 변환하는 로직을 더 간결하게 개선할 수 있습니다. userRolesrequired를 초기화하는 부분을 Array.prototype.flat()을 사용하여 더 간단하고 읽기 쉽게 만들 수 있습니다.

user.rolestring, string[], 또는 undefined일 수 있고, requiredRolestring 또는 string[]일 수 있습니다. flat() 메소드는 이러한 경우를 효과적으로 처리하여 코드를 단순화합니다.

    const userRoles = [user?.role].flat().filter(Boolean);
    const required = [requiredRole].flat();


const hasRole = required.some((r) => userRoles.includes(r));
if (!hasRole) {
return <NotFound />;
}
}

return <>{children}</>;
}
4 changes: 1 addition & 3 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
{
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
Loading