In this lesson, we're going to cover how to send a password reset link via email. If you've skipped any lessons so far, you'll want to make sure that you've at least implemented transactional email.
Resetting a password is more complicated than you might expect. The way password reset works is
First, create a link that allows a user to request a new password
Second, create the view that for the user to submit the reset link
Third, generate and send the password reset link via email
Fourth, create another view that accepts a token as a query parameter and sends the new password along with the token
Fifth, match the token with an existing user account
Sixth, automatically log the user in if the token and new password is valid
The first thing we're going to do is change our backend to accept a password reset. We're going to need two additional endpoints to add this functionality.
The first endpoint will be reset-request which will take the initial request from the frontend and will include the email address for which we want to reset the password. The second endpoint will be reset which will pass along the new password and a (presumably) valid token in order to reset the password of the account that made the request. Let's add those endpoints now.
...scope "/api", PhoenixChat do pipe_through [:api, :api_auth] resources "/users", UserController, except: [:index, :show, :new, :edit] post "/users/reset-request", UserController, :reset_request, as: :reset post "/users/reset", UserController, :reset, as: :reset ...end...The next thing we should do is update our UserController. You can see in the code above that we created two new functions, :reset_request and :reset, so we should define those now. We will start with reset_request, which is the function we'll call along with an email to send the reset link to the email address specified. We'll go over each line below the code block.
defmodule PhoenixChat.UserController do ... def reset_request(conn, %{"email" => email}) do user = Repo.get_by(User, email: String.downcase(email)) if user do user |> User.password_reset_changeset |> Repo.update! |> send_password_reset_email send_resp(conn, :no_content, "") else send_resp(conn, :bad_request, "user does not exist") end end ...endFirst, we check to see if the user exists by using Repo.get_by. If the user exists, we pass the user along to the password_reset_changeset (which we will create later) that will generate the token and store it along with our user so we can match against it later.
Then we send it along to the send_password_reset_email function, which we will define later. If it does not exist, we send along an error.
In order to store this token with our user, we need to create a new migration to update our User model.
$ mix ecto.gen.migration add_user_password_reset_fieldsWithin our new migration, we need to add two fields. One is the token that we will match against and the other is a timestamp for the last time a user changed her password.
defmodule PhoenixChat.Repo.Migrations.AddUserPasswordResetFields do use Ecto.Migration def change do alter table(:users) do add :password_reset_token, :string, default: nil add :password_reset_timestamp, :datetime end endendGo ahead and run mix ecto.migrate. Now that we have our model updated, we need to create our password_reset_changeset. This looks similar to our other changesets except for the put_token function, in which we will generate a token and add it to our user.
...def password_reset_changeset(model, params \\ %{}) do model |> changeset(params) |> put_change(:password_reset_timestamp, Ecto.DateTime.utc) |> put_token(:password_reset_token)end...Now we need to define put_token. In the function below, we're checking to make sure the changeset is valid (recall that changesets have the valid? parameter), and if it is, we call generate_token (defined later) and use put_change to add the token to our user.
...def put_token(changeset, field) when field in ~w(password_reset_token)a do case changeset do %Ecto.Changeset{valid?: true} -> token = generate_token() put_change(changeset, field, token) _ -> changeset endend...So now we need to define generate_token. All we're doing is creating a 50-character random string.
...defp generate_token do 50 |> :crypto.strong_rand_bytes |> Base.url_encode64 |> binary_part(0, 50)end...This confuses a lot of people because it's so simple. Contrary to what you might think, there is no magic that comes with keys or tokens—they're just random numbers and letters that you match against another key or token.
In our case, we are creating a token and saving it with our user. When that user requests a new password, we send along that token as a query parameter in a link via email. When that link is clicked, we search our database for matching tokens, and if we find a match, we allow the user to reset the password.
Now that we have our token, we need to define the password reset email function, which we're calling in our reset_request function. This simply takes in the user and passes it along to the Email.password_reset_email function, which we will also need to define.
defmodule PhoenixChat.UserController do ... defp send_password_reset_email(user) do user |> Email.password_reset_email |> Mailer.deliver_later end ...endNow we need to define the email that is sent to the user who forgot her password. Recall that we're taking in the user, which now has a password_reset_token field. For now, we're going to hard-code the reset link, but eventually we would want to use the email_reset_link function to set the link based on the environment (test, dev, prod, etc).
The first thing we do is URI encode the query so that it makes for a valid link, then we concatenate it with the email_reset_link. From there, we pass along the reset_link to the email address associated with the current user.
defmodule PhoenixChat.Email do ... def password_reset_email(user) do query = URI.encode_query(token: user.password_reset_token) reset_link = "#{email_reset_link}?#{query}" user |> base_email |> subject("Password Reset") |> text_body(""" A password reset was requested, follow #{reset_link} to reset your password. If this was a mistake, please ignore this email. """) end defp email_reset_link do # This will eventually handle for environment using # Application.get_env(PhoenixChat.Mailer) "http://localhost:3000/#/reset-password" end ...endNow, when a user clicks on the link, she will be directed a page that will allow her to set a new password.
The last thing we need to do before moving to the frontend is to set up our reset endpoint that will actually allow our user to change her password.
In this function, we're going to find the user that has the matching token (user_for_password_token), ensure that the token is less than 48 hours old, update the password, send the user an email, and log the user in.
Adding an expiration is a good idea from a security perspective because it limits the time that an account could be potentially vulnerable. That said, it's still next to impossible that someone can guess a 50-character token in their lifetime no matter how many guesses per second (see our blog post for more information on collision probabilities), so leaving an account sort-of-vulnerable for 48 hours is not a big deal.
defmodule PhoenixChat.UserController do ... def reset(conn, %{"token" => token, "password" => password}) do case user_for_password_token(token) do user = %User{} -> user |> User.registration_changeset(%{password: password}) |> Repo.update! {:ok, jwt, _claims} = Guardian.encode_and_sign(user, :token) send_password_change_email(user) conn |> put_status(:ok) |> render("show.json", user: user, web_token: jwt) nil -> conn |> put_status(:bad_request) |> render(ErrorView, "error.json", errors: ["invalid or expired token"]) end end ...endThis should all look familiar. We are using user_for_password_token (defined below) to match the token and sure validity, then using the existing registration_changeset to update the password, then Guardian.encode_and_sign to log the user in, just as we did before in our automatic login on signup, and finally sending the email.
The user_for_password_token function is a little bit tricky. We're creating a query that searches through our User models and finds a password_reset_token that matches the token that was passed into the function. Then, it checks to make sure that the timestamp is less than 48 hours old using fragment, which allows us to send database queries directly to Postgres.
... defp user_for_password_token(token) do query = from u in User, where: u.password_reset_token == ^token and u.password_reset_timestamp > fragment("now() - interval '48hours'"), select: u Repo.one(query) end...Now we need to define the function in which we send the confirmation email.
...defp send_password_change_email(user) do user |> Email.password_change_email |> Mailer.deliver_laterend...And finally, define the email.
...def password_change_email(user) do user |> base_email |> subject("Password Change") |> text_body("Your password on Learn Phoenix has been updated recently.")end...And that's it for our backend. Now we need to create the forms on our frontend and connect it to our backend.
Previous: Basics of Analytics