mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
email signup up flow in dev mode, therefore in place for prod
This commit is contained in:
@@ -98,9 +98,6 @@ defmodule Chesstrainer.Accounts do
|
||||
def register_user(attrs) do
|
||||
%User{}
|
||||
|> User.registration_changeset(attrs)
|
||||
# Accounts are usable straight away; email confirmation is intentionally off
|
||||
# because no production mailer adapter is configured yet.
|
||||
|> Ecto.Changeset.put_change(:confirmed_at, DateTime.utc_now(:second))
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
@@ -113,6 +110,48 @@ defmodule Chesstrainer.Accounts do
|
||||
User.registration_changeset(user, attrs, opts)
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Delivers the confirmation email instructions to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> deliver_user_confirmation_instructions(user, &url(~p"/users/confirm/#{&1}"))
|
||||
{:ok, %{to: ..., body: ...}}
|
||||
|
||||
iex> deliver_user_confirmation_instructions(confirmed_user, &url(~p"/users/confirm/#{&1}"))
|
||||
{:error, :already_confirmed}
|
||||
|
||||
"""
|
||||
def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
|
||||
when is_function(confirmation_url_fun, 1) do
|
||||
if user.confirmed_at do
|
||||
{:error, :already_confirmed}
|
||||
else
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
|
||||
Repo.insert!(user_token)
|
||||
UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Confirms a user by the given token.
|
||||
|
||||
If the token matches, the user account is marked as confirmed and the token is
|
||||
deleted. The token is valid for one day.
|
||||
"""
|
||||
def confirm_user(token) do
|
||||
with {:ok, query} <- UserToken.verify_confirmation_token_query(token),
|
||||
%UserToken{sent_to: email} <- Repo.one(query),
|
||||
%User{} = user <- Repo.get_by(User, email: email),
|
||||
{:ok, user} <- Repo.update(User.confirm_changeset(user)),
|
||||
{_count, _result} <-
|
||||
Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: "confirm"])) do
|
||||
{:ok, user}
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a user's authority role.
|
||||
|
||||
|
||||
@@ -17,6 +17,26 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to confirm account.
|
||||
"""
|
||||
def deliver_confirmation_instructions(user, url) do
|
||||
deliver(user.email, "Confirmation instructions", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can confirm your account by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't create an account with us, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to update a user email.
|
||||
"""
|
||||
|
||||
@@ -7,6 +7,7 @@ defmodule Chesstrainer.Accounts.UserToken do
|
||||
@rand_size 32
|
||||
|
||||
@change_email_validity_in_days 7
|
||||
@confirm_validity_in_days 1
|
||||
@session_validity_in_days 14
|
||||
|
||||
@primary_key {:id, :binary_id, autogenerate: true}
|
||||
@@ -121,6 +122,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 confirm the user account.
|
||||
The given token is valid if it matches its hashed counterpart in the
|
||||
database and if it has not expired (after @confirm_validity_in_days).
|
||||
"""
|
||||
def verify_confirmation_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, "confirm"),
|
||||
where: token.inserted_at > ago(@confirm_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
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
defmodule ChesstrainerWeb.UserConfirmationController do
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
|
||||
def edit(conn, %{"token" => token}) do
|
||||
case Accounts.confirm_user(token) do
|
||||
{:ok, _user} ->
|
||||
conn
|
||||
|> put_flash(:info, "User confirmed successfully.")
|
||||
|> redirect(to: ~p"/users/log-in")
|
||||
|
||||
:error ->
|
||||
conn
|
||||
|> put_flash(:error, "User not found or token is invalid.")
|
||||
|> redirect(to: ~p"/users/register")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -17,9 +17,24 @@ defmodule ChesstrainerWeb.UserSessionController do
|
||||
|> redirect(to: ~p"/users/log-in")
|
||||
|
||||
user ->
|
||||
conn
|
||||
|> put_flash(:info, "Welcome back!")
|
||||
|> UserAuth.log_in_user(user, user_params)
|
||||
if user.confirmed_at do
|
||||
conn
|
||||
|> put_flash(:info, "Welcome back!")
|
||||
|> UserAuth.log_in_user(user, user_params)
|
||||
else
|
||||
{:ok, _} =
|
||||
Accounts.deliver_user_confirmation_instructions(
|
||||
user,
|
||||
&url(~p"/users/confirm/#{&1}")
|
||||
)
|
||||
|
||||
# In order to prevent user enumeration attacks, report the same error
|
||||
# as invalid credentials.
|
||||
conn
|
||||
|> put_flash(:error, "Invalid email, username or password")
|
||||
|> put_flash(:email, String.slice(login, 0, 160))
|
||||
|> redirect(to: ~p"/users/log-in")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -81,10 +81,19 @@ defmodule ChesstrainerWeb.UserLive.Registration do
|
||||
@impl true
|
||||
def handle_event("save", %{"user" => user_params}, socket) do
|
||||
case Accounts.register_user(user_params) do
|
||||
{:ok, _user} ->
|
||||
{:ok, user} ->
|
||||
{:ok, _} =
|
||||
Accounts.deliver_user_confirmation_instructions(
|
||||
user,
|
||||
&url(~p"/users/confirm/#{&1}")
|
||||
)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Account created successfully. Please log in.")
|
||||
|> put_flash(
|
||||
:info,
|
||||
"An email with instructions for how to confirm your email address has been sent to your inbox."
|
||||
)
|
||||
|> push_navigate(to: ~p"/users/log-in")}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
|
||||
@@ -85,6 +85,8 @@ defmodule ChesstrainerWeb.Router do
|
||||
live "/users/log-in", UserLive.Login, :new
|
||||
end
|
||||
|
||||
get "/users/confirm/:token", UserConfirmationController, :edit
|
||||
|
||||
post "/users/log-in", UserSessionController, :create
|
||||
delete "/users/log-out", UserSessionController, :delete
|
||||
end
|
||||
|
||||
@@ -163,7 +163,7 @@ defmodule Chesstrainer.AccountsTest do
|
||||
assert "has already been taken" in errors_on(changeset).username
|
||||
end
|
||||
|
||||
test "registers users with a password, a confirmed account and default access" do
|
||||
test "registers users with a password, an unconfirmed account and default access" do
|
||||
email = unique_user_email()
|
||||
username = unique_username()
|
||||
|
||||
@@ -174,12 +174,70 @@ defmodule Chesstrainer.AccountsTest do
|
||||
assert user.username == username
|
||||
assert is_binary(user.hashed_password)
|
||||
assert is_nil(user.password)
|
||||
assert user.confirmed_at
|
||||
assert is_nil(user.confirmed_at)
|
||||
assert user.role == :member
|
||||
assert user.plan == :free
|
||||
end
|
||||
end
|
||||
|
||||
describe "deliver_user_confirmation_instructions/2" do
|
||||
setup do
|
||||
%{user: unconfirmed_user_fixture()}
|
||||
end
|
||||
|
||||
test "sends token through notification", %{user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_confirmation_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 == "confirm"
|
||||
end
|
||||
|
||||
test "does not send instructions when the account is already confirmed", %{user: user} do
|
||||
{:ok, user} = Repo.update(User.confirm_changeset(user))
|
||||
|
||||
assert Accounts.deliver_user_confirmation_instructions(user, fn _ -> "" end) ==
|
||||
{:error, :already_confirmed}
|
||||
end
|
||||
end
|
||||
|
||||
describe "confirm_user/1" do
|
||||
setup do
|
||||
user = unconfirmed_user_fixture()
|
||||
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_confirmation_instructions(user, url)
|
||||
end)
|
||||
|
||||
%{user: user, token: token}
|
||||
end
|
||||
|
||||
test "confirms the user with a valid token", %{user: user, token: token} do
|
||||
assert {:ok, %User{} = confirmed_user} = Accounts.confirm_user(token)
|
||||
assert confirmed_user.id == user.id
|
||||
assert confirmed_user.confirmed_at
|
||||
refute Repo.get_by(UserToken, user_id: user.id, context: "confirm")
|
||||
end
|
||||
|
||||
test "does not confirm with an invalid token", %{user: user} do
|
||||
assert Accounts.confirm_user("oops") == :error
|
||||
assert is_nil(Repo.get!(User, user.id).confirmed_at)
|
||||
end
|
||||
|
||||
test "does not confirm if the token expired", %{user: user, token: token} do
|
||||
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]])
|
||||
|
||||
assert Accounts.confirm_user(token) == :error
|
||||
assert is_nil(Repo.get!(User, user.id).confirmed_at)
|
||||
end
|
||||
end
|
||||
|
||||
describe "change_user_registration/3" do
|
||||
test "returns a user changeset" do
|
||||
assert %Ecto.Changeset{} = changeset = Accounts.change_user_registration(%User{})
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
defmodule ChesstrainerWeb.UserConfirmationControllerTest do
|
||||
use ChesstrainerWeb.ConnCase, async: true
|
||||
|
||||
import Chesstrainer.AccountsFixtures
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
alias Chesstrainer.Accounts.User
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
setup do
|
||||
%{user: unconfirmed_user_fixture()}
|
||||
end
|
||||
|
||||
describe "GET /users/confirm/:token" do
|
||||
test "confirms the user and redirects to the login page", %{conn: conn, user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_confirmation_instructions(user, url)
|
||||
end)
|
||||
|
||||
conn = get(conn, ~p"/users/confirm/#{token}")
|
||||
|
||||
assert Phoenix.Flash.get(conn.assigns.flash, :info) == "User confirmed successfully."
|
||||
assert redirected_to(conn) == ~p"/users/log-in"
|
||||
assert Repo.get!(User, user.id).confirmed_at
|
||||
end
|
||||
|
||||
test "redirects with an error for an invalid token", %{conn: conn} do
|
||||
conn = get(conn, ~p"/users/confirm/oops")
|
||||
|
||||
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
|
||||
"User not found or token is invalid."
|
||||
|
||||
assert redirected_to(conn) == ~p"/users/register"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -2,6 +2,7 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
|
||||
use ChesstrainerWeb.ConnCase, async: true
|
||||
|
||||
import Chesstrainer.AccountsFixtures
|
||||
import Swoosh.TestAssertions
|
||||
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
@@ -75,6 +76,25 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
|
||||
|
||||
assert redirected_to(conn) == ~p"/users/log-in"
|
||||
end
|
||||
|
||||
test "does not log in an unconfirmed user and resends confirmation instructions", %{
|
||||
conn: conn
|
||||
} do
|
||||
user = unconfirmed_user_fixture()
|
||||
|
||||
conn =
|
||||
post(conn, ~p"/users/log-in", %{
|
||||
"user" => %{"email" => user.email, "password" => valid_user_password()}
|
||||
})
|
||||
|
||||
refute get_session(conn, :user_token)
|
||||
|
||||
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
|
||||
"Invalid email, username or password"
|
||||
|
||||
assert redirected_to(conn) == ~p"/users/log-in"
|
||||
assert_email_sent(subject: "Confirmation instructions")
|
||||
end
|
||||
end
|
||||
|
||||
describe "DELETE /users/log-out" do
|
||||
|
||||
@@ -3,6 +3,7 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do
|
||||
|
||||
import Phoenix.LiveViewTest
|
||||
import Chesstrainer.AccountsFixtures
|
||||
import Swoosh.TestAssertions
|
||||
|
||||
describe "Registration page" do
|
||||
test "renders registration page", %{conn: conn} do
|
||||
@@ -56,7 +57,10 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do
|
||||
render_submit(form)
|
||||
|> follow_redirect(conn, ~p"/users/log-in")
|
||||
|
||||
assert html =~ "Account created successfully"
|
||||
assert html =~
|
||||
"An email with instructions for how to confirm your email address has been sent to your inbox."
|
||||
|
||||
assert_email_sent(subject: "Confirmation instructions")
|
||||
end
|
||||
|
||||
test "renders errors for duplicated email", %{conn: conn} do
|
||||
|
||||
@@ -22,6 +22,17 @@ defmodule Chesstrainer.AccountsFixtures do
|
||||
end
|
||||
|
||||
def user_fixture(attrs \\ %{}) do
|
||||
user = unconfirmed_user_fixture(attrs)
|
||||
|
||||
{:ok, user} =
|
||||
user
|
||||
|> Chesstrainer.Accounts.User.confirm_changeset()
|
||||
|> Chesstrainer.Repo.update()
|
||||
|
||||
user
|
||||
end
|
||||
|
||||
def unconfirmed_user_fixture(attrs \\ %{}) do
|
||||
{:ok, user} =
|
||||
attrs
|
||||
|> valid_user_attributes()
|
||||
|
||||
Reference in New Issue
Block a user