如何使基于角色的中间件以Node.js和Mongoose中的适当权限访问api?

时间:2018-12-15 14:47:51

标签: node.js mongodb express mongoose

我正在尝试制作具有角色权限的网站 将会是

SuperAdmin - will approve admins and will have all right which admin have

Admin - will approve articles and will have all the rights which loggedin user have

Loggedin User - can post articles and will have all the rights which guest user have.

Guest(Non Loggedin User) - can see articles.

我有一个想法来制作具有role key的架构,我制作了所有api,但是不知道如何授予权限,因此特定的apis被有权访问的人访问。< / p>

能否请某人帮助我制作此身份验证中间件?

先感谢

1 个答案:

答案 0 :(得分:1)

因此,首先,您应该在req对象中具有用户角色。我想你做到了。然后,您可以为数据库中的角色指定别名。例如

SuperAdmin - superadmin

Admin - admin

Loggedin User - user

Guest(Non Loggedin User) - you do not need to have a role for a guest, you just can check whether user authenticated or not

示例中间件看起来像

// Authentication middleware
const isAuthenticated = (roles) => (req, res, next) => {
  // `roles` argument is an array of roles
  // We check whether user authenticated or not.
  // If user authenticated, `req.user` will be object otherwise it will be `undefined` 
  if(req.user) { // `req.user` is a user object from Database
    // Checking whether `req.user` has a corresponded role
    if (roles.indexOf(req.user.role) !== -1) next(); // `req.user.role` is string and it may be "admin", "superadmin", or "user"
    else res.status(403).send({message: "unauthorized"}); 
  } else {
    res.status(401).send({message: "unauthorized"});
  }
};

您可以在路由器上使用此中间件

const express = require('express');
const router = express.Router();

// Example routes

// This route is for guests
router.get('/articles', (req, res) => {
  res.send({'article': 'lorem ipsum'})
});

// This route is for authenticated user
router.get('/forOnlyAuthUser', isAuthenticated(['user']) (req, res) => {
  res.send({user: req.user})
});

// This route is for admin
router.get('/forOnlyAdmin', isAuthenticated(['admin']) (req, res) => {
  res.send({user: req.user})
});

// This route is for superadmin
router.get('/forOnlySuperadmin', isAuthenticated(['superadmin']) (req, res) => {
  res.send({user: req.user})
});

// This route is for all authenticated users
router.get('/forOnlyAllAuthUsers', isAuthenticated(['user', 'admin', 'superadmin']) (req, res) => {
  res.send({user: req.user})
});

您可以根据需要自定义isAuthenticated函数