Passport-Local Mongoose – 更改密码?

我使用Passport-Local Mongoose来encryption帐户的密码。 但我不知道如何更改密码。 任何人都知道该怎么办? TKS

查看源代码,有一个函数被添加到名为setPassword的模式中。 我相信validation后,你可以调用它来改变用户的密码。

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

不需要authentication。 使用findByUsername()方法从passport-local- findByUsername()放置在模型中,然后运行setPassword() ,然后在callback中运行findByUsername() ,从帐户中检索用户。

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

我调用了用户sanitizedUser()因为我configuration了passport-local- findByUsername()而不是使用findByUsername()和模型中的护照选项返回密码或盐字段。

很好的答案,但对于来自MEAN堆栈的人(使用护照本地,而不是护照本地mongoose):

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

所以这将改变通过:

 user.password = '12345678';//and after this setter... user.save(function(err){ //...save if(err)... });