diff --git a/lib/chesstrainer/accounts.ex b/lib/chesstrainer/accounts.ex index c551c72..9119bba 100644 --- a/lib/chesstrainer/accounts.ex +++ b/lib/chesstrainer/accounts.ex @@ -251,6 +251,48 @@ defmodule Chesstrainer.Accounts do |> update_user_and_delete_all_tokens() end + @doc ~S""" + Delivers the reset password email instructions to the given user. + + ## Examples + + iex> deliver_user_reset_password_instructions(user, &url(~p"/users/reset-password/#{&1}")) + {:ok, %{to: ..., body: ...}} + + """ + def deliver_user_reset_password_instructions(%User{} = user, reset_password_url_fun) + when is_function(reset_password_url_fun, 1) do + {encoded_token, user_token} = UserToken.build_email_token(user, "reset_password") + Repo.insert!(user_token) + UserNotifier.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token)) + end + + @doc """ + Gets the user with the given reset password token. + + Returns `nil` if the token is invalid or has expired. + """ + def get_user_by_reset_password_token(token) do + with {:ok, query} <- UserToken.verify_reset_password_token_query(token), + %UserToken{sent_to: email} <- Repo.one(query), + %User{} = user <- Repo.get_by(User, email: email) do + user + else + _ -> nil + end + end + + @doc """ + Resets the user password. + + Returns a tuple with the updated user, as well as a list of expired tokens. + """ + def reset_user_password(user, attrs) do + user + |> User.password_changeset(attrs) + |> update_user_and_delete_all_tokens() + end + ## Deletion @doc """ diff --git a/lib/chesstrainer/accounts/user_notifier.ex b/lib/chesstrainer/accounts/user_notifier.ex index 66e076b..2220cb8 100644 --- a/lib/chesstrainer/accounts/user_notifier.ex +++ b/lib/chesstrainer/accounts/user_notifier.ex @@ -37,6 +37,26 @@ defmodule Chesstrainer.Accounts.UserNotifier do """) end + @doc """ + Deliver instructions to reset a user password. + """ + def deliver_reset_password_instructions(user, url) do + deliver(user.email, "Reset password instructions", """ + + ============================== + + Hi #{user.email}, + + You can reset your password by visiting the URL below: + + #{url} + + If you didn't request this change, please ignore this. + + ============================== + """) + end + @doc """ Deliver instructions to update a user email. """ diff --git a/lib/chesstrainer/accounts/user_token.ex b/lib/chesstrainer/accounts/user_token.ex index ffed500..ae3b103 100644 --- a/lib/chesstrainer/accounts/user_token.ex +++ b/lib/chesstrainer/accounts/user_token.ex @@ -8,6 +8,7 @@ defmodule Chesstrainer.Accounts.UserToken do @change_email_validity_in_days 7 @confirm_validity_in_days 1 + @reset_password_validity_in_days 1 @session_validity_in_days 14 @primary_key {:id, :binary_id, autogenerate: true} @@ -147,6 +148,31 @@ defmodule Chesstrainer.Accounts.UserToken do end end + @doc """ + Checks if the token is valid and returns its underlying lookup query. + + The query returns the user_token found by the token, if any. + + This is used to validate requests to reset the user password. + The given token is valid if it matches its hashed counterpart in the + database and if it has not expired (after @reset_password_validity_in_days). + """ + def verify_reset_password_token_query(token) do + case Base.url_decode64(token, padding: false) do + {:ok, decoded_token} -> + hashed_token = :crypto.hash(@hash_algorithm, decoded_token) + + query = + from token in by_token_and_context_query(hashed_token, "reset_password"), + where: token.inserted_at > ago(@reset_password_validity_in_days, "day") + + {:ok, query} + + :error -> + :error + end + end + defp by_token_and_context_query(token, context) do from UserToken, where: [token: ^token, context: ^context] end diff --git a/lib/chesstrainer_web/live/user_live/login.ex b/lib/chesstrainer_web/live/user_live/login.ex index d2ef01e..117f0fd 100644 --- a/lib/chesstrainer_web/live/user_live/login.ex +++ b/lib/chesstrainer_web/live/user_live/login.ex @@ -54,6 +54,15 @@ defmodule ChesstrainerWeb.UserLive.Login do Log in only this time + +

+ <.link + navigate={~p"/users/reset-password"} + class="font-semibold text-primary hover:underline" + > + Forgot your password? + +

