In the last post we added some functionality to our authentication system. We added a “Remember me” functionality to allow users to log in using a cookie and we also added an activation process that authenticates the email address we get from the user.
On this post, i’ll cover password resets:
The logic behind a password reset process is rather simple, basically it is very similar to the activation process we did before.
- We create some kind of a temporary (perishable) token that identifies the user who wishes to reset the password.
- We send the user an email with a link that contains that token and leads to a page that allows the user to choose a new password.
- We update the new password, and start dancing.
First, we are going to add a field that will contain that reset token, and a method to generate it when required:
That’s basically it.
We need to add a few actions:
- one to generate the token and trigger the reset password email.
- one to show a “reset password” form with password and password confirmation field.
- and last, an action to save the new password and log in the user. We can’t use the
#updateaction because we need a little different behavior that i think is enough to justify a separate action: First we need to find the user record based on a token not by
idand second, we need to use our
logout_keeping_sessionto make sure no malicious changes are made to a logged in user if it exists.
The process will work like that:
- The user will be able to go on a form and enter his email in case they forgot the password, that action will be
- If the user entered a valid email address (and one that identifies a user on the application), then
UsersController#send_password_resetwill generate a new reset token and send the user with reset instructions.
- When the user follows the reset link on the email, they’ll arrive on
UsersController#reset_passwordthat will match the reset token from the URI to a specific user on the system and allow the user to enter a new password if matched.
- Once the user had changed and saved the password, they will be logged off and asked to re-login with their new password.
Here’s the current
Source for the UsersController#forgot_password view, UsersController#send_password_reset view, “UserMailer model”http://gist.github.com/325983, Reset instructions mail template and UsersController#reset_password added.
Again, it seems that we tackled most of the problems we had with Mongoid in the early stages and practically nothing bothered us too much since the first part of this series.
I keep the implementation of a background processor until a bit later, it is not that important at this stage so we’ll get back to it later.