简体   繁体   English

Expressjs路由:基于角色的路由

[英]Expressjs routing : Role based routes

I have a small dilema to resolve this. 我有一个小难题来解决这个问题。

I have a user and an admin role. 我有一个用户和一个管理员角色。

userRoles: ['user', 'admin']

Users should be able to list all users except admins. 用户应该能够列出除管理员以外的所有用户。 Admins can list all users. 管理员可以列出所有用户。

The first solution i have in mind is to check roles at the controller level: 我想到的第一个解决方案是在控制器级别检查角色:

if (req.user.role == 'admin'){list all users}
else{list all except admins}

but what i'd like to do is more on a route level, to keep the controllers cleaner, but somehow it doest work. 但是我想做的更多的是在路由级别上,以保持控制器的清洁,但是某种程度上它不起作用。 It lists the users only even if im logged as an admin. 即使im以管理员身份登录,它也仅列出用户。

router.get('/', auth.hasRole('user'), controller.index);
router.get('/', auth.hasRole('admin'), controller.getUsers);


function hasRole(roleRequired) {
 if (!roleRequired) throw new Error('Required role needs to be set');

  return compose()
    .use(isAuthenticated())
    .use(function meetsRequirements(req, res, next) {
      if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
        next();
      }
      else {
        res.status(403).send('Forbidden');
      }
    });
}

any suggestions? 有什么建议么? Thanks ! 谢谢 !

So, I'm not sure this is your problem, but one thing to remember is that JS doesn't guarantee the indexing of an array (per the ecmascript spec), so your >= test is not reliable. 因此,我不确定这是否是您的问题,但要记住的一件事是JS不保证(根据ecmascript规范)数组的索引,因此您的>=测试不可靠。

Better to use a bitmask like I did in AuthZ , where you assign rights or roles as fixed binary numbers that you can then filter against: 最好像在AuthZ中一样使用位掩码,在其中您将权限或角色分配为固定的二进制数字,然后可以根据以下内容进行过滤:

// lib/rights.js
module.exports = {
  READ : 1 << 0, // 001
  WRITE : 1 << 1, // 010
  DELETE : 1 << 2 //100
};

// lib/roles.js
var rights = require('./rights');
    module.exports = {
      ADMIN : rights.READ ^ rights.WRITE ^ rights.DELETE,
      MEMBER : rights.READ ^ rights.WRITE,
      GUEST : rights.READ
    };

Then you can check pretty easily: 然后,您可以轻松检查:

if (user.role & resource.rightsRequired) { /* you're in! */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM