prevent unconfirmed users from logging in

This commit is contained in:
shibao 2022-02-16 22:16:08 -05:00 committed by oliviasculley
parent 059004ba78
commit 97a9b6d51a
3 changed files with 22 additions and 5 deletions

View File

@ -279,7 +279,7 @@ defmodule Lokal.Accounts do
end end
end end
defp confirm_user_multi(user) do def confirm_user_multi(user) do
Ecto.Multi.new() Ecto.Multi.new()
|> Ecto.Multi.update(:user, User.confirm_changeset(user)) |> Ecto.Multi.update(:user, User.confirm_changeset(user))
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"])) |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"]))

View File

@ -5,8 +5,8 @@ defmodule LokalWeb.UserAuth do
import Plug.Conn import Plug.Conn
import Phoenix.Controller import Phoenix.Controller
import LokalWeb.Gettext
alias Lokal.Accounts alias Lokal.{Accounts, Accounts.User}
alias LokalWeb.Router.Helpers, as: Routes alias LokalWeb.Router.Helpers, as: Routes
# Make the remember me cookie valid for 60 days. # 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 disconnected on log out. The line can be safely removed
if you are not using LiveView. 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) token = Accounts.generate_user_session_token(user)
user_return_to = get_session(conn, :user_return_to) user_return_to = get_session(conn, :user_return_to)
@ -136,7 +149,7 @@ defmodule LokalWeb.UserAuth do
conn conn
else else
conn 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() |> maybe_store_return_to()
|> redirect(to: Routes.user_session_path(conn, :new)) |> redirect(to: Routes.user_session_path(conn, :new))
|> halt() |> halt()

View File

@ -17,6 +17,7 @@ defmodule LokalWeb.ConnCase do
use ExUnit.CaseTemplate use ExUnit.CaseTemplate
alias Ecto.Adapters.SQL.Sandbox alias Ecto.Adapters.SQL.Sandbox
alias Lokal.{Accounts, Repo}
using do using do
quote do quote do
@ -48,6 +49,9 @@ defmodule LokalWeb.ConnCase do
""" """
def register_and_log_in_user(%{conn: conn}) do def register_and_log_in_user(%{conn: conn}) do
user = Lokal.AccountsFixtures.user_fixture() user = Lokal.AccountsFixtures.user_fixture()
{:ok, %{user: user}} = user |> Accounts.confirm_user_multi() |> Repo.transaction()
%{conn: log_in_user(conn, user), user: user} %{conn: log_in_user(conn, user), user: user}
end end