nodejs acl的用户权限管理详解

2020-06-17 06:43:35易采站长站整理


app.locals.hasRole = function (userRole, path, method = 'get') {

if (userRole === 'root') {
return true;
}

const current = aclConf.find((n) => {
return n['roles'] === userRole;
});

let isFind = false;
for (let i of current.allows) {
const currentPath = i.resources; // 目前数组第一个为单纯的get路由
isFind = currentPath.includes(path);

if (isFind) {
// 如果找到包含该路径 并且method也对应得上 那么则通过
if (i.permissions.includes(method)) {
break;
}

// 如果找到该路径 但是method对应不上 则继续找.
continue;
}
}

return isFind;
};

上述代码页比较简单, 去遍历acl_conf,查找用户是否有当前页面的或者按钮的权限 因为acl_conf在加载的时候就已经被写入内存了,所以性能消耗不会特别大。比如下面的例子。


if hasRole(user.role, '/admin/reserve/audit', 'post')
.col.l3.right-align
a.waves-effect.waves-light.btn.margin-right.blue.font12.js-reviewe-ok 同意
a.waves-effect.waves-light.btn.pink.accent-3.font12.js-reviewe-no 拒绝

结尾

依靠acl这个组件可以快速打造一个用户的权限管理模块。 但是还有个问题 也急速那个app.locals.hasRole函数, 如果你使用removeAllow动态改变了用户的权限表,那么hasRole函数就很麻烦了。 所以在这种情况下 有以下几个解决方案

从acl源码入手
每次渲染的时候就把数据准备好


const hasBtn1Role = hasRole(user.role, '/xxx','get');
res.render('a.pug',{hasBtn1Role})