使用RBAC登录时遇到问题

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

所以我在我的代码中实现了 rbac,所以我使用 laravel 并对这个项目做出反应,我遇到了问题,所以对于上下文我的 role_id 有这样的标签

现在我使用 RequireAuth.jsx 实现它,所以它有这个代码

import { useLocation,Navigate, Outlet} from 'react-router-dom';
import useAuth from '../hooks/useAuth';

const RequireAuth = ({ allowedRoles }) => {
  const { auth } = useAuth();
  const location = useLocation();
  const userRole = auth?.role_id;

// Check if the user's role matches any of the allowed roles
const isAllowed = allowedRoles?.includes(userRole);

return (
    isAllowed ? (
        <Outlet />
    ) : (
        auth?.user ? (
            <Navigate to={{ pathname: '/unauthorized', state: { from: location } }} replace />
        ) : (
            <Navigate to={{ pathname: '/login', state: { from: location } }} replace />
        )
    )
);
}
export default RequireAuth;

我的 app.jsx 具有 allowedRoles 用于调用 role_id 这是我的 App.jsx

function App() {

return (
<Routes>
  {/* Public Route */}
  <Route path="login" element={<Login/>}/>
  <Route path='*' element={<NotFound/>}/>
  <Route path='unauthorized' element={<Unauthorized/>}/>
  <Route path="create" element={<Create/>}/>
  <Route path="ask" element={<Ask/>}/>


  {/* Protected Route */}
  
  <Route element={<RequireAuth allowedRoles={[1]}/>}> 
    <Route path="/" element={<Dashboard/>}/>
    <Route  path="notification" element={<Notification/>}/>
    <Route path="user" element={<User/>}/>
    <Route path="scholar" element={<Scholar/>}/>
    <Route path="scholarship" element={<Scholarship/>}/>
    <Route path="submission" element={<Submission/>}/>
    <Route path="export" element={<Export/>}/>
    <Route path="school" element={<School/>}/>
    <Route path="view" element={<ViewSubmission/>}/>
  </Route> 

  {/* Manager Route */}
  <Route element={<RequireAuth allowedRoles={[2]}/>}>
    <Route path="scholar" element={<Scholar/>}/>
  </Route>

  {/* Scholar Route */}
  <Route element={<RequireAuth allowedRoles={[3]}/>}>
    <Route path="scholar-dashboard" element={<ScholarDashboard/>}/>
    <Route path="scholar-submission" element={<ScholarSubmission/>}/>
    <Route path="scholar-profile" element={<ScholarProfile/>}/>
  </Route>
</Routes>
)
}

export default App

所以我的主要问题是,当我使用我的管理员帐户登录时,它可以工作,但是当我尝试通过经理和学者登录时,它会从我的 requireauth.jsx 返回未经授权的导航,另一个目标是学者无法访问某些选项卡管理员

reactjs authentication routes react-router rbac
1个回答
0
投票

我只是通过每个角色的导航来更改我的onsubmit,所以我创建了一个三元操作来根据他们应该拥有的路线传递它

const rolePath = role_id === 1  ? '/'  : role_id === 2 ? '/' : role_id === 3 ? '/scholar-dashboard' : '/login';

  // Navigate the user to the intended route (from variable contains the intended route)
  navigate(rolePath);
© www.soinside.com 2019 - 2024. All rights reserved.