From 97a9b6d51a86d23757854083175fb6e693453c4f Mon Sep 17 00:00:00 2001 From: shibao Date: Wed, 16 Feb 2022 22:16:08 -0500 Subject: [PATCH] prevent unconfirmed users from logging in --- lib/lokal/accounts.ex | 2 +- lib/lokal_web/controllers/user_auth.ex | 21 +++++++++++++++++---- test/support/conn_case.ex | 4 ++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/lokal/accounts.ex b/lib/lokal/accounts.ex index 40eb1a23..fdaa9ee1 100644 --- a/lib/lokal/accounts.ex +++ b/lib/lokal/accounts.ex @@ -279,7 +279,7 @@ defmodule Lokal.Accounts do end end - defp confirm_user_multi(user) do + def confirm_user_multi(user) do Ecto.Multi.new() |> Ecto.Multi.update(:user, User.confirm_changeset(user)) |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"])) diff --git a/lib/lokal_web/controllers/user_auth.ex b/lib/lokal_web/controllers/user_auth.ex index de994481..57237d59 100644 --- a/lib/lokal_web/controllers/user_auth.ex +++ b/lib/lokal_web/controllers/user_auth.ex @@ -5,8 +5,8 @@ defmodule LokalWeb.UserAuth do import Plug.Conn import Phoenix.Controller - - alias Lokal.Accounts + import LokalWeb.Gettext + alias Lokal.{Accounts, Accounts.User} alias LokalWeb.Router.Helpers, as: Routes # Make the remember me cookie valid for 60 days. @@ -28,7 +28,20 @@ defmodule LokalWeb.UserAuth do disconnected on log out. The line can be safely removed if you are not using LiveView. """ - def log_in_user(conn, user, params \\ %{}) do + def log_in_user(conn, user, params \\ %{}) + + def log_in_user(conn, %User{confirmed_at: nil}, _params) do + conn + |> put_flash( + :error, + dgettext("errors", "You must confirm your account and log in to access this page.") + ) + |> maybe_store_return_to() + |> redirect(to: Routes.user_session_path(conn, :new)) + |> halt() + end + + def log_in_user(conn, user, params) do token = Accounts.generate_user_session_token(user) user_return_to = get_session(conn, :user_return_to) @@ -136,7 +149,7 @@ defmodule LokalWeb.UserAuth do conn else conn - |> put_flash(:error, "You must log in to access this page.") + |> put_flash(:error, "You must confirm your account and log in to access this page.") |> maybe_store_return_to() |> redirect(to: Routes.user_session_path(conn, :new)) |> halt() diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 5fecabfc..10d8b7be 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -17,6 +17,7 @@ defmodule LokalWeb.ConnCase do use ExUnit.CaseTemplate alias Ecto.Adapters.SQL.Sandbox + alias Lokal.{Accounts, Repo} using do quote do @@ -48,6 +49,9 @@ defmodule LokalWeb.ConnCase do """ def register_and_log_in_user(%{conn: conn}) do user = Lokal.AccountsFixtures.user_fixture() + + {:ok, %{user: user}} = user |> Accounts.confirm_user_multi() |> Repo.transaction() + %{conn: log_in_user(conn, user), user: user} end