%{"email" => email}}) when is_binary(email) do
- email = String.trim(email)
+ def create(conn, %{"subscriber" => params}) when is_map(params) do
+ email = params["email"]
- case MailingList.subscribe(email) do
- {:ok, :already_subscribed} ->
- conn
- |> put_flash(:info, "You're already on the mailing list.")
- |> redirect(to: @return_to)
+ cond do
+ honeypot_filled?(params) ->
+ fake_success(conn)
- {:ok, :confirmation_required} ->
- case send_confirmation(email) do
- :ok ->
- conn
- |> put_flash(:info, "Check your inbox to confirm your subscription.")
- |> redirect(to: @return_to)
+ not is_binary(email) ->
+ invalid_email(conn)
- :error ->
- conn
- |> put_flash(:error, "We couldn't send the confirmation email. Please try again.")
- |> redirect(to: @return_to)
- end
+ MailingListFormToken.verify(params["form_token"]) != :ok ->
+ form_error(conn)
- {:error, %Ecto.Changeset{}} ->
- conn
- |> put_flash(:error, "Enter a valid email address.")
- |> redirect(to: @return_to)
+ true ->
+ subscribe(conn, email)
end
end
- def create(conn, _params) do
- conn
- |> put_flash(:error, "Enter a valid email address.")
- |> redirect(to: @return_to)
- end
+ def create(conn, _params), do: invalid_email(conn)
def confirm(conn, %{"token" => token}) do
case Phoenix.Token.verify(
@@ -77,13 +63,63 @@ defmodule ChesstrainerWeb.MailingListController do
end
end
- defp send_confirmation(email) do
+ defp subscribe(conn, email) do
+ email = String.trim(email)
+
+ case MailingList.subscribe(email) do
+ {:ok, :already_subscribed} ->
+ conn
+ |> put_flash(:info, "You're already on the mailing list.")
+ |> redirect(to: @return_to)
+
+ {:ok, :confirmation_required} ->
+ if MailingList.confirmation_allowed?(email) do
+ send_confirmation(conn, email)
+ else
+ fake_success(conn)
+ end
+
+ {:error, %Ecto.Changeset{}} ->
+ invalid_email(conn)
+ end
+ end
+
+ defp send_confirmation(conn, email) do
token = Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @token_salt, email)
url = url(~p"/mailing-list/confirm/#{token}")
case Notifier.deliver_confirmation_instructions(email, url) do
- {:ok, _email} -> :ok
- {:error, _reason} -> :error
+ {:ok, _email} ->
+ _ = MailingList.mark_confirmation_sent(email)
+
+ conn
+ |> put_flash(:info, "Check your inbox to confirm your subscription.")
+ |> redirect(to: @return_to)
+
+ {:error, _reason} ->
+ conn
+ |> put_flash(:error, "We couldn't send the confirmation email. Please try again.")
+ |> redirect(to: @return_to)
end
end
+
+ defp honeypot_filled?(params), do: params["company"] not in [nil, ""]
+
+ defp fake_success(conn) do
+ conn
+ |> put_flash(:info, "Check your inbox to confirm your subscription.")
+ |> redirect(to: @return_to)
+ end
+
+ defp form_error(conn) do
+ conn
+ |> put_flash(:error, "Please refresh the page and try again.")
+ |> redirect(to: @return_to)
+ end
+
+ defp invalid_email(conn) do
+ conn
+ |> put_flash(:error, "Enter a valid email address.")
+ |> redirect(to: @return_to)
+ end
end
diff --git a/lib/chesstrainer_web/live/user_live/profile.ex b/lib/chesstrainer_web/live/user_live/profile.ex
index 862abf6..66e3985 100644
--- a/lib/chesstrainer_web/live/user_live/profile.ex
+++ b/lib/chesstrainer_web/live/user_live/profile.ex
@@ -4,6 +4,7 @@ defmodule ChesstrainerWeb.UserLive.Profile do
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
+ alias Chesstrainer.MailingList
@recent_attempts 25
@@ -159,6 +160,27 @@ defmodule ChesstrainerWeb.UserLive.Profile do
+
+
+
+
+ You're subscribed to occasional endgame tips and site news.
+
+
+
+ You're not subscribed to the mailing list.
+
+
+ <.button
+ :if={@mailing_list_subscribed?}
+ id="unsubscribe-mailing-list"
+ variant="secondary"
+ phx-click="unsubscribe_mailing_list"
+ >
+ Unsubscribe
+
+
+
More site settings will appear here as they become available.
@@ -332,6 +354,24 @@ defmodule ChesstrainerWeb.UserLive.Profile do
end
end
+ def handle_event("unsubscribe_mailing_list", _params, socket) do
+ user = socket.assigns.current_scope.user
+
+ case MailingList.unsubscribe_user(user) do
+ {:ok, _subscriber} ->
+ {:noreply,
+ socket
+ |> assign(:mailing_list_subscribed?, false)
+ |> put_flash(:info, "You've been removed from the mailing list.")}
+
+ {:error, :not_found} ->
+ {:noreply,
+ socket
+ |> assign(:mailing_list_subscribed?, false)
+ |> put_flash(:info, "You're not on the mailing list.")}
+ end
+ end
+
def handle_event("delete_account", _params, socket) do
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
@@ -348,10 +388,16 @@ defmodule ChesstrainerWeb.UserLive.Profile do
case socket.assigns.live_action do
:account -> assign_account(socket)
:data -> assign_data(socket)
+ :settings -> assign_settings(socket)
_ -> socket
end
end
+ defp assign_settings(socket) do
+ user = socket.assigns.current_scope.user
+ assign(socket, :mailing_list_subscribed?, MailingList.user_subscribed?(user))
+ end
+
defp assign_account(socket) do
user = socket.assigns.current_scope.user
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
diff --git a/lib/chesstrainer_web/mailing_list_form_token.ex b/lib/chesstrainer_web/mailing_list_form_token.ex
new file mode 100644
index 0000000..bf648b2
--- /dev/null
+++ b/lib/chesstrainer_web/mailing_list_form_token.ex
@@ -0,0 +1,38 @@
+defmodule ChesstrainerWeb.MailingListFormToken do
+ @moduledoc """
+ Signed timestamp hidden in the mailing-list signup form.
+
+ Used as a timing check: submissions that arrive faster than a human could
+ plausibly fill the form are rejected. The timestamp is signed so a bot
+ cannot simply make one up.
+ """
+
+ @salt "mailing_list_form"
+ @max_age 2 * 60 * 60
+ @min_seconds 2
+
+ @type verify_result :: :ok | :too_fast | :expired | :invalid
+
+ @doc "Signs the current time for the hidden form field."
+ def sign, do: sign(System.system_time(:second))
+
+ @doc false
+ def sign(signed_at) when is_integer(signed_at) do
+ Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @salt, signed_at, signed_at: signed_at)
+ end
+
+ @doc "Checks a submitted form token."
+ @spec verify(term()) :: verify_result()
+ def verify(token) when is_binary(token) do
+ now = System.system_time(:second)
+
+ case Phoenix.Token.verify(ChesstrainerWeb.Endpoint, @salt, token, max_age: @max_age) do
+ {:ok, signed_at} when is_integer(signed_at) and now - signed_at >= @min_seconds -> :ok
+ {:ok, _signed_at} -> :too_fast
+ {:error, :expired} -> :expired
+ {:error, _reason} -> :invalid
+ end
+ end
+
+ def verify(_token), do: :invalid
+end
diff --git a/mix.exs b/mix.exs
index 8182728..434aff8 100644
--- a/mix.exs
+++ b/mix.exs
@@ -62,6 +62,7 @@ defmodule Chesstrainer.MixProject do
depth: 1},
{:swoosh, "~> 1.16"},
{:req, "~> 0.5"},
+ {:gen_smtp, "~> 1.2"},
{:telemetry_metrics, "~> 1.0"},
{:telemetry_poller, "~> 1.0"},
{:gettext, "~> 1.0"},
diff --git a/mix.lock b/mix.lock
index 40405e6..a48769e 100644
--- a/mix.lock
+++ b/mix.lock
@@ -17,6 +17,7 @@
"file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"},
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
"fine": {:hex, :fine, "0.1.6", "4bf7151493443c454aac9f2fa2f34f5fefd0346a83fb5586a016c4a135c63247", [:mix], [], "hexpm", "5638eb4495488e885ebec167fa57973e5c35e1a50c344eb7666c90ec1c4e3b12"},
+ "gen_smtp": {:hex, :gen_smtp, "1.3.0", "62c3d91f0dcf6ce9db71bcb6881d7ad0d1d834c7f38c13fa8e952f4104a8442e", [:rebar3], [{:ranch, ">= 1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "0b73fbf069864ecbce02fe653b16d3f35fd889d0fdd4e14527675565c39d84e6"},
"gettext": {:hex, :gettext, "1.0.2", "5457e1fd3f4abe47b0e13ff85086aabae760497a3497909b8473e0acee57673b", [:mix], [{:expo, "~> 0.5.1 or ~> 1.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "eab805501886802071ad290714515c8c4a17196ea76e5afc9d06ca85fb1bfeb3"},
"glicko": {:hex, :glicko, "0.8.1", "3f038a9b1022116d19e33f03b95641d8a199882d718592f9b03bbdc63d55215c", [:mix], [], "hexpm", "86dc0c86f3ef442d8c0b977d377a8aed50bc732ebf4582eb1bf19b87d7bd5b1c"},
"heroicons": {:git, "https://github.com/tailwindlabs/heroicons.git", "0435d4ca364a608cc75e2f8683d374e55abbae26", [tag: "v2.2.0", sparse: "optimized", depth: 1]},
@@ -40,6 +41,7 @@
"plug": {:hex, :plug, "1.19.2", "e4950525b22c6789dfb38a3f95d47171ba159da3fc5a33be9643b43d5e8adb98", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b6fce20a56af5e60fa5dfecf3f907bb98ec981be43c79a3809a499bc3d133de0"},
"plug_crypto": {:hex, :plug_crypto, "2.1.1", "19bda8184399cb24afa10be734f84a16ea0a2bc65054e23a62bb10f06bc89491", [:mix], [], "hexpm", "6470bce6ffe41c8bd497612ffde1a7e4af67f36a15eea5f921af71cf3e11247c"},
"postgrex": {:hex, :postgrex, "0.22.2", "4aec14df2a72722aee92492566edbeeb44e233ecb86b1915d03136297ef1385d", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "8946382ddb06294f56026ac4278b3cc212bac8a2c82ed68b4087819ed1abc53b"},
+ "ranch": {:hex, :ranch, "2.3.0", "7de7b041a9a6a5091a3aa5898d66c0564be671d87db4f9d63b1b5ee775b097df", [:make, :rebar3], [], "hexpm", "6168ec49409d982f7cfbd83dd083144f6cbe67caa4036551d2f0a3ad67c9d023"},
"req": {:hex, :req, "0.6.2", "b9b2024f35bcf60a92cc8cad2eaaf9d4e7aace463ff74be1afe5986830184413", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "cc9cd30a2ddd04989929b887178e1610c940456d962c6c3a52df6146d2eef9bf"},
"rustler": {:hex, :rustler, "0.38.0", "7a8906998ff0d28e3021c0a73264abcda719bda344b2e58307c6805b0f87c9b4", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "704c03c1bf66be12b031c5a389347b91c81c5cb819a24b068b0de36fe4a5652a"},
"swoosh": {:hex, :swoosh, "1.26.1", "2989f1089e3cf1a938bbd3908c11d7dba8c8a4fe78801a7762d26f01bdbb32b4", [:mix], [{:bandit, ">= 1.0.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, ">= 1.9.0 and < 5.0.0", [hex: :hackney, repo: "hexpm", optional: true]}, {:idna, ">= 6.0.0 and < 8.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mua, "~> 0.2.3", [hex: :mua, repo: "hexpm", optional: true]}, {:multipart, "~> 0.4", [hex: :multipart, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:req, "~> 0.5.10 or ~> 0.6 or ~> 1.0", [hex: :req, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "8ad197c025102bbcbaffcd67c10ff7b390746c32f534ff5158891b149460118e"},
diff --git a/priv/repo/migrations/20261109141840_add_unsubscribed_at_to_mailing_list_subscribers.exs b/priv/repo/migrations/20261109141840_add_unsubscribed_at_to_mailing_list_subscribers.exs
new file mode 100644
index 0000000..3a720da
--- /dev/null
+++ b/priv/repo/migrations/20261109141840_add_unsubscribed_at_to_mailing_list_subscribers.exs
@@ -0,0 +1,9 @@
+defmodule Chesstrainer.Repo.Migrations.AddUnsubscribedAtToMailingListSubscribers do
+ use Ecto.Migration
+
+ def change do
+ alter table(:mailing_list_subscribers) do
+ add :unsubscribed_at, :utc_datetime
+ end
+ end
+end
diff --git a/priv/repo/migrations/20261109153254_add_confirmation_sent_at_to_mailing_list_subscribers.exs b/priv/repo/migrations/20261109153254_add_confirmation_sent_at_to_mailing_list_subscribers.exs
new file mode 100644
index 0000000..2a9a8c7
--- /dev/null
+++ b/priv/repo/migrations/20261109153254_add_confirmation_sent_at_to_mailing_list_subscribers.exs
@@ -0,0 +1,9 @@
+defmodule Chesstrainer.Repo.Migrations.AddConfirmationSentAtToMailingListSubscribers do
+ use Ecto.Migration
+
+ def change do
+ alter table(:mailing_list_subscribers) do
+ add :confirmation_sent_at, :utc_datetime
+ end
+ end
+end
diff --git a/test/chesstrainer/accounts_test.exs b/test/chesstrainer/accounts_test.exs
index cf8d34e..4e82161 100644
--- a/test/chesstrainer/accounts_test.exs
+++ b/test/chesstrainer/accounts_test.exs
@@ -9,6 +9,8 @@ defmodule Chesstrainer.AccountsTest do
alias Chesstrainer.Attempts
alias Chesstrainer.Attempts.Attempt
alias Chesstrainer.Accounts.Scope
+ alias Chesstrainer.MailingList
+ alias Chesstrainer.MailingList.Subscriber
describe "get_user_by_email/1" do
test "does not return the user if the email does not exist" do
@@ -340,6 +342,19 @@ defmodule Chesstrainer.AccountsTest do
refute Repo.get_by(UserToken, user_id: user.id)
end
+ test "updates the linked mailing-list address", %{
+ user: user,
+ token: token,
+ email: email
+ } do
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+ MailingList.confirm_user_subscription(user)
+
+ assert {:ok, %{email: ^email}} = Accounts.update_user_email(user, token)
+
+ assert %Subscriber{email: ^email} = Repo.get_by(Subscriber, user_id: user.id)
+ end
+
test "does not update email with invalid token", %{user: user} do
assert Accounts.update_user_email(user, "oops") ==
{:error, :transaction_aborted}
diff --git a/test/chesstrainer/mailing_list_test.exs b/test/chesstrainer/mailing_list_test.exs
index 0776a97..53b6023 100644
--- a/test/chesstrainer/mailing_list_test.exs
+++ b/test/chesstrainer/mailing_list_test.exs
@@ -127,4 +127,172 @@ defmodule Chesstrainer.MailingListTest do
Repo.get_by(Subscriber, email: "player@example.com")
end
end
+
+ describe "unsubscribe/1" do
+ test "marks a confirmed address as unsubscribed" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.confirm("player@example.com")
+
+ assert {:ok, %Subscriber{unsubscribed_at: unsubscribed_at}} =
+ MailingList.unsubscribe("player@example.com")
+
+ assert unsubscribed_at
+ assert MailingList.count_confirmed_subscribers() == 0
+ end
+
+ test "is idempotent" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.confirm("player@example.com")
+
+ {:ok, first} = MailingList.unsubscribe("player@example.com")
+ {:ok, second} = MailingList.unsubscribe("player@example.com")
+
+ assert first.unsubscribed_at == second.unsubscribed_at
+ end
+
+ test "returns not found for an unknown address" do
+ assert {:error, :not_found} = MailingList.unsubscribe("nobody@example.com")
+ end
+ end
+
+ describe "unsubscribe_user/1" do
+ test "unsubscribes the address linked to the user" do
+ user = user_fixture()
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+ MailingList.confirm_user_subscription(user)
+
+ assert {:ok, %Subscriber{unsubscribed_at: unsubscribed_at}} =
+ MailingList.unsubscribe_user(user)
+
+ assert unsubscribed_at
+ refute MailingList.user_subscribed?(user)
+ end
+
+ test "returns not found when the user is not on the list" do
+ assert {:error, :not_found} = MailingList.unsubscribe_user(user_fixture())
+ end
+ end
+
+ describe "user_subscribed?/1" do
+ test "is true only for a confirmed, active subscription" do
+ user = user_fixture()
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+
+ refute MailingList.user_subscribed?(user)
+
+ MailingList.confirm_user_subscription(user)
+ assert MailingList.user_subscribed?(user)
+
+ {:ok, _subscriber} = MailingList.unsubscribe_user(user)
+ refute MailingList.user_subscribed?(user)
+ end
+ end
+
+ describe "re-subscribing after unsubscribe" do
+ test "requires a fresh confirmation and clears the unsubscribe" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.confirm("player@example.com")
+ {:ok, _subscriber} = MailingList.unsubscribe("player@example.com")
+
+ assert {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+
+ assert {:ok, %Subscriber{confirmed_at: confirmed_at, unsubscribed_at: nil}} =
+ MailingList.confirm("player@example.com")
+
+ assert confirmed_at
+ assert MailingList.count_confirmed_subscribers() == 1
+ end
+ end
+
+ describe "update_subscriber_email/2" do
+ test "moves the linked subscription to the new address" do
+ user = user_fixture()
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+ MailingList.confirm_user_subscription(user)
+
+ new_email = unique_user_email()
+
+ assert {:ok, %Subscriber{email: ^new_email}} =
+ MailingList.update_subscriber_email(user, new_email)
+
+ assert Repo.get_by(Subscriber, user_id: user.id).email == new_email
+ end
+
+ test "removes an anonymous row that already holds the new address" do
+ user = user_fixture()
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+ new_email = unique_user_email()
+ {:ok, :confirmation_required} = MailingList.subscribe(new_email)
+
+ assert {:ok, _subscriber} = MailingList.update_subscriber_email(user, new_email)
+
+ assert Repo.aggregate(Subscriber, :count) == 1
+ assert %Subscriber{user_id: user_id} = Repo.get_by(Subscriber, email: new_email)
+ assert user_id == user.id
+ end
+
+ test "keeps an unsubscribe from an anonymous row at the new address" do
+ user = user_fixture()
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+ MailingList.confirm_user_subscription(user)
+ new_email = unique_user_email()
+ {:ok, :confirmation_required} = MailingList.subscribe(new_email)
+ {:ok, _subscriber} = MailingList.confirm(new_email)
+ {:ok, _subscriber} = MailingList.unsubscribe(new_email)
+
+ assert {:ok, %Subscriber{unsubscribed_at: unsubscribed_at}} =
+ MailingList.update_subscriber_email(user, new_email)
+
+ assert unsubscribed_at
+ refute MailingList.user_subscribed?(user)
+ end
+
+ test "does nothing when the user is not on the list" do
+ user = user_fixture()
+
+ assert {:ok, :no_subscription} =
+ MailingList.update_subscriber_email(user, unique_user_email())
+ end
+ end
+
+ describe "confirmation cooldown" do
+ test "allows an address that has never received a confirmation" do
+ assert MailingList.confirmation_allowed?("player@example.com")
+ end
+
+ test "blocks a recently sent confirmation" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.mark_confirmation_sent("player@example.com")
+
+ refute MailingList.confirmation_allowed?("player@example.com")
+ end
+
+ test "allows another send after the cooldown" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+
+ Repo.get_by(Subscriber, email: "player@example.com")
+ |> Ecto.Changeset.change(
+ confirmation_sent_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
+ )
+ |> Repo.update!()
+
+ assert MailingList.confirmation_allowed?("player@example.com")
+ end
+
+ test "allows a confirmed address" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.confirm("player@example.com")
+
+ assert MailingList.confirmation_allowed?("player@example.com")
+ end
+
+ test "still applies after an unsubscribe" do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.confirm("player@example.com")
+ {:ok, _subscriber} = MailingList.unsubscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.mark_confirmation_sent("player@example.com")
+
+ refute MailingList.confirmation_allowed?("player@example.com")
+ end
+ end
end
diff --git a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs
index 57591ef..b2a1de7 100644
--- a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs
+++ b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs
@@ -1,14 +1,19 @@
defmodule ChesstrainerWeb.MailingListControllerTest do
use ChesstrainerWeb.ConnCase, async: true
+ alias Chesstrainer.MailingList
alias Chesstrainer.MailingList.Subscriber
alias Chesstrainer.Repo
+ alias ChesstrainerWeb.MailingListFormToken
@salt "mailing_list_confirm"
describe "POST /mailing-list" do
test "sends a confirmation email for a new address", %{conn: conn} do
- conn = post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
assert redirected_to(conn) == "/#mailing-list"
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Check your inbox"
@@ -17,32 +22,140 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
assert_received {:email, email}
assert email.subject == "Confirm your mailing list subscription"
assert email.text_body =~ "/mailing-list/confirm/"
+ assert email.reply_to == {"", "support@innersquare.app"}
end
- test "resends confirmation for an address that has not confirmed yet", %{conn: conn} do
- post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
- assert_received {:email, _email}
+ test "re-confirms an address that previously unsubscribed", %{conn: conn} do
+ {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
+ {:ok, _subscriber} = MailingList.confirm("player@example.com")
+ {:ok, _subscriber} = MailingList.unsubscribe("player@example.com")
- conn = post(build_conn(), ~p"/mailing-list", subscriber: %{email: "player@example.com"})
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Check your inbox"
- assert_received {:email, _email}
- assert Repo.aggregate(Subscriber, :count) == 1
- end
- test "does not email an address that has already confirmed", %{conn: conn} do
- post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
assert_received {:email, email}
get(build_conn(), "/mailing-list/confirm/#{extract_token(email)}")
- conn = post(build_conn(), ~p"/mailing-list", subscriber: %{email: "player@example.com"})
+ subscriber = Repo.get_by(Subscriber, email: "player@example.com")
+ assert subscriber.confirmed_at
+ assert subscriber.unsubscribed_at == nil
+ assert MailingList.count_confirmed_subscribers() == 1
+ end
+
+ test "does not resend confirmation while the cooldown is active", %{conn: conn} do
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
+ assert_received {:email, _email}
+
+ conn =
+ post(build_conn(), ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
+ assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Check your inbox"
+ refute_received {:email, _email}
+ assert Repo.aggregate(Subscriber, :count) == 1
+ end
+
+ test "resends confirmation after the cooldown", %{conn: conn} do
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
+ assert_received {:email, _email}
+
+ subscriber = Repo.get_by(Subscriber, email: "player@example.com")
+
+ subscriber
+ |> Ecto.Changeset.change(
+ confirmation_sent_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
+ )
+ |> Repo.update!()
+
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
+ assert_received {:email, _email}
+ end
+
+ test "silently accepts a honeypot submission", %{conn: conn} do
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{
+ email: "player@example.com",
+ company: "spam.example",
+ form_token: form_token()
+ }
+ )
+
+ assert redirected_to(conn) == "/#mailing-list"
+ assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Check your inbox"
+ refute_received {:email, _email}
+ assert Repo.aggregate(Subscriber, :count) == 0
+ end
+
+ test "rejects a form token submitted too quickly", %{conn: conn} do
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: MailingListFormToken.sign()}
+ )
+
+ assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "refresh the page"
+ refute_received {:email, _email}
+ assert Repo.aggregate(Subscriber, :count) == 0
+ end
+
+ test "rejects an expired form token", %{conn: conn} do
+ token = MailingListFormToken.sign(System.system_time(:second) - 3 * 60 * 60)
+
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: token}
+ )
+
+ assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "refresh the page"
+ refute_received {:email, _email}
+ end
+
+ test "rejects an invalid form token", %{conn: conn} do
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: "oops"}
+ )
+
+ assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "refresh the page"
+ refute_received {:email, _email}
+ end
+
+ test "does not email an address that has already confirmed", %{conn: conn} do
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
+ assert_received {:email, email}
+ get(build_conn(), "/mailing-list/confirm/#{extract_token(email)}")
+
+ conn =
+ post(build_conn(), ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "already on the mailing list"
refute_received {:email, _email}
end
test "reports an invalid address", %{conn: conn} do
- conn = post(conn, ~p"/mailing-list", subscriber: %{email: "not an email"})
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "not an email", form_token: form_token()}
+ )
assert redirected_to(conn) == "/#mailing-list"
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address"
@@ -60,7 +173,10 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
describe "GET /mailing-list/confirm/:token" do
test "confirms the subscription from the emailed link", %{conn: conn} do
- post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
assert_received {:email, email}
conn = get(build_conn(), "/mailing-list/confirm/#{extract_token(email)}")
@@ -107,4 +223,8 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
[_, token] = Regex.run(~r{/mailing-list/confirm/(\S+)}, email.text_body)
token
end
+
+ defp form_token do
+ MailingListFormToken.sign(System.system_time(:second) - 5)
+ end
end
diff --git a/test/chesstrainer_web/controllers/page_controller_test.exs b/test/chesstrainer_web/controllers/page_controller_test.exs
index 393b9b3..e72c266 100644
--- a/test/chesstrainer_web/controllers/page_controller_test.exs
+++ b/test/chesstrainer_web/controllers/page_controller_test.exs
@@ -194,6 +194,9 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert html =~ "Join the list"
assert html =~ ~s(name="_csrf_token")
+ assert html =~ ~s(name="subscriber[form_token]")
+ assert html =~ ~s(id="mailing-list-company")
+ assert html =~ ~s(class="mailing-list-honeypot")
end
test "guest navbar links to log in and register", %{conn: conn} do
diff --git a/test/chesstrainer_web/live/user_live/profile_test.exs b/test/chesstrainer_web/live/user_live/profile_test.exs
index baed8fe..c5fa0aa 100644
--- a/test/chesstrainer_web/live/user_live/profile_test.exs
+++ b/test/chesstrainer_web/live/user_live/profile_test.exs
@@ -4,6 +4,9 @@ defmodule ChesstrainerWeb.UserLive.ProfileTest do
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
+ alias Chesstrainer.MailingList
+ alias Chesstrainer.MailingList.Subscriber
+ alias Chesstrainer.Repo
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
import Chesstrainer.EndgamesFixtures
@@ -303,4 +306,38 @@ defmodule ChesstrainerWeb.UserLive.ProfileTest do
assert message == "You must log in to access this page."
end
end
+
+ describe "mailing list settings" do
+ setup %{conn: conn} do
+ user = user_fixture()
+ %{conn: log_in_user(conn, user), user: user}
+ end
+
+ test "shows the not-subscribed state", %{conn: conn} do
+ {:ok, view, html} = live(conn, ~p"/users/profile/settings")
+
+ assert has_element?(view, "#mailing-list-settings")
+ assert html =~ "not subscribed"
+ refute has_element?(view, "#unsubscribe-mailing-list")
+ end
+
+ test "unsubscribes a subscribed user", %{conn: conn, user: user} do
+ {:ok, _subscriber} = MailingList.subscribe_user(user)
+ MailingList.confirm_user_subscription(user)
+
+ {:ok, view, _html} = live(conn, ~p"/users/profile/settings")
+
+ assert has_element?(view, "#unsubscribe-mailing-list")
+
+ html = view |> element("#unsubscribe-mailing-list") |> render_click()
+
+ assert html =~ "removed from the mailing list"
+ refute has_element?(view, "#unsubscribe-mailing-list")
+
+ assert %Subscriber{unsubscribed_at: unsubscribed_at} =
+ Repo.get_by(Subscriber, user_id: user.id)
+
+ assert unsubscribed_at
+ end
+ end
end