【发布时间】:2021-02-10 13:19:16
【问题描述】:
我正在实现一个 Web 应用程序,其中有几个不同的角色,称为系统管理员和员工。系统管理员将被重定向到以“/admin/xxx”开头的路径,而普通员工在登录后将被重定向到“/employees/xxx”。
如何确保以系统管理员身份登录后,手动输入“/employees/xx”时无法访问员工路径,反之亦然?
const antIcon = (
<LoadingOutlined style={{ fontSize: 100, textAlign: "center" }} spin />
);
toast.configure();
function AuthenticatedRoute({ component: C, appProps, propss, user, ...rest }) {
return (
<Route
{...rest}
render={(props) => {
if (!appProps.isAuthenticated) {
if (propss.loading) {
// console.log(typeof user);
if (localStorage.length === 0) {
toast.error("You have no authorization to access!");
return <Redirect to={{ pathname: "/login" }} />;
} else {
console.log("error");
}
}
}
if (propss.loading) {
return (
<div style={{ textAlign: "center", marginTop: "250px" }}>
<Spin indicator={antIcon} />
</div>
);
}
if (appProps.isAuthenticated) {
return <C {...props} {...appProps} />;
}
}}
/>
);
}
export default AuthenticatedRoute;
<Router history={history}>
<Switch>
<Route path="/:path?" exact>
<LoginContainer>
<Route exact path="/" component={() => <Redirect to="/login" />} />
<Route
path="/login"
render={(props) => {
if (loading) {
return (
<div style={{ textAlign: "center", marginTop: "250px" }}>
<Spin indicator={antIcon} />
</div>
);
} else if (!isAuthenticated) {
return <Login {...props} setAuth={setAuth} />;
} else {
if (localStorage.getItem("designation") === "System Admin") {
return (
<Redirect
to="/admin/Dashboard"
{...props}
setAuth={setAuth}
/>
);
} else {
return (
<Redirect
to="/employee/Dashboard"
{...props}
setAuth={setAuth}
/>
);
}
}
}}
/>
<Route path="/forgot" component={ForgotPassword} />
<Route path="/notFound" component={NotFound} />
</LoginContainer>
</Route>
<UserContext.Provider value={{ user }}>
<SiderProvider>
<AuthenticatedRoute path="/admin/:path?">
<SystemAdminContainer>
<Switch>
<AuthenticatedRoute
path="/admin/Dashboard"
appProps={{ isAuthenticated }}
propss={{ loading }}
component={Dashboard}
user={user}
/>
</Switch>
</SystemAdminContainer>
</AuthenticatedRoute>
<AuthenticatedRoute path="/employee/:path?">
<EmployeeContainer>
<Switch>
<AuthenticatedRoute
path="/employee/Dashboard"
appProps={{ isAuthenticated }}
propss={{ loading }}
component={Dashboard}
user={user}
/>
</Switch>
</EmployeeContainer>
</AuthenticatedRoute>
</SiderProvider>
</UserContext.Provider>
</Switch>
</Router>
【问题讨论】:
-
为什么这个问题被关闭了?
-
我也不确定!
标签: node.js reactjs react-router