Node.js Passport本地猫鼬-更改密码?

Node.js Passport本地猫鼬-更改密码?,node.js,mongoose,passwords,passport.js,Node.js,Mongoose,Passwords,Passport.js,我使用加密帐户的密码。但我不知道如何更改密码 你能给出一些文件或例子来做这件事吗?谢谢。查看源代码,有一个函数被添加到模式中,名为setPassword。 我相信在验证后,您可以调用它来更改用户的密码 schema.methods.setPassword = function (password, cb) { if (!password) { return cb(new BadRequestError(options.missingPasswordError));

我使用加密帐户的密码。但我不知道如何更改密码


你能给出一些文件或例子来做这件事吗?谢谢。

查看源代码,有一个函数被添加到模式中,名为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);
        });
    });
};

回答很好,但对于那些来自平均值堆栈的人(使用passport local,而不是passport local mongoose):

因此,这将改变通行证:

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

不需要验证。使用
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);
})

我调用用户
sanitizedUser()
,因为我已经配置了passport local mongoose,使用
findByUsername()
和模型中的passport选项不返回密码或salt字段。

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

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


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

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

})

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

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


const sanitizedUser=await User.findByUsername(用户名);
试一试{
等待sanitizedUser.setPassword(新密码);
等待sanitizedUser.save();
res.status(200).json({message:'Successful!'});
} 
捕捉(错误){
res.status(422).send(err);
}

Old-thread,无论如何:实际上,您不需要身份验证。从帐户中检索用户,设置密码,然后在回调中保存user.save,您就完成了身份验证,即“忘记密码”电子邮件或其他确保用户身份的方法
 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'})
             }
             });