【问题标题】:Find a way to update the user passport with passport-local-mongoose找到一种使用 passport-local-mongoose 更新用户护照的方法
【发布时间】:2016-01-30 02:58:38
【问题描述】:

我正在使用 nodejspassport-local-mongoose 创建一个应用程序, 问题是我找不到更新用户密码的方法,因为护照使用 Salt 和 Hash,有一些方法或方法可以通过 PUT 方法更新密码吗?

【问题讨论】:

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


    【解决方案1】:

    假设您已将 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
            });
        });
    });
    

    【讨论】:

      【解决方案2】:

      如果要更改密码,可以使用 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'})
               } 
               });
      

      【讨论】:

        猜你喜欢
        • 2018-07-27
        • 2013-07-23
        • 2023-03-30
        • 2018-11-07
        • 2022-07-30
        • 2014-07-21
        • 2021-08-21
        • 2014-07-24
        • 1970-01-01
        相关资源
        最近更新 更多