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
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"]))

View File

@ -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()

View File

@ -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