gpt4 book ai didi

node.js - Express.js/Mongoose 用户角色和权限

转载 作者:搜寻专家 更新时间:2023-10-31 22:17:58 25 4
gpt4 key购买 nike

我正在使用 Node、Express 和 Mongoose 创建一个相当简单的站点。该站点需要具有用户角色和权限。我的想法是,我将根据用户与数据库的交互来验证权限。

在 mongoose 中有没有办法确定用户当前可能执行的 CRUD 操作的类型?

最佳答案

我找到了解决方案。很高兴听到人们对此的意见。

我有一个权限配置对象,它定义了每个角色及其权限。

权限配置对象

roles.admin = {
id: "admin",
name: "Admin",
description: "",
resource : [
{
id : 'blog',
permissions: ['create', 'read', 'update', 'delete']
},
{
id : 'user',
permissions: ['create', 'read', 'update', 'delete']
},
{
id : 'journal',
permissions: ['create', 'read', 'update', 'delete']
},

]
};

roles.editor = {
id: "editor",
name: "Editor",
description: "",
resource : [
{
id : 'blog',
permissions: ['create', 'read', 'update', 'delete']
},
{
id : 'user',
permissions: ['read']
},
{
id : 'journal',
permissions: ['create', 'read', 'update']
},

]
};

中间件功能

var roles = require('./config');


var permissions = (function () {

var getRoles = function (role) {

var rolesArr = [];

if (typeof role === 'object' && Array.isArray(role)) {

// Returns selected roles
for (var i = 0, len = role.length; i < len; i++) {
rolesArr.push(roles[role[i]]);
};
return rolesArr;

} else if (typeof role === 'string' || !role) {

// Returns all roles
if (!role) {
for (var role in roles) {
rolesArr.push(roles[role]);
};
}

// Returns single role
rolesArr.push(roles[role]);
return rolesArr;

}

},
check = function (action, resource, loginRequired) {

return function(req, res, next) {

var isAuth = req.isAuthenticated();

// If user is required to be logged in & isn't
if (loginRequired && !isAuth) {
return next(new Error("You must be logged in to view this area"));
}

if (isAuth || !loginRequired) {

var authRole = isAuth ? req.user.role : 'user',
role = get(authRole),
hasPermission = false;

(function () {
for (var i = 0, len = role[0].resource.length; i < len; i++){
if (role[0].resource[i].id === resource && role[0].resource[i].permissions.indexOf(action) !== -1) {
hasPermission = true;
return;
}
};
})();

if (hasPermission) {
next();
} else {
return next(new Error("You are trying to " + action + " a " + resource + " and do not have the correct permissions."));
}

}
}
}

return {
get : function (role) {

var roles = getRoles(role);

return roles;
},
check : function (action, resource, loginRequired) {
return check(action, resource, loginRequired);
}
}

})();

module.exports = permissions;

然后我创建了一个中间件函数,当调用 check 方法时,它从 req 对象 (req.user.role) 获取用户角色。然后它查看传递给中间件的参数,并将它们与权限配置对象中的参数交叉引用。

路由中间件

app.get('/journal', `**permissions.check('read', 'journal')**`, function (req, res) {
// do stuff
};

关于node.js - Express.js/Mongoose 用户角色和权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24286835/

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