通过用户角色保护路由

问题描述 投票:0回答:1

我想保护我在React js中的路线,并且我有具有角色的用户,所以请告诉我如何在主页中执行此操作,我已经使用chaeack框登录角色学生和老师,我有这条路线,请告诉我最好的方法这样做,这是我的路线。

const routes = useRoutes([
    {
      path: "/",
      element: <Firstpage></Firstpage>,
    },

   
    {
        path: "/Student",
        
          element: <Studenpage />,
          children: [

            { path: "",
             element: <Main /> 
            },{
              path: "form",
              element: < Pfeextern/>,
            },
            {
              path: "upload",
              element: <Uploadfile />,
            },
            {
              path: "propose",
              element: <Propose />,
            }
          ],                     
    },

        {
          path: "/teacher",
          
            element:<HomePageEncadreur />,
            children: [
              { path: "",
               element: <Mainn/> 
              },{
                path: "Request",
                element: < Request/>,
              },
              
            ],
            
            
           
          },
    
    
      {
        path: "/loginAdmin",
        element: <LoginAdmin />, // Render LoginAdmin component initially
      },
          {
            path: '/Admin', // Default child route
            element: <Adminnn />, // Render Adminnn component after successful login
            children: [
              {
                path: "",
                element: <Students />, // Render nested route within Adminnn component
              },
              {
                path: "team",
                element: <Teacher />, // Render nested route within Adminnn component
              },
              {
                path: "jury",
                element: <Jury />, // Render nested route within Adminnn component
              },
              {
                path: "form",
                element: <Form />, // Render nested route within Adminnn component
              },
              {
                path: "feedback",
                element: <Feedback />, // Render nested route within Adminnn component
              },
          
              {
                path: "calendar",
                element: <Calendar />, // Render nested route within Adminnn component
              },
            ],
          },
        ],`
  );


  return (
    <>
      {routes}
    </>
  );

我这样做了,但它不起作用上帝我想在上下文和cheak rol中帮助我

reactjs authentication protected nested-routes
1个回答
0
投票

我会采取不同的方法来解决这个问题。我会将

RouteProvider
createBrowserRouter
createRoutesFromElements
一起使用。 这将提供传递路由配置对象以及每个路由应具有的角色以便可见的机会。

所以我的

app.tsx
会是这样的:

const routes = [
  {
    path: "/",
    element: <Firstpage></Firstpage>,
  },
  {
    path: "/Student",
    roles: ["Student"],
    element: <Studenpage />,
    children: [
      {
        path: "",
        element: <Main />,
      },
      {
        path: "form",
        element: <Pfeextern />,
      },
    ],
  },
  {
    path: "/Teacher",
    roles: ["Teacher"],
    element: <TeacherPage />,
  },
];

const router = createBrowserRouter(
  createRoutesFromElements(buildRoutes(routes))
);
const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

root.render(<RouterProvider router={router} />);

那么我的

buildRoutes
函数将是这样的:

export const buildRoutes = (routes: RouteObject): JSX.Element => {
    return (
        <Route path={routes.path} element={routes.element}>
            {routes.children?.map((route: RouteObject) => buildRoute(route))}
        </Route>
    )
}

我的

buildRoute
功能如下:

export const buildRoute = (route: RouteObject) => {
    const {path, roles, element, children, ...rest} = route

    return (
        <Route
            {...rest}
            key={`${path}_key`}
            path={path}
            element={
                <ProtectedRoute roles={roles}>
                  {route.element}
                </ProtectedRoute>
            }
        >
            {(children as any)?.map((childRoute: any) => buildRoute(childRoute))}
        </Route>
    )
}

最后

ProtectedRoute.tsx

export interface ProtectedRouteProps{
    roles: string[]
    children?: ReactElement<any, any>[] | ReactElement<any, any>

}

export const ProtectedRoute = (props: ProtectedRouteProps) => {
    
    const effectiveRoles: string[] = [] //get from token or context
    
    const roleExists = (roles: string[]) => {
        return roles.some(role => effectiveRoles.includes(role))
    }
    
    return roleExists(props.roles) ? props.children : <Navigate to="/unauthorized" />
}

我希望这些能帮助你前进

© www.soinside.com 2019 - 2024. All rights reserved.