如何创建此权限中间件?

时间:2018-06-04 03:26:48

标签: javascript node.js mongoose

我在尝试制作基于多角色的权限中间件时遇到了麻烦,具体而言,猫鼬模型(用户)有一组群组。

let UserSchema = Schema(
  username: String,
  password: String,
  group: [{
    "_id": {type: Schema.ObjectId, ref: 'Group'},
    "add_date": String,
    "role_comment": String
  }]
});

现在,我有这个猫鼬模型(组):

let GroupSchema = Schema({
  name: String,
  web_permissions: {
    example1: {
      create: Boolean,
      read: Boolean,
      update: Boolean,
      delete: Boolean
    },
    example2: {
      create: Boolean,
      read: Boolean,
      update: Boolean,
      delete: Boolean
  }
});

所以,现在我有一个JWT-Token中间件,它有req.user作为有效载荷,现在,我正在尝试创建一个中间件,您可以分配以查找是否有任何用户组" true&# 34;就此而言,这是一个例子:

api.post(
  '/create-example1', 
  [
    md_auth.ensureAuth, 
    md_permissions.ensurePerms(group.web_permissions.example1.create)
  ],
  UserController.getUsers
);

现在,这是我尝试创建的中间件,我尝试使用map()forEach()来检测其中一个是否可以继续,但我和#39;我对此非常困惑,如果您对如何做到这一点有所了解,我将非常感激,谢谢。

let Group = require('../models/group');
let User = require('../models/user');

exports.ensurePerms = function(permission) {
  return function(req, res, next) {
    try {
      if(permission !== undefined) {
        User.findOne({"_id" : req.user.sub}).populate("group").exec((err, user) =>  {
          if (err)
            return res.status(500).send({
              message: "Ha ocurrido un error al realizar la búsqueda de permisos."
            });
          // I need here to detect if any group has that permission in "true", if not, return a res.status(403)
        });
      }
    } catch(e) {
      console.log(err);
    }
    next();
  }
};

0 个答案:

没有答案