使用Mongoose模式验证密码/确认密码

11 mongoose mongodb node.js express

我有一个userSchema看起来像这样:

var userSchema = new Schema({
    name: {
      type: String
    , required: true
    , validate: [validators.notEmpty, 'Name is empty']
    }
  , username: {
      type: String
    , required: true
    , validate: [validators.notEmpty, 'Username is empty']
    }
  , email: {
      type: String
    , required: true
    , validate: [
        { validator: validators.notEmpty, msg: 'Email is empty' }
      , { validator: validators.isEmail, msg: 'Invalid email' }
      ]
    }
  , salt: String
  , hash: String
});
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的所有验证都发生在模式中,我想知道如何通过密码验证来实现这一点.用户将密码输入两个字段,模型应检查它们是否彼此相同.

这种验证是否属于架构?我是这种验证的新手.

我该如何验证密码?

小智 23

我最终发现你可以使用虚拟路径invalidate功能的组合来实现这一点,如本要点所示,出于与匹配密码相同的目的:https://gist.github.com/1350041

直接引用:

CustomerSchema.virtual('password')
.get(function() {
  return this._password;
})
.set(function(value) {
  this._password = value;
  var salt = bcrypt.gen_salt_sync(12);
  this.passwordHash = bcrypt.encrypt_sync(value, salt);
});

CustomerSchema.virtual('passwordConfirmation')
.get(function() {
  return this._passwordConfirmation;
})
.set(function(value) {
  this._passwordConfirmation = value;
});

CustomerSchema.path('passwordHash').validate(function(v) {
  if (this._password || this._passwordConfirmation) {
    if (!val.check(this._password).min(6)) {
      this.invalidate('password', 'must be at least 6 characters.');
    }
    if (this._password !== this._passwordConfirmation) {
      this.invalidate('passwordConfirmation', 'must match confirmation.');
    }
  }

  if (this.isNew && !this._password) {
    this.invalidate('password', 'required');
  }
}, null);
Run Code Online (Sandbox Code Playgroud)

  • 如果需要,您还可以在虚拟的“set()”函数调用中添加“this.invalidate()”调用。 (2认同)

sqr*_*ept 10

我认为密码匹配属于客户端界面,不应该到达服务器(DB层已经太多了).对于用户体验来说,最好不要让服务器往返只是告诉用户2个字符串是不同的.

至于瘦控制器,胖模型......那些所有这些银子弹都应该向原发者射击.在任何情况下都没有解决方案.在他们自己的背景下思考每个人.

在这里引入胖模型的想法,使您使用一个功能(模式验证)用于完全不同的目的(密码匹配),并使您的应用程序依赖于您现在使用的技术.有一天你会想要改变技术,你会得到一些没有模式验证的东西......然后你必须记住你的应用程序的部分功能依赖于它.而且你必须将它移回客户端或控制器.