首页 > 解决方案 > 如何在 Node.js 中创建用户角色?

问题描述

我想在 Node.js 中创建一个“用户”角色。我同时拥有“版主”和“管理员”帐户,但我想限制版主访问某些页面。我必须构建一个中间件,但它限制了受保护页面的管理员。

这是我的路线:

function checkRole(role) {
  return function (req, res, next) {
    const user = User.findById(req.user._id);
      if (user.roleId === role) {
          next();
      } else {
        req.flash('error_msg', 'Payment Page is Restricted');
        res.redirect('back')
      }
  }
}

这是我的用户模型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var userSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    },
    gender:{
        type: String
    },
    nickname:{
        type: String
    },
    twitter:{
        type: String
    },
    skype:{
        type: String
    },
    username:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    roleId: { type: String, lowercase: true, trim: true, enum: ['admin', 'moderator'] },
    resetPasswordToken: String,
    resetPasswordExpires: Date
}, {timestamps: true})

userSchema.pre('save', function(next) {
    var user = this;
    var SALT_FACTOR = 12;

    if (!user.isModified('password')) return next();

    bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
      if (err) return next(err);

      bcrypt.hash(user.password, salt, null, function(err, hash) {
        if (err) return next(err);
        user.password = hash;
        next();
      });
    });
  });

  userSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
      if (err) return cb(err);
      cb(null, isMatch);
    });
  };

module.exports = mongoose.model('User', userSchema);

checkRole我在要限制版主的页面中包含了该功能,但管理员也受到限制。我不知道这个错误来自哪里。

标签: node.jsmongodbmongooseuser-roles

解决方案


推荐阅读