找一种用passport-local-mongoose

时间:2015-10-29 19:39:10

标签: node.js mongoose passport.js mean-stack passport-local

我正在使用 nodejs passport-local-mongoose 创建应用, 问题是我找不到更新用户密码的方法,因为护照使用Salt和Hash,有一些方法或某种方法通过PUT方法更新密码?

2 个答案:

答案 0 :(得分:0)

假设您已将passport-local-mongoose插件添加到用户架构中,您应该可以调用 您的用户架构上的setPassword(password, cb)

yourSchemaName.findById(id, function(err, user) {
    user.setPassword(req.body.password, function(err) {
        if (err) //handle error
        user.save(function(err) {
            if (err) //handle error
            else //handle success
        });
    });
});

答案 1 :(得分:0)

如果要更改密码,可以使用changePassword命令。 这是一个例子

router.post('/changepassword', function(req, res) {
// Search for user in database
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'})
         } 
         });