Write the password reset request handler:
User will post their email address and we will send an email with the reset url.
users/routes.js
// POST /password_reset
exports.passwordRest = function (req, res) {
req.onValidationError(function (msg) {
//Redirect to `/password_reset` if email is bogus
return res.redirect('/password_rest');
});
req.check('email', 'Please enter a valid email').len(1).isEmail();
// get the user
User.findOne({email: req.body.email}, function (err, usr) {
if (err) {
// TODO return error
}
if (!usr) {
// TODO return message if user is not found
}
// Create a token UserToken
UserToken.new(usr._id, function (err, token) {
// build the reset url:
// http://localhost:3000/password_reset/12345TOKEN
var resetUrl = req.protocol + '://' + req.host + '/password_reset/' + token.token;
// Create the template vars
var locals = {
resetUrl: resetUrl,
// TODO confirm that the user has email prior to sending this.
email: usr.emails[0].value
};
mailer.sendOne('password_reset', locals, function (err, respMs) {
// TODO add success message.
// redirect to password_rest success page.
return req.redirect('/');
});
});
});
};
Write the password token check url:
users/routes.js
// POST /password_reset/<token>
exports.passwordRestCheck = function (req, res) {
// Check for a UserToken using the supplied token.
UserToken({token: req.params.token}, function (err, token) {
if (err) {
// TODO return error
}
if (!token) {
// TODO return message if token is not found
}
// get the user
User.findOne({_id: token.userId}, function (err, user) {
if (err) {
// TODO return error
}
if (!user) {
// TODO return message if token is not found
}
// log the user in
req.logIn(user, function (err) {
if (err) {
// TODO return error
}
// redirect the user to a password reset form
return res.redirect('/account/password');
});
});
});
};
Add the routes to app.js
app.js
//...
app.post('/password_reset', users.passwordReset);
app.get('/password_reset/:token', users.passwordResetCheck);