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

我有一个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

});

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

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

我应该如何验证密码?

回答:

我最终发现,您可以结合使用

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);

以上是 验证密码/使用Mongoose模式确认密码 的全部内容, 来源链接: utcz.com/qa/398981.html

回到顶部