20

我使用Passport-Local Mongoose来加密帐户的密码。但我不知道如何更改密码。

你能给出一些文件或例子吗?谢谢你。

4

7 回答 7

21

查看源代码,有一个函数被添加到名为 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);
        });
    });
};
于 2013-08-04T14:59:40.640 回答
16

无需认证。使用方法从 account 中检索用户findByUsername(),该方法由passport-local-mongoose放置在模型上,然后 run 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);
})

我打电话给用户sanitizedUser()是因为我已将passport-local-mongoosefindByUsername()配置为不使用模型中的password 选项和passport 选项返回密码或salt 字段。

于 2015-09-30T16:52:26.577 回答
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;
});

所以这会改变通行证:

user.password = '12345678';//and after this setter...
user.save(function(err){ //...save
    if(err)...
});
于 2014-01-23T14:05:34.010 回答
3

在 passport-local-mongoose 中,您不必在模式中创建任何方法,而是可以直接使用 changePassword 命令。这是一个例子

router.post('/changepassword', function(req, res) {

User.findOne({ _id: 'your id here' },(err, user) => {
  // Check if error connecting
  if (err) {
    res.json({ success: false, message: err }); // Return error
  } else {
    // Check if user was found in database
    if (!user) {
      res.json({ success: false, message: 'User not found' }); // Return error, user was not found in db
    } else {
      user.changePassword(req.body.oldpassword, req.body.newpassword, function(err) {
         if(err) {
                  if(err.name === 'IncorrectPasswordError'){
                       res.json({ success: false, message: 'Incorrect password' }); // Return error
                  }else {
                      res.json({ success: false, message: 'Something went wrong!! Please try again after sometimes.' });
                  }
        } else {
          res.json({ success: true, message: 'Your password has been changed successfully' });
         }
       })
    }
  }
});   });

如果您想在不使用旧密码的情况下更改密码,请使用 setPassword 方法。它用于忘记密码的情况。这是代码

 user.setPassword(req.body.password, function(err,user){
if (err) {
    res.json({success: false, message: 'Password could not be saved. 
  Please try again!'})
} else { 
  res.json({success: true, message: 'Your new password has been saved 
successfully'})
             }
             });
于 2019-04-02T04:48:14.970 回答
2

如其他答案所述,您需要从数据库中获取用户对象的新实例,该实例是异步的,因此您需要用户等待或使用回调/承诺函数,如下所示......

User.findOne({ username: req.user.username })
.then((u) => {
    u.setPassword(req.body.newPassword,(err, u) => {
        if (err) return next(err);
        u.save();
        res.status(200).json({ message: 'password change successful' });
    });

})
于 2019-01-18T13:58:18.833 回答
1

我认为您可以使用在 4.1.0 版中实现的 changepassword 方法

https://github.com/saintedlama/passport-local-mongoose/blob/master/CHANGELOG.md#410--2017-08-08

对于实施参考,您可以在以下位置检查书面测试:

https://github.com/saintedlama/passport-local-mongoose/blob/807d9cf669f7a7c433eb0206c97574761c03b8e5/test/passport-local-mongoose.js#L217

于 2018-12-18T10:40:56.760 回答
0

使用 async/await 方法,您可以改进@steampowered 的代码,如下所示:

  

    const sanitizedUser = await User.findByUsername(userName);

    try {
      await sanitizedUser.setPassword(newPassword);
      await sanitizedUser.save();
      res.status(200).json({ message: 'Successful!' });
    } 
    catch (err) {
      res.status(422).send(err);
    }
 

于 2020-02-27T10:13:49.340 回答