""" diff --git a/lib/chesstrainer_web/live/user_live/reset_password.ex b/lib/chesstrainer_web/live/user_live/reset_password.ex new file mode 100644 index 0000000..6184925 --- /dev/null +++ b/lib/chesstrainer_web/live/user_live/reset_password.ex @@ -0,0 +1,128 @@ +defmodule ChesstrainerWeb.UserLive.ResetPassword do + use ChesstrainerWeb, :live_view + + alias Chesstrainer.Accounts + + @impl true + def render(assigns) do + ~H""" + +
+
+ <.header> + {@title} + <:subtitle>{@subtitle} + +
+ + <.form for={@form} id="reset_password_form" phx-submit={@submit_event}> + <%= if @token do %> + <.input + field={@form[:password]} + type="password" + label="New password" + autocomplete="new-password" + spellcheck="false" + required + /> + <.input + field={@form[:password_confirmation]} + type="password" + label="Confirm new password" + autocomplete="new-password" + spellcheck="false" + /> + <% else %> + <.input + field={@form[:email]} + type="email" + label="Email" + autocomplete="email" + spellcheck="false" + required + /> + <% end %> + + <.button variant="primary" class="w-full" phx-disable-with="Saving..."> + {@submit_label} + + + +

+ <.link + navigate={~p"/users/log-in"} + class="font-semibold text-primary hover:underline" + > + Back to log in + +

