我有一个如下所示的 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
});
到目前为止,我的所有验证都在模式中进行,我想知道如何通过密码验证来实现这一点。用户在两个字段中输入密码,模型应该检查它们是否相同。
这种验证是否属于架构?我是这种验证的新手。
我应该如何验证密码?
最佳答案
我最终发现,您可以使用 virtual paths 和 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);
关于node.js - 使用 Mongoose 模式验证密码/确认密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13982159/