gpt4 book ai didi

reactjs - 如何在前端 React JS 上控制用户角色 - MERN 应用程序

转载 作者:行者123 更新时间:2023-12-05 02:09:22 25 4
gpt4 key购买 nike

MERN APP(MongoDB、Express、ReactJS、NodeJS)- 在后端,我使用 token 控制登录用户并根据角色授予用户访问权限。

问题是:如果用户是管理员或客户端,如何控制前端(ReactJS)用户的角色?

例如:如果用户已登录,我会从后端向前端发送一个 token ,如果用户已登录,我可以像这样控制路由:

if(token){                                //if user is logged
<Route path="/dashboard" exact>
<Products/> //Products Page
</Route>
}else{
<Route path="/dashboard" exact>
<Page1 /> //AnyPage
</Route>
}

我只想为管理员用户授予访问用户页面的权限:

if(token && role === 'admin'){                                //if user is logged and role is admin
<Route path="/dashboard" exact>
<Users /> //Users Page
</Route>
}...

我可以在后端控制这个东西,我只想在前端对这个问题有任何其他想法。谢谢:)

最佳答案

Interactive example

遇到这种情况我会怎么做:

  1. 当用户登录时,API 应返回他们的信息,包括权限。将该信息存储在状态中。

  2. 创建一个函数,checkUserPermission(user = { roles: [] }, permission)。此函数接受 user 对象、permission 字符串(即 "route.admin""component.Authenticate")并应根据用户的访问级别返回 true 或 false。那将是一个决定当前用户是否被允许做这个或那个的地方。它可以包含简单的属性检查(if (user.role === 'admin'))或更复杂的内容(查看示例)。

  3. 创建 SecuredRoute 组件,它是 Route 的包装器,但需要 userpermission 参数和如果用户看不到这条路线,则重定向离开。

  4. 使用 checkUserPermission 函数有条件地呈现链接或组件。

  5. 正如在其他答案中已经提到的,API 必须对每个请求进行自己的权限检查,因为在 UI 端隐藏内容不会阻止恶意和知识渊博的用户


//src/utils/checkUserPermission.js
export default function checkUserPermission(user = { roles: [] }, permission) {
const allowAccessForRoles = {
"route.admin": ["admin"],
"route.authenticated": ["user", "admin"],
"route.home": ["*"], //means "Any role"
"component.Authenticate": ["*", "!user", "!admin"], //Any role except user and admin
"component.BecomeAdmin": ["user"],
"component.LogOut": ["user", "admin"]
};

//If we don't have such permission in list, access denied for everyone
if (!Array.isArray(allowAccessForRoles[permission])) {
return false;
}

//Check if any of user's roles explicitly denies access
for (const role of user.roles) {
if (allowAccessForRoles[permission].includes("!" + role)) {
return false;
}
}

//If list of allowed roles contains '*', access allowed for everyone
if (allowAccessForRoles[permission].includes("*")) {
return true;
}

//Check if any of user's roles allowes access
for (const role of user.roles) {
if (allowAccessForRoles[permission].includes(role)) {
return true;
}
}

return false;
}

//src/SecuredRoute
import React from "react";
import { Route, Redirect } from "react-router-dom";
import checkUserPermission from "./utils/checkUserPermission";

const SecuredRoute = ({
user,
permission,
redirectTo = "/",
children,
...rest
}) => {
const allowed = checkUserPermission(user, permission);

if (allowed) {
return <Route {...rest} render={() => children} />;
}

return (
<Route
{...rest}
render={({ location }) => (
<Redirect
to={{
pathname: redirectTo,
state: { from: location }
}}
/>
)}
/>
);
};

export default SecuredRoute;

//src/App.js
import React, { useState } from "react";
import "./styles.css";
import { BrowserRouter as Router, Switch, Link } from "react-router-dom";
import SecuredRoute from "./SecuredRoute";
import checkUserPermission from "./utils/checkUserPermission";

const AdminPage = () => <div>Admin page is open for admins</div>;

const AuthenticatedPage = () => (
<div>Authenticated page is open for users and admins</div>
);

const HomePage = () => <div>Home page is open for everyone</div>;

export default function App() {
const [user, setUser] = useState();

return (
<Router>
<div className="App">
<div className="Nav">
<div>
<Link to="/">Go to Home Page</Link>
</div>
{checkUserPermission(user, "route.authenticated") ? (
<div>
<Link to="/authenticated">Go to Authenticated Page</Link>
</div>
) : null}
{checkUserPermission(user, "route.admin") ? (
<div>
<Link to="/admin">Go to Admin Page</Link>
</div>
) : null}
</div>

<div className="Controls">
{checkUserPermission(user, "component.Authenticate") ? (
<button type="button" onClick={() => setUser({ roles: ["user"] })}>
Become authenticated
</button>
) : null}

{checkUserPermission(user, "component.BecomeAdmin") ? (
<button type="button" onClick={() => setUser({ roles: ["admin"] })}>
Become admin
</button>
) : null}

{checkUserPermission(user, "component.LogOut") ? (
<button type="button" onClick={() => setUser()}>
Log out
</button>
) : null}
</div>

<div className="Main">
<Switch>
<SecuredRoute user={user} permission="route.home" exact path="/">
<HomePage />
</SecuredRoute>
<SecuredRoute
user={user}
permission="route.authenticated"
path="/authenticated"
>
<AuthenticatedPage />
</SecuredRoute>
<SecuredRoute user={user} permission="route.admin" path="/admin">
<AdminPage />
</SecuredRoute>
</Switch>
</div>
</div>
</Router>
);
}

关于reactjs - 如何在前端 React JS 上控制用户角色 - MERN 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59957892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com