Gà *_* Rù 16 passwords mongoose node.js passport.js
我使用Passport-Local Mongoose加密帐户的密码.但我不知道如何更改密码.
你能举一些文件或例子来做吗?谢谢.
use*_*287 20
查看源代码时,会有一个函数添加到名为setPassword的模式中.我相信经过身份验证后,您可以调用它来更改用户的密码.
schema.methods.setPassword = function (password, cb) {
if (!password) {
return cb(new BadRequestError(options.missingPasswordError));
}
var self = this;
crypto.randomBytes(options.saltlen, function(err, buf) {
if (err) {
return cb(err);
}
var salt = buf.toString('hex');
crypto.pbkdf2(password, salt, options.iterations, options.keylen, function(err, hashRaw) {
if (err) {
return cb(err);
}
self.set(options.hashField, new Buffer(hashRaw, 'binary').toString('hex'));
self.set(options.saltField, salt);
cb(null, self);
});
});
};
Run Code Online (Sandbox Code Playgroud)
ste*_*red 12
无需验证.使用findByUsername()方法从帐户中检索用户,该方法由passport-local-mongoose放置在模型上,然后运行setPassword(),然后user.save()在回调中.
userModel.findByUsername(email).then(function(sanitizedUser){
if (sanitizedUser){
sanitizedUser.setPassword(newPasswordString, function(){
sanitizedUser.save();
res.status(200).json({message: 'password reset successful'});
});
} else {
res.status(500).json({message: 'This user does not exist'});
}
},function(err){
console.error(err);
})
Run Code Online (Sandbox Code Playgroud)
我打电话给用户sanitizedUser()是因为我已经将passport-local-mongoose配置为不使用findByUsername()模型中的密码或盐字段以及护照选项.
小智 9
很好的答案,但对于那些来自MEAN堆栈的人(使用本地护照,而不是护照本地猫鼬):
//in app/models/user.js
/**
* Virtuals
*/
UserSchema.virtual('password').set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
}).get(function() {
return this._password;
});
Run Code Online (Sandbox Code Playgroud)
所以这会改变传球:
user.password = '12345678';//and after this setter...
user.save(function(err){ //...save
if(err)...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15373 次 |
| 最近记录: |