+
+
+ """ + end + + @impl true + def mount(%{"token" => token}, _session, socket) do + case Accounts.get_user_by_reset_password_token(token) do + nil -> + {:ok, + socket + |> put_flash(:error, "Reset password link is invalid or it has expired.") + |> push_navigate(to: ~p"/users/log-in")} + + user -> + {:ok, + socket + |> assign(:user, user) + |> assign(:token, token) + |> assign(:title, "Reset password") + |> assign(:subtitle, "Choose a new password for your account.") + |> assign(:submit_label, "Reset password") + |> assign(:submit_event, "submit_password") + |> assign(:form, to_form(%{"password" => ""}, as: "user"))} + end + end + + def mount(_params, _session, socket) do + {:ok, + socket + |> assign(:user, nil) + |> assign(:token, nil) + |> assign(:title, "Forgot your password?") + |> assign(:subtitle, "Enter your email and we'll send you reset instructions.") + |> assign(:submit_label, "Send reset instructions") + |> assign(:submit_event, "submit_email") + |> assign(:form, to_form(%{"email" => ""}, as: "user"))} + end + + @impl true + def handle_event("submit_email", %{"user" => %{"email" => email}}, socket) do + if user = Accounts.get_user_by_email(String.trim(email)) do + Accounts.deliver_user_reset_password_instructions( + user, + &url(~p"/users/reset-password/#{&1}") + ) + end + + {:noreply, + socket + |> put_flash( + :info, + "If your email is in our system, you will receive instructions to reset your password shortly." + ) + |> push_navigate(to: ~p"/users/log-in")} + end + + def handle_event("submit_password", %{"user" => user_params}, socket) do + case Accounts.reset_user_password(socket.assigns.user, user_params) do + {:ok, {_user, _expired_tokens}} -> + {:noreply, + socket + |> put_flash(:info, "Password reset successfully. Log in with your new password.") + |> push_navigate(to: ~p"/users/log-in")} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, form: to_form(changeset, action: :insert))} + end + end +end diff --git a/lib/chesstrainer_web/router.ex b/lib/chesstrainer_web/router.ex index b074fed..f5956a8 100644 --- a/lib/chesstrainer_web/router.ex +++ b/lib/chesstrainer_web/router.ex @@ -83,6 +83,8 @@ defmodule ChesstrainerWeb.Router do live "/endgames/:public_code/play", EndgameLive.Play, :play live "/users/register", UserLive.Registration, :new live "/users/log-in", UserLive.Login, :new + live "/users/reset-password", UserLive.ResetPassword, :new + live "/users/reset-password/:token", UserLive.ResetPassword, :edit end get "/users/confirm/:token", UserConfirmationController, :edit diff --git a/test/chesstrainer/accounts_test.exs b/test/chesstrainer/accounts_test.exs index 7ee8d40..4dd788d 100644 --- a/test/chesstrainer/accounts_test.exs +++ b/test/chesstrainer/accounts_test.exs @@ -439,6 +439,95 @@ defmodule Chesstrainer.AccountsTest do end end + describe "deliver_user_reset_password_instructions/2" do + setup do + %{user: user_fixture()} + end + + test "sends token through notification", %{user: user} do + token = + extract_user_token(fn url -> + Accounts.deliver_user_reset_password_instructions(user, url) + end) + + {:ok, token} = Base.url_decode64(token, padding: false) + assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token)) + assert user_token.user_id == user.id + assert user_token.sent_to == user.email + assert user_token.context == "reset_password" + end + end + + describe "get_user_by_reset_password_token/1" do + setup do + user = user_fixture() + + token = + extract_user_token(fn url -> + Accounts.deliver_user_reset_password_instructions(user, url) + end) + + %{user: user, token: token} + end + + test "returns the user with a valid token", %{user: user, token: token} do + assert %User{id: id} = Accounts.get_user_by_reset_password_token(token) + assert id == user.id + end + + test "returns nil with an invalid token" do + refute Accounts.get_user_by_reset_password_token("oops") + end + + test "returns nil if the token expired", %{token: token} do + {1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]]) + + refute Accounts.get_user_by_reset_password_token(token) + end + end + + describe "reset_user_password/2" do + setup do + %{user: user_fixture()} + end + + test "updates the password", %{user: user} do + assert {:ok, {%User{} = updated_user, expired_tokens}} = + Accounts.reset_user_password(user, %{password: "new valid password"}) + + assert updated_user.id == user.id + assert expired_tokens == [] + assert is_nil(updated_user.password) + assert Accounts.get_user_by_login_and_password(user.email, "new valid password") + refute Accounts.get_user_by_login_and_password(user.email, valid_user_password()) + end + + test "deletes all tokens for the given user", %{user: user} do + token = + extract_user_token(fn url -> + Accounts.deliver_user_reset_password_instructions(user, url) + end) + + {:ok, {_, _}} = Accounts.reset_user_password(user, %{password: "new valid password"}) + + refute Repo.get_by(UserToken, user_id: user.id) + refute Accounts.get_user_by_reset_password_token(token) + end + + test "validates the new password", %{user: user} do + assert {:error, changeset} = + Accounts.reset_user_password(user, %{ + password: "not valid", + password_confirmation: "another" + }) + + assert %{ + password: ["should be at least 12 character(s)"], + password_confirmation: ["does not match password"] + } = errors_on(changeset) + end + end + describe "generate_user_session_token/1" do setup do %{user: user_fixture()} diff --git a/test/chesstrainer_web/live/user_live/reset_password_test.exs b/test/chesstrainer_web/live/user_live/reset_password_test.exs new file mode 100644 index 0000000..8ee3e62 --- /dev/null +++ b/test/chesstrainer_web/live/user_live/reset_password_test.exs @@ -0,0 +1,109 @@ +defmodule ChesstrainerWeb.UserLive.ResetPasswordTest do + use ChesstrainerWeb.ConnCase, async: true + + import Phoenix.LiveViewTest + import Chesstrainer.AccountsFixtures + import Swoosh.TestAssertions + + alias Chesstrainer.Accounts + + describe "forgot password" do + test "renders the form", %{conn: conn} do + {:ok, _lv, html} = live(conn, ~p"/users/reset-password") + + assert html =~ "Forgot your password?" + assert html =~ "Send reset instructions" + end + + test "sends reset instructions for a known email", %{conn: conn} do + user = user_fixture() + {:ok, lv, _html} = live(conn, ~p"/users/reset-password") + + form = form(lv, "#reset_password_form", user: %{"email" => user.email}) + + {:ok, _lv, html} = + render_submit(form) + |> follow_redirect(conn, ~p"/users/log-in") + + assert html =~ "If your email is in our system" + assert_email_sent(to: user.email, subject: "Reset password instructions") + end + + test "does not reveal an unknown email", %{conn: conn} do + {:ok, lv, _html} = live(conn, ~p"/users/reset-password") + + form = form(lv, "#reset_password_form", user: %{"email" => "unknown@example.com"}) + + {:ok, _lv, html} = + render_submit(form) + |> follow_redirect(conn, ~p"/users/log-in") + + assert html =~ "If your email is in our system" + refute_email_sent() + end + end + + describe "reset password" do + setup do + user = user_fixture() + + token = + extract_user_token(fn url -> + Accounts.deliver_user_reset_password_instructions(user, url) + end) + + %{user: user, token: token} + end + + test "renders the form with a valid token", %{conn: conn, token: token} do + {:ok, _lv, html} = live(conn, ~p"/users/reset-password/#{token}") + + assert html =~ "Reset password" + assert html =~ "Confirm new password" + end + + test "redirects with an error for an invalid token", %{conn: conn} do + {:ok, _lv, html} = + live(conn, ~p"/users/reset-password/oops") + |> follow_redirect(conn, ~p"/users/log-in") + + assert html =~ "Reset password link is invalid or it has expired." + end + + test "resets the password and redirects to log in", %{conn: conn, user: user, token: token} do + {:ok, lv, _html} = live(conn, ~p"/users/reset-password/#{token}") + + form = + form(lv, "#reset_password_form", + user: %{ + "password" => "new valid password", + "password_confirmation" => "new valid password" + } + ) + + {:ok, _lv, html} = + render_submit(form) + |> follow_redirect(conn, ~p"/users/log-in") + + assert html =~ "Password reset successfully" + + assert Accounts.get_user_by_login_and_password(user.email, "new valid password") + end + + test "shows validation errors for mismatched passwords", %{conn: conn, token: token} do + {:ok, lv, _html} = live(conn, ~p"/users/reset-password/#{token}") + + html = + lv + |> form("#reset_password_form", + user: %{ + "password" => "new valid password", + "password_confirmation" => "something else" + } + ) + |> render_submit() + + assert html =~ "does not match password" + end + end +end