【问题标题】:Passport-Local Mongoose - Change password?Passport-Local Mongoose - 更改密码?
【发布时间】:2013-07-23 14:43:09
【问题描述】:

我使用Passport-Local Mongoose 来加密帐户的密码。但是不知道怎么改密码。

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

【问题讨论】:

    标签: node.js mongoose passwords passport.js


    【解决方案1】:

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

    【讨论】:

    • 老线程,无论如何:实际上,您不需要身份验证。从 account 中检索用户,setPassword,然后在回调中 user.save,你就完成了。
    • 在某种意义上的身份验证,即“忘记密码”电子邮件或其他确保用户身份的方式
    【解决方案2】:

    无需认证。使用 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() 和模型中的护照选项返回密码或盐字段。

    【讨论】:

      【解决方案3】:

      很好的答案,但对于来自 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)...
      });
      

      【讨论】:

        【解决方案4】:

        在 passport-local-mongoose 中,您不必在 schema 中创建任何方法,而是可以直接使用 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'})
                     }
                     });
        

        【讨论】:

          【解决方案5】:

          【讨论】:

            【解决方案6】:

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

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

            【讨论】:

              【解决方案7】:

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

              【讨论】:

                猜你喜欢
                • 2014-07-21
                • 2017-09-25
                • 2021-08-21
                • 1970-01-01
                • 2021-08-15
                • 1970-01-01
                • 2021-10-13
                • 2018-11-07
                • 2018-12-13
                相关资源
                最近更新 更多