add mailing list signup with email confirmation (#67)

This commit is contained in:
2026-11-06 22:37:40 +01:00
parent b54fb0a6d7
commit 924a3e08dc
20 changed files with 761 additions and 2 deletions
+2 -1
View File
@@ -15,6 +15,7 @@ defmodule Chesstrainer.Accounts.User do
field :rating_deviation, :float, default: 350.0
field :confirmed_at, :utc_datetime
field :authenticated_at, :utc_datetime, virtual: true
field :mailing_list, :boolean, virtual: true, default: false
timestamps(type: :utc_datetime)
end
@@ -34,7 +35,7 @@ defmodule Chesstrainer.Accounts.User do
"""
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email, :username, :password])
|> cast(attrs, [:email, :username, :password, :mailing_list])
|> validate_email(opts)
|> validate_username(opts)
|> validate_confirmation(:password, message: "does not match password")
+142
View File
@@ -0,0 +1,142 @@
defmodule Chesstrainer.MailingList do
@moduledoc """
The marketing mailing list.
Addresses arrive from the signup form on the landing page and from the
opt-in checkbox on registration. A subscriber is only active once their
address is confirmed: the landing-page form sends a confirmation email, while
the registration checkbox relies on the account-confirmation email and is
confirmed when the user's account is. A subscriber created from the landing
page has no user; one created from registration is linked to the user so
deleting the account also removes their address.
"""
import Ecto.Query, warn: false
alias Chesstrainer.Accounts.User
alias Chesstrainer.MailingList.Subscriber
alias Chesstrainer.Repo
@doc """
Requests a subscription from the landing-page form.
Returns `{:ok, :confirmation_required}` for a new or still-unconfirmed
address, so the caller can send a confirmation email, and
`{:ok, :already_subscribed}` for an address that has already confirmed.
iex> subscribe("player@example.com")
{:ok, :confirmation_required}
iex> confirm("player@example.com")
{:ok, %Subscriber{}}
iex> subscribe("player@example.com")
{:ok, :already_subscribed}
"""
def subscribe(email, opts \\ []) when is_binary(email) do
changeset =
%Subscriber{source: Keyword.get(opts, :source, :home)}
|> Subscriber.changeset(%{email: email})
if changeset.valid? do
email = Ecto.Changeset.get_field(changeset, :email)
case Repo.get_by(Subscriber, email: email) do
%Subscriber{confirmed_at: confirmed_at} when not is_nil(confirmed_at) ->
{:ok, :already_subscribed}
%Subscriber{} ->
{:ok, :confirmation_required}
nil ->
insert_subscription(changeset, email)
end
else
{:error, changeset}
end
end
@doc """
Records a newly registered user's mailing-list opt-in.
The subscriber stays unconfirmed until the account itself is confirmed. If
the address was already subscribed anonymously, the existing row is linked to
the user and re-sourced so the account deletion cascade removes it.
"""
def subscribe_user(%User{} = user) do
%Subscriber{source: :registration, user_id: user.id}
|> Subscriber.changeset(%{email: user.email})
|> Repo.insert(
on_conflict: {:replace, [:user_id, :source, :updated_at]},
conflict_target: :email
)
end
@doc """
Confirms a subscription by email address.
Returns `{:error, :not_found}` when the address is not on the list.
"""
def confirm(email) when is_binary(email) do
case Repo.get_by(Subscriber, email: String.trim(email)) do
nil ->
{:error, :not_found}
%Subscriber{confirmed_at: nil} = subscriber ->
subscriber
|> Ecto.Changeset.change(confirmed_at: DateTime.utc_now(:second))
|> Repo.update()
%Subscriber{} = subscriber ->
{:ok, subscriber}
end
end
@doc """
Confirms the subscription linked to a user whose account was just confirmed.
Registration opt-ins use the account-confirmation email as their proof of
address ownership, so this is called from the account confirmation flow.
"""
def confirm_user_subscription(%User{} = user) do
now = DateTime.utc_now(:second)
Subscriber
|> where([s], s.user_id == ^user.id and is_nil(s.confirmed_at))
|> Repo.update_all(set: [confirmed_at: now, updated_at: now])
end
@doc "Returns the number of confirmed addresses on the mailing list."
def count_confirmed_subscribers do
Subscriber
|> where([s], not is_nil(s.confirmed_at))
|> Repo.aggregate(:count)
end
defp insert_subscription(changeset, email) do
case Repo.insert(changeset) do
{:ok, _subscriber} ->
{:ok, :confirmation_required}
{:error, changeset} ->
# A concurrent request may have inserted the address between the read
# above and this insert; the unique constraint decides, so re-read it.
if email_taken?(changeset) do
case Repo.get_by(Subscriber, email: email) do
%Subscriber{confirmed_at: nil} -> {:ok, :confirmation_required}
%Subscriber{} -> {:ok, :already_subscribed}
nil -> {:error, changeset}
end
else
{:error, changeset}
end
end
end
defp email_taken?(changeset) do
Enum.any?(changeset.errors, fn
{:email, {_message, opts}} -> opts[:constraint] == :unique
_other -> false
end)
end
end
+44
View File
@@ -0,0 +1,44 @@
defmodule Chesstrainer.MailingList.Notifier do
@moduledoc """
Emails for the mailing list.
"""
import Swoosh.Email
alias Chesstrainer.Branding
alias Chesstrainer.Mailer
@doc """
Delivers the confirmation email for a mailing-list subscription.
"""
def deliver_confirmation_instructions(email, url) do
deliver(email, "Confirm your mailing list subscription", """
==============================
Hi #{email},
You asked to receive occasional endgame tips and site news from
#{Branding.name()}. Confirm your subscription by visiting the URL below:
#{url}
If you didn't ask for this, ignore this email and we won't add you.
==============================
""")
end
defp deliver(recipient, subject, body) do
email =
new()
|> to(recipient)
|> from({Branding.name(), Branding.support_email()})
|> subject(subject)
|> text_body(body)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
end
@@ -0,0 +1,35 @@
defmodule Chesstrainer.MailingList.Subscriber do
use Ecto.Schema
import Ecto.Changeset
alias Chesstrainer.Accounts.User
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "mailing_list_subscribers" do
field :email, :string
field :source, Ecto.Enum, values: [:home, :registration], default: :home
field :confirmed_at, :utc_datetime
belongs_to :user, User
timestamps(type: :utc_datetime)
end
@doc """
A changeset for subscribing an email address.
`:source` and `:user_id` are programmatic: the context sets them on the
struct, never from user-supplied params.
"""
def changeset(subscriber, attrs) do
subscriber
|> cast(attrs, [:email])
|> update_change(:email, &String.trim/1)
|> validate_required([:email])
|> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
message: "must have the @ sign and no spaces"
)
|> validate_length(:email, max: 160)
|> unique_constraint(:email)
end
end
@@ -8,6 +8,8 @@ defmodule ChesstrainerWeb.LandingComponents do
"""
use Phoenix.Component
import Phoenix.Controller, only: [get_csrf_token: 0]
alias Chesstrainer.FEN
alias Chesstrainer.Themes
@@ -70,6 +72,43 @@ defmodule ChesstrainerWeb.LandingComponents do
end
end
@doc """
Renders the mailing-list signup band.
The form posts to `POST /mailing-list` and the controller redirects back to
the `#mailing-list` anchor with a flash. Keeping it a plain form means the
landing page needs no LiveView to collect an address.
"""
def mailing_list_signup(assigns) do
~H"""
<section class="mailing-list" id="mailing-list">
<div class="mailing-list-copy">
<span class="section-kicker">Mailing list</span>
<h2>One good endgame idea, now and then.</h2>
<p>
Occasional emails about new puzzles and features. We'll ask you to confirm your address first.
</p>
</div>
<form action="/mailing-list" method="post" id="mailing-list-form" class="mailing-list-form">
<input type="hidden" name="_csrf_token" value={get_csrf_token()} />
<label for="mailing-list-email">Email address</label>
<div class="mailing-list-row">
<input
id="mailing-list-email"
type="email"
name="subscriber[email]"
placeholder="you@example.com"
autocomplete="email"
required
/>
<.pill_button variant={:primary} type="submit">Join the list</.pill_button>
</div>
</form>
</section>
"""
end
@doc """
Renders a static board preview for the landing page.
@@ -0,0 +1,89 @@
defmodule ChesstrainerWeb.MailingListController do
use ChesstrainerWeb, :controller
alias Chesstrainer.MailingList
alias Chesstrainer.MailingList.Notifier
@return_to "/#mailing-list"
@token_salt "mailing_list_confirm"
@token_max_age 7 * 24 * 60 * 60
def create(conn, %{"subscriber" => %{"email" => email}}) when is_binary(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} ->
case send_confirmation(email) do
:ok ->
conn
|> put_flash(:info, "Check your inbox to confirm your subscription.")
|> redirect(to: @return_to)
:error ->
conn
|> put_flash(:error, "We couldn't send the confirmation email. Please try again.")
|> redirect(to: @return_to)
end
{:error, %Ecto.Changeset{}} ->
conn
|> put_flash(:error, "Enter a valid email address.")
|> redirect(to: @return_to)
end
end
def create(conn, _params) do
conn
|> put_flash(:error, "Enter a valid email address.")
|> redirect(to: @return_to)
end
def confirm(conn, %{"token" => token}) do
case Phoenix.Token.verify(
ChesstrainerWeb.Endpoint,
@token_salt,
token,
max_age: @token_max_age
) do
{:ok, email} ->
confirm_subscription(conn, email)
{:error, _reason} ->
conn
|> put_flash(:error, "That confirmation link is invalid or has expired.")
|> redirect(to: @return_to)
end
end
defp confirm_subscription(conn, email) do
case MailingList.confirm(email) do
{:ok, _subscriber} ->
conn
|> put_flash(:info, "Your mailing list subscription is confirmed.")
|> redirect(to: @return_to)
{:error, :not_found} ->
conn
|> put_flash(
:error,
"That address is no longer on the mailing list. Please sign up again."
)
|> redirect(to: @return_to)
end
end
defp send_confirmation(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
end
end
end
@@ -71,6 +71,8 @@
</div>
</section>
<.mailing_list_signup />
<%!-- <section class="progress-banner" id="progress">
<div>
<span class="section-kicker">A calmer way to improve</span>
@@ -24,6 +24,13 @@
We record the puzzles you attempt and whether you solved them, so we can
show your progress and keep the daily puzzle meaningful.
</li>
<li>
<strong>Mailing list email.</strong>
If you join the mailing list — using the form on the home page or the
checkbox when registering — we store your email address and where you
signed up, so we can send you occasional updates. You can ask to be
removed at any time.
</li>
<li>
<strong>Technical data.</strong>
Our hosting and server infrastructure may keep standard request logs
@@ -58,6 +65,7 @@
<li>To create and secure your account and sign you in.</li>
<li>To run the trainer and remember your progress.</li>
<li>To send service emails, such as confirmation and password reset links.</li>
<li>To send occasional endgame tips and site news, if you opted in.</li>
<li>To keep the site available, prevent abuse, and fix faults.</li>
<li>To respond when you ask for help.</li>
</ul>
@@ -2,10 +2,13 @@ defmodule ChesstrainerWeb.UserConfirmationController do
use ChesstrainerWeb, :controller
alias Chesstrainer.Accounts
alias Chesstrainer.MailingList
def edit(conn, %{"token" => token}) do
case Accounts.confirm_user(token) do
{:ok, _user} ->
{:ok, user} ->
MailingList.confirm_user_subscription(user)
conn
|> put_flash(:info, "User confirmed successfully.")
|> redirect(to: ~p"/users/log-in")
@@ -3,6 +3,7 @@ defmodule ChesstrainerWeb.UserLive.Registration do
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.User
alias Chesstrainer.MailingList
@impl true
def render(assigns) do
@@ -56,6 +57,11 @@ defmodule ChesstrainerWeb.UserLive.Registration do
spellcheck="false"
required
/>
<.input
field={@form[:mailing_list]}
type="checkbox"
label="Send me occasional endgame tips and site news by email"
/>
<.button phx-disable-with="Creating account..." variant="primary" class="w-full">
Create an account
@@ -82,6 +88,8 @@ defmodule ChesstrainerWeb.UserLive.Registration do
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.register_user(user_params) do
{:ok, user} ->
if user.mailing_list, do: MailingList.subscribe_user(user)
{:ok, _} =
Accounts.deliver_user_confirmation_instructions(
user,
+2
View File
@@ -23,6 +23,8 @@ defmodule ChesstrainerWeb.Router do
get "/", PageController, :home
get "/privacy", PageController, :privacy
get "/terms-conditions", PageController, :terms_conditions
post "/mailing-list", MailingListController, :create
get "/mailing-list/confirm/:token", MailingListController, :confirm
end
scope "/admin", ChesstrainerWeb do