如何获得基于角色的授权才能从此状态开始工作?

时间:2019-02-28 13:38:02

标签: node.js express roles

我在路线上添加了基于角色的授权,无论我尝试使用哪个用户通过邮递员发出请求,我都不断收到代码中的“禁止”错误。角色在用户上声明。用户的默认角色是“用户”,而我有一个具有“管理员”角色的其他用户。

我的路线

var express = require('express');
var router = express.Router();
const AuthenticationController = require('./controllers/AuthenticationController')
const AuthenticationControllerPolicy = require('./policies/AuthenticationControllerPolicy')
const ProjectController = require('./controllers/ProjectController')
const UserController = require('./controllers/UserController')
const Role = require('./_helpers/role');
const permit = require("./middleware/permission");

router.post('/register',
  AuthenticationControllerPolicy.register,
  AuthenticationController.register)
router.post('/login',
  AuthenticationController.login)


router.get('/projects',
  ProjectController.getProjects)
router.post('/projects/create', permit('Admin'),
  ProjectController.createProject)


router.get('/users',
  UserController.getUsers)
router.get('/users/:user_id', permit('Users'),
  UserController.getUser)

module.exports = router;

我的Permissions.js

function permit(...allowed) {
  const isAllowed = role => allowed.indexOf(role) > -1;

  // return a middleware
  return (req, res, next) => {
    if (req.user && isAllowed(req.user.role))
      next(); // role is allowed, so continue on the next middleware
    else {
      res.status(403).json({message: "Forbidden"}); // user is forbidden
    }
  }
}

module.exports = permit

0 个答案:

没有答案