我已经设置好使用NodeJS/Passport更新用户密码.

99%的工作正常.我不得不对它进行一些修改,以包含一些条带功能.不过,我恐怕在某个地方有一个严重的错误,我找不到.用户目前可以通过向其发送邮箱,输入新密码,然后登录.随后,另一封邮箱称他们的密码已成功更新.一切都很完美.然而出于某种原因.未保存新密码.用户只能使用旧密码登录.我想尽一切办法来解决这个问题.

我已经让其他几个程序员看到了这一点,但他们中没有一个人能够弄明白它究竟是如何不起作用的.

目前的 idea 是,会话可能没有正确结束,但我们试图 destruct 会话,但仍然没有成功.

非常感谢您的帮助.

完整设置:

User Model:

var UserSchema = new mongoose.Schema({
    username:   { type: String, required: true, unique: true },
    password:  String,
    datapoint:  String,
    email:  { type: String, required: true, unique: true },
    resetPasswordToken: String,
    resetPasswordExpires: Date
});


UserSchema.pre('save', function(next) {
  var user = this;
  var SALT_FACTOR = 5;

  if (!user.isModified('password')) return next();

  bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
    if (err) return next(err);

    bcrypt.hash(user.password, salt, null, function(err, hash) {
      if (err) return next(err);
      user.password = hash;
      next();
    });
  });
});

Register New Account

var newUser = new User({username: req.body.username, email: req.body.email, datapoint: req.body.datapoint});
      User.register(newUser, req.body.password, function(err, user){


            if(err){
            console.log('Looks like there was an error:' + ' ' + err)
             res.redirect('/login')

          } else {
          passport.authenticate("local")(req, res, function(){

      var user = new User({
      username: req.body.username,
      email: req.body.email,
      password: req.body.password

      })


console.log('creating new account')
console.log('prepping charge')
var token = req.body.stripeToken; // Using Express
var charge = stripe.charges.create({
  amount: 749,
  currency: "usd",
  description: "Example charge",
  source: token,

}, function(err, charge) {
  // asynchronously called
  console.log('charged')
});
            res.redirect('/jobquiz')
             console.log(req.body.datapoint)
             console.log(req.body.email)

          });
          }
      });
});

Set up forgot password posting

app.post('/forgot', function(req, res, next) {
  async.waterfall([
    function(done) {
      crypto.randomBytes(20, function(err, buf) {
        var token = buf.toString('hex');
        done(err, token);
      });
    },
    function(token, done) {
      User.findOne({ email: req.body.email }, function(err, user) {
        if (!user) {
        //   console.log('error', 'No account with that email address exists.');
        req.flash('error', 'No account with that email address exists.');
          return res.redirect('/forgot');
        }
console.log('step 1')
        user.resetPasswordToken = token;
        user.resetPasswordExpires = Date.now() + 3600000; // 1 hour

        user.save(function(err) {
          done(err, token, user);
        });
      });
    },
    function(token, user, done) {
        console.log('step 2')


      var smtpTrans = nodemailer.createTransport({
         service: 'Gmail', 
         auth: {
          user: 'myemail',
          pass: 'mypassword'
        }
      });
      var mailOptions = {

        to: user.email,
        from: 'myemail',
        subject: 'Node.js Password Reset',
        text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
          'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
          'http://' + req.headers.host + '/reset/' + token + '\n\n' +
          'If you did not request this, please ignore this email and your password will remain unchanged.\n'

      };
      console.log('step 3')

        smtpTrans.sendMail(mailOptions, function(err) {
        req.flash('success', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
        console.log('sent')
        res.redirect('/forgot');
});
}
  ], function(err) {
    console.log('this err' + ' ' + err)
    res.redirect('/');
  });
});

app.get('/forgot', function(req, res) {
  res.render('forgot', {
    User: req.user
  });
});

Set up changing password post

app.get('/reset/:token', function(req, res) {
  User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
      console.log(user);
    if (!user) {
      req.flash('error', 'Password reset token is invalid or has expired.');
      return res.redirect('/forgot');
    }
    res.render('reset', {
     User: req.user
    });
  });
});




app.post('/reset/:token', function(req, res) {
  async.waterfall([
    function(done) {
      User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user, next) {
        if (!user) {
          req.flash('error', 'Password reset token is invalid or has expired.');
          return res.redirect('back');
        }


        user.password = req.body.password;
        user.resetPasswordToken = undefined;
        user.resetPasswordExpires = undefined;
        console.log('password' + user.password  + 'and the user is' + user)

user.save(function(err) {
  if (err) {
      console.log('here')
       return res.redirect('back');
  } else { 
      console.log('here2')
    req.logIn(user, function(err) {
      done(err, user);
    });

  }
        });
      });
    },





    function(user, done) {
        // console.log('got this far 4')
      var smtpTrans = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
          user: 'myemail',
          pass: 'mypass'
        }
      });
      var mailOptions = {
        to: user.email,
        from: 'myemail',
        subject: 'Your password has been changed',
        text: 'Hello,\n\n' +
          ' - This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
      };
      smtpTrans.sendMail(mailOptions, function(err) {
        // req.flash('success', 'Success! Your password has been changed.');
        done(err);
      });
    }
  ], function(err) {
    res.redirect('/');
  });
});

推荐答案

我没有(或没有)发现你的代码有任何问题,但我有一个跟踪错误的建议.

这段代码有风险.您可能会意外地更新密码字段并触发重新设置密码的过程.

UserSchema.pre('save', function(next) {
   var user = this;
   var SALT_FACTOR = 12; // 12 or more for better security

   if (!user.isModified('password')) return next();

   console.log(user.password) // Check accident password update

   bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
      if (err) return next(err);

      bcrypt.hash(user.password, salt, null, function(err, hash) {
         if (err) return next(err);
         user.password = hash;
         next();
      });
   });
});

if (!user.isModified('password'))后面加一个console.log,判断是否有意外的密码更新.现在重试忘记密码,看看是否有任何错误.

*运输署;LR在新方法中单独更新密码,而不是将其放入预保存,因为您可能会意外地更新新密码以及其他字段

*更新:感谢#imns建议一个更好的盐系数.

Mongodb相关问答推荐

我们可以在Mongoose中这样使用Unique:[True,";This to Unique&qot;]吗

Mongo DB-如果一个特定字段有多个文档匹配,则更新文档字段

为什么数组长度0被认为是Mongoose中排序中最大的数字

Spring数据MongoDB(聚合)

MongoDB 聚合 - 条件 $lookup 取决于字段是否存在

通过insertId MongoDB获取文档

有没有一种方法可以找到一个文档并通过 Go 更改 mongodb 中的 id/value 来克隆它

在mongoose 中按键查找嵌套对象

在推入 mongodb 时自动填充 golang struct 中的 created_at 和 updated_at

Pymongo API TypeError: Unhashable dict

mongoose中的 required是什么意思?

使用 mongoimport 将日期(ISODate)导入 MongoDB

MongoDB聚合排序不起作用

使用 MongoDB 进行嵌套分组

单个模式数组中的多个模式引用 - mongoose

如何使用node.js http服务器从mongodb返回大量行?

mongodb: UnknownError assertion src/mongo/db/server_options_helpers.cpp:355

使用自定义 _id 值时 mongodb 中的 Upserts

120 个 mongodb 集合与单个集合 - 哪个更有效?

如何从集合中删除除 MongoDB 中的文档之外的所有文档