Tuesday, 2 May 2017

Reset password using passport.js - seems to work but password not reset

I'm implementing a reset password function in my app. I've managed to get it so that when a user enters their email in a 'forgot password' form, an email is generated (using nodemailer) containing a link with a reset token. This link takes them to a reset password form. When I try this out, the form seems to work ok and the user is redirected to the home page as desired with a flash message stating password has been changed and an email is generated confirming they have changed their password. So the code seems to run through without error, however the password clearly isn't being updated as when I go to log in again, the old password is still the one that works.

Here's my reset password form:

<% include ./partials/header %>

Reset password

New password Confirm password Reset password
<% include ./partials/footer %>

And here's the route that handles the password update POST function:

router.post('/reset/:token', function(req, res) {
async.waterfall([
function(done) {
  User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
    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;

    user.save(function(err) {
      req.logIn(user, function(err) {
        done(err, user);
      });
    });
  });
},
function(user, done) {
  var smtpTransport = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
      user: '******@gmail.com',
      pass: '*******'
    }
  });
  var mailOptions = {
    to: user.email,
    from: 'passwordreset@demo.com',
    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'
  };
  smtpTransport.sendMail(mailOptions, function(err) {
    req.flash('success', 'Success! Your password has been changed.');
    done(err);
  });
}
], function(err) {
res.redirect('/');
});
});

Can anyone see where I'm going wrong here?



via DaveB1

No comments:

Post a Comment