Add user profile hub with account, settings and data export (#103)

This commit is contained in:
2026-11-06 21:13:37 +01:00
committed by GitHub
parent f5efcde5ca
commit c71f465487
21 changed files with 893 additions and 251 deletions
+10
View File
@@ -34,6 +34,16 @@ h1, h2 { font-family: 'DM Serif Display', serif; font-weight: 400; letter-spacin
h1 { max-width: 590px; font-size: clamp(56px, 6vw, 87px); line-height: .93; }
h1 em { color: var(--color-coral); font-weight: 400; }
.settings-header {
font-size: 3rem;
}
.settings-subtitle {
font-size: 1rem;;
color: var(--color-base-content);
opacity: 0.7;
}
@media (max-width: 650px) {
h1 { font-size: clamp(51px, 15vw, 68px); }
}
+7 -1
View File
@@ -14,7 +14,12 @@
.nav-links a { transition: opacity .2s; }
.nav-links a:hover { opacity: .55; }
.nav-links a.nav-cta:hover { opacity: 1; }
.nav-user { color: var(--color-muted); font-weight: 500; }
.nav-user-menu { position: relative; }
.nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; }
.nav-user-menu summary::-webkit-details-marker { display: none; }
.nav-user-menu summary::after { content: "▾"; font-size: 10px; }
.nav-user-menu-panel { position: absolute; right: 0; top: calc(100% + 14px); z-index: 20; display: grid; gap: 12px; min-width: 170px; padding: 16px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
html[data-theme="dark"] .nav-user-menu-panel { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
.nav-cta, .primary-button, .light-button {
display: inline-flex; align-items: center; justify-content: center; gap: 13px;
border-radius: 999px; font-weight: 600; transition: transform .2s, background .2s;
@@ -37,5 +42,6 @@
.nav-links.open { display: flex; }
.nav-cta { width: 100%; }
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
.nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; }
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
}
+16
View File
@@ -4,6 +4,11 @@
const WRAP = ".nav-wrap";
const TOGGLE = ".menu-button";
const LINKS = ".nav-links";
const USER_MENU = ".nav-user-menu";
const closeUserMenus = () => {
document.querySelectorAll(`${USER_MENU}[open]`).forEach((menu) => menu.removeAttribute("open"));
};
const setOpen = (open) => {
const wrap = document.querySelector(WRAP);
@@ -26,6 +31,16 @@ document.addEventListener("click", (event) => {
return;
}
if (target.closest(`${USER_MENU} a`)) {
closeUserMenus();
setOpen(false);
return;
}
if (!target.closest(USER_MENU)) {
closeUserMenus();
}
if (target.closest(`${LINKS} a`)) {
setOpen(false);
return;
@@ -39,6 +54,7 @@ document.addEventListener("click", (event) => {
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
setOpen(false);
closeUserMenus();
}
});
+36
View File
@@ -70,6 +70,39 @@ defmodule Chesstrainer.Attempts do
|> Repo.one()
end
@doc """
Aggregated attempt totals for `user_id`.
Returns a map with `:attempts`, `:solved`, `:failed` and `:endgames` (the
number of distinct puzzles tried).
"""
def stats_for_user(user_id) do
Attempt
|> where([a], a.user_id == ^user_id)
|> select([a], %{
attempts: count(a.id),
solved: filter(count(a.id), a.outcome == :solved),
failed: filter(count(a.id), a.outcome == :failed),
endgames: count(a.endgame_id, :distinct)
})
|> Repo.one()
end
@doc """
The attempts of `user_id`, newest first, with each endgame preloaded.
Pass `limit: n` to cap the history (the profile page shows a recent window;
exports pass no limit).
"""
def list_attempts_for_user(user_id, opts \\ []) do
Attempt
|> where([a], a.user_id == ^user_id)
|> order_by([a], desc: a.inserted_at)
|> maybe_limit(Keyword.get(opts, :limit))
|> preload(:endgame)
|> Repo.all()
end
@doc """
The distinct endgame ids `user_id` has attempted in the last `days` days.
@@ -87,4 +120,7 @@ defmodule Chesstrainer.Attempts do
end
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
defp maybe_limit(query, nil), do: query
defp maybe_limit(query, limit) when is_integer(limit), do: limit(query, ^limit)
end
+21 -22
View File
@@ -67,6 +67,7 @@ defmodule ChesstrainerWeb.Layouts do
assigns
|> assign(:nav_links, nav_links(assigns.current_scope))
|> assign(:start_href, start_href(assigns.current_scope))
|> assign(:user, signed_in_user(assigns.current_scope))
~H"""
<header>
@@ -92,11 +93,22 @@ defmodule ChesstrainerWeb.Layouts do
<div class="nav-links" id="nav-links">
<%= for link <- @nav_links do %>
<%= if link[:kind] == :text do %>
<span class="nav-user">{link.label}</span>
<% else %>
<.link href={link.href} method={link[:method]}>{link.label}</.link>
<% end %>
<.link href={link.href}>{link.label}</.link>
<% end %>
<%= if @user do %>
<details class="nav-user-menu">
<summary>{@user.username}</summary>
<div class="nav-user-menu-panel">
<.link navigate={~p"/users/profile"}>Account</.link>
<.link navigate={~p"/users/profile/settings"}>Settings</.link>
<.link navigate={~p"/users/profile/data"}>Data</.link>
<.link href={~p"/users/log-out"} method="delete">Log out</.link>
</div>
</details>
<% else %>
<.link href={~p"/users/log-in"}>Log in</.link>
<.link href={~p"/users/register"}>Register</.link>
<% end %>
<.pill_button variant={:nav} href={@start_href}>
@@ -126,25 +138,12 @@ defmodule ChesstrainerWeb.Layouts do
[]
end
account =
case scope do
%{user: %{username: username}} ->
[
%{label: "Settings", href: ~p"/users/settings"},
%{label: "Log out", href: ~p"/users/log-out", method: "delete"},
%{label: username, kind: :text}
]
_ ->
[
%{label: "Log in", href: ~p"/users/log-in"},
%{label: "Register", href: ~p"/users/register"}
]
end
marketing ++ admin ++ account
marketing ++ admin
end
defp signed_in_user(%{user: %{username: _} = user}), do: user
defp signed_in_user(_scope), do: nil
defp admin?(%{user: %{role: role}}), do: Role.admin?(role)
defp admin?(_scope), do: false
@@ -95,7 +95,7 @@ defmodule ChesstrainerWeb.PlayComponents do
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
</.button>
<.button
:if={@session and @status in [:solved, :failed] and not @reviewing}
:if={@session and @status in [:solved, :failed]}
id="next-puzzle-button"
phx-click="next_puzzle"
variant="primary"
@@ -0,0 +1,104 @@
defmodule ChesstrainerWeb.UserDataController do
use ChesstrainerWeb, :controller
alias Chesstrainer.Attempts
@user_columns ~w(user_username user_email user_rating user_rating_deviation user_plan user_joined_at)
@attempt_columns ~w(played_at puzzle public_code color result outcome rated_at)
@columns @user_columns ++ @attempt_columns
def export(conn, %{"format" => format}) when format in ["csv", "json"] do
user = conn.assigns.current_scope.user
attempts = Attempts.list_attempts_for_user(user.id)
filename = "lucid-chess-data-#{Date.utc_today()}.#{format}"
conn
|> put_resp_content_type(content_type(format))
|> put_resp_header("content-disposition", ~s(attachment; filename="#{filename}"))
|> send_resp(200, body(format, user, attempts))
end
def export(conn, _params), do: send_resp(conn, 404, "Unknown export format")
defp body("csv", user, attempts), do: to_csv(user, attempts)
defp body("json", user, attempts) do
%{user: user_map(user), attempts: Enum.map(attempts, &attempt_map/1)}
|> Jason.encode!(pretty: true)
end
defp user_map(user) do
%{
username: user.username,
email: user.email,
rating: user.rating,
rating_deviation: user.rating_deviation,
plan: user.plan,
joined_at: DateTime.to_iso8601(user.inserted_at)
}
end
defp attempt_map(attempt) do
%{
played_at: DateTime.to_iso8601(attempt.inserted_at),
puzzle: attempt.endgame.key,
public_code: attempt.endgame.public_code,
color: attempt.endgame.color,
result: attempt.endgame.result,
outcome: attempt.outcome,
rated_at: attempt.rated_at && DateTime.to_iso8601(attempt.rated_at)
}
end
defp to_csv(user, attempts) do
rows =
case attempts do
[] -> [user_row(user) ++ empty_attempt_row()]
attempts -> Enum.map(attempts, &(user_row(user) ++ attempt_row(&1)))
end
[@columns | rows]
|> Enum.map_join("\n", fn row -> Enum.map_join(row, ",", &csv_field/1) end)
|> Kernel.<>("\n")
end
defp user_row(user) do
[
user.username,
user.email,
user.rating,
user.rating_deviation,
user.plan,
DateTime.to_iso8601(user.inserted_at)
]
end
defp attempt_row(attempt) do
[
DateTime.to_iso8601(attempt.inserted_at),
attempt.endgame.key,
attempt.endgame.public_code,
attempt.endgame.color,
attempt.endgame.result,
attempt.outcome,
attempt.rated_at && DateTime.to_iso8601(attempt.rated_at)
]
end
defp empty_attempt_row, do: List.duplicate(nil, length(@attempt_columns))
defp csv_field(nil), do: ""
defp csv_field(value) do
value = to_string(value)
if String.contains?(value, [",", "\"", "\n"]) do
~s("#{String.replace(value, "\"", "\"\"")}")
else
value
end
end
defp content_type("csv"), do: "text/csv"
defp content_type("json"), do: "application/json"
end
@@ -50,7 +50,7 @@ defmodule ChesstrainerWeb.UserSessionController do
user = Accounts.get_user_by_login_and_password(login, password)
conn
|> put_session(:user_return_to, ~p"/users/settings")
|> put_session(:user_return_to, ~p"/users/profile")
|> put_flash(:info, "Password updated successfully!")
|> UserAuth.log_in_user(user, user_params)
end
@@ -24,7 +24,7 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
phx-submit="endgame_search"
class="mb-6 flex items-end gap-2"
>
<div class="flex-1">
<div class="flex-1 [&>div]:mb-0">
<.input
field={@search_form[:query]}
type="text"
@@ -0,0 +1,394 @@
defmodule ChesstrainerWeb.UserLive.Profile do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
@recent_attempts 25
@tabs [
%{id: :account, label: "Account", path: "/users/profile"},
%{id: :settings, label: "Settings", path: "/users/profile/settings"},
%{id: :data, label: "Data", path: "/users/profile/data"}
]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} current_scope={@current_scope}>
<.header>
Profile
<:subtitle>Manage your account, site settings and training data.</:subtitle>
</.header>
<nav id="profile-tabs" class="flex gap-1 border-b border-base-300" aria-label="Profile sections">
<.link
:for={tab <- @tabs}
id={"profile-tab-#{tab.id}"}
patch={tab.path}
class={[
"border-b-2 -mb-px px-3 py-2 text-sm font-semibold",
if(@live_action == tab.id,
do: "border-primary text-primary",
else: "border-transparent text-base-content/60 hover:text-base-content"
)
]}
aria-current={@live_action == tab.id && "page"}
>
{tab.label}
</.link>
</nav>
<%= case @live_action do %>
<% :account -> %>
<section id="profile-summary" class="space-y-2 rounded-lg border border-base-300 p-4">
<p class="text-sm text-base-content/60">Signed in as</p>
<p class="text-lg font-semibold">{@current_scope.user.username}</p>
<p class="text-sm">{@current_scope.user.email}</p>
<p class="text-sm text-base-content/60">
Rating:
<span class="font-semibold text-base-content">{round(@current_scope.user.rating)}</span>
</p>
</section>
<section id="email-settings" class="space-y-4">
<h2 class="settings-header">Change email</h2>
<p class="settings-subtitle">We will send a confirmation link to the new address.</p>
<.form
for={@email_form}
id="email_form"
phx-submit="update_email"
phx-change="validate_email"
>
<.input
field={@email_form[:email]}
type="email"
label="Email"
autocomplete="username"
spellcheck="false"
required
/>
<.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
</.form>
</section>
<hr class="my-6 border-base-200" />
<section id="password-settings" class="space-y-4">
<h2 class="settings-header">Change password</h2>
<p class="settings-subtitle">Choose a new password for this account.</p>
<.form
for={@password_form}
id="password_form"
action={~p"/users/update-password"}
method="post"
phx-change="validate_password"
phx-submit="update_password"
phx-trigger-action={@trigger_submit}
>
<input
name={@password_form[:email].name}
type="hidden"
id="hidden_user_email"
spellcheck="false"
value={@current_email}
/>
<.input
field={@password_form[:password]}
type="password"
label="New password"
autocomplete="new-password"
spellcheck="false"
required
/>
<.input
field={@password_form[:password_confirmation]}
type="password"
label="Confirm new password"
autocomplete="new-password"
spellcheck="false"
/>
<.button variant="primary" phx-disable-with="Saving...">
Save Password
</.button>
</.form>
</section>
<hr class="my-6 border-base-200" />
<section id="delete_account" class="space-y-4">
<h2 class="settings-header">Delete account</h2>
<p class="settings-subtitle">This action is permanent and cannot be undone.</p>
<p class="text-sm text-base-content/70">
Deleting your account permanently removes your profile, rating and training history.
Nothing can be recovered.
</p>
<.button
id="delete_account_button"
variant="danger"
phx-click="delete_account"
data-confirm="This permanently deletes your account and all of your data. Nothing can be recovered. Are you sure?"
>
Delete my account
</.button>
</section>
<% :settings -> %>
<%!-- Keep section for when board themes are added etc --%>
<%!-- <section id="appearance-settings" class="space-y-4 rounded-lg border border-base-300 p-4">
<.header>
Appearance
<:subtitle>Choose how the site looks on this device.</:subtitle>
</.header>
<Layouts.colour_mode_toggle />
</section> --%>
<section id="membership-settings" class="space-y-2 rounded-lg border border-base-300 p-4">
<h2 class="settings-header">Membership</h2>
<p class="settings-subtitle">Your current plan.</p>
<p class="text-sm">
You are on the <strong>{plan_label(@current_scope)}</strong> plan.
</p>
<p class="text-sm text-base-content/70">
Premium membership is not available yet. When it arrives it will add session
analytics, weak-theme reports and the full puzzle search.
</p>
</section>
<p id="settings-empty-state" class="text-sm text-base-content/60">
More site settings will appear here as they become available.
</p>
<% :data -> %>
<section id="training-stats" class="space-y-4 rounded-lg border border-base-300 p-4">
<h2 class="settings-header">Progress</h2>
<p class="settings-subtitle">Your score and solve history across every puzzle.</p>
<dl class="grid grid-cols-2 gap-3 sm:grid-cols-4">
<.stat label="Rating" value={round(@current_scope.user.rating)} />
<.stat label="Attempts" value={@stats.attempts} />
<.stat label="Solved" value={@stats.solved} />
<.stat label="Solve rate" value={"#{@stats.solve_rate}%"} />
</dl>
</section>
<section id="data-export" class="space-y-4 rounded-lg border border-base-300 p-4">
<h2 class="settings-header">Export your data</h2>
<p class="settings-subtitle">Download your profile details and every recorded attempt.</p>
<div class="flex flex-wrap gap-3">
<.button id="export-csv" href={~p"/users/profile/export/csv"}>
<.icon name="hero-arrow-down-tray" class="w-4 h-4" /> Download CSV
</.button>
<.button id="export-json" href={~p"/users/profile/export/json"}>
<.icon name="hero-arrow-down-tray" class="w-4 h-4" /> Download JSON
</.button>
</div>
</section>
<section id="attempt-history" class="space-y-4 rounded-lg border border-base-300 p-4">
<h2 class="settings-header">Recent attempts</h2>
<p class="settings-subtitle">The last {@recent_attempts} puzzles you finished.</p>
<table :if={@attempts != []} class="w-full text-left text-sm">
<thead class="border-b border-base-300 text-base-content/60">
<tr>
<th class="py-2">Played</th>
<th class="py-2">Puzzle</th>
<th class="py-2">Outcome</th>
</tr>
</thead>
<tbody>
<tr
:for={attempt <- @attempts}
id={"attempt-#{attempt.id}"}
class="border-b border-base-200"
>
<td class="py-2">{Calendar.strftime(attempt.inserted_at, "%d %b %Y")}</td>
<td class="py-2">
<.link
navigate={~p"/endgames/#{attempt.endgame.public_code}/play"}
class="font-semibold"
>
{attempt.endgame.key}
</.link>
</td>
<td class="py-2 capitalize">{attempt.outcome}</td>
</tr>
</tbody>
</table>
<p :if={@attempts == []} class="text-sm text-base-content/70">
No attempts yet. Play a puzzle to start building your history.
</p>
</section>
<section id="premium-data" class="space-y-2 rounded-lg border border-base-300 p-4">
<h2 class="settings-header">Premium Insights</h2>
<p class="settings-subtitle">Deeper training analytics, once Premium is available.</p>
<ul class="list-inside list-disc text-sm text-base-content/70">
<li>Session-by-session performance</li>
<li>Failed puzzles and weak themes</li>
</ul>
</section>
<% end %>
</Layouts.app>
"""
end
@impl true
def mount(%{"token" => token}, _session, socket) do
socket =
case Accounts.update_user_email(socket.assigns.current_scope.user, token) do
{:ok, _user} ->
put_flash(socket, :info, "Email changed successfully.")
{:error, _} ->
put_flash(socket, :error, "Email change link is invalid or it has expired.")
end
{:ok, push_navigate(socket, to: ~p"/users/profile")}
end
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:page_title, "Profile")
|> assign(:tabs, @tabs)
|> assign(:recent_attempts, @recent_attempts)}
end
@impl true
def handle_params(_params, _uri, socket) do
socket = load_section(socket)
if socket.assigns.live_action == :account and not sudo_mode?(socket) do
{:noreply,
socket
|> put_flash(:error, "You must re-authenticate to access this page.")
|> redirect(to: ~p"/users/log-in")}
else
{:noreply, socket}
end
end
@impl true
def handle_event("validate_email", params, socket) do
%{"user" => user_params} = params
email_form =
socket.assigns.current_scope.user
|> Accounts.change_user_email(user_params, validate_unique: false)
|> Map.put(:action, :validate)
|> to_form()
{:noreply, assign(socket, email_form: email_form)}
end
def handle_event("update_email", params, socket) do
%{"user" => user_params} = params
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
case Accounts.change_user_email(user, user_params) do
%{valid?: true} = changeset ->
Accounts.deliver_user_update_email_instructions(
Ecto.Changeset.apply_action!(changeset, :insert),
user.email,
&url(~p"/users/settings/confirm-email/#{&1}")
)
info = "A link to confirm your email change has been sent to the new address."
{:noreply, socket |> put_flash(:info, info)}
changeset ->
{:noreply, assign(socket, :email_form, to_form(changeset, action: :insert))}
end
end
def handle_event("validate_password", params, socket) do
%{"user" => user_params} = params
password_form =
socket.assigns.current_scope.user
|> Accounts.change_user_password(user_params, hash_password: false)
|> Map.put(:action, :validate)
|> to_form()
{:noreply, assign(socket, password_form: password_form)}
end
def handle_event("update_password", params, socket) do
%{"user" => user_params} = params
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
case Accounts.change_user_password(user, user_params) do
%{valid?: true} = changeset ->
{:noreply, assign(socket, trigger_submit: true, password_form: to_form(changeset))}
changeset ->
{:noreply, assign(socket, password_form: to_form(changeset, action: :insert))}
end
end
def handle_event("delete_account", _params, socket) do
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
{:ok, _user} = Accounts.delete_user(user)
{:noreply,
socket
|> put_flash(:info, "Your account has been deleted.")
|> redirect(to: ~p"/")}
end
defp load_section(socket) do
case socket.assigns.live_action do
:account -> assign_account(socket)
:data -> assign_data(socket)
_ -> socket
end
end
defp assign_account(socket) do
user = socket.assigns.current_scope.user
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
password_changeset = Accounts.change_user_password(user, %{}, hash_password: false)
socket
|> assign(:current_email, user.email)
|> assign(:email_form, to_form(email_changeset))
|> assign(:password_form, to_form(password_changeset))
|> assign(:trigger_submit, false)
end
defp assign_data(socket) do
user = socket.assigns.current_scope.user
stats = Attempts.stats_for_user(user.id)
solve_rate = if stats.attempts > 0, do: round(stats.solved * 100 / stats.attempts), else: 0
socket
|> assign(:stats, Map.put(stats, :solve_rate, solve_rate))
|> assign(:attempts, Attempts.list_attempts_for_user(user.id, limit: @recent_attempts))
end
defp sudo_mode?(socket) do
Accounts.sudo_mode?(socket.assigns.current_scope.user, -10)
end
defp plan_label(scope), do: if(Scope.premium?(scope), do: "Premium", else: "Free")
attr :label, :string, required: true
attr :value, :any, required: true
defp stat(assigns) do
~H"""
<div class="rounded-lg border border-base-300 p-3">
<dt class="text-xs uppercase tracking-wide text-base-content/60">{@label}</dt>
<dd class="text-xl font-semibold">{@value}</dd>
</div>
"""
end
end
@@ -1,195 +0,0 @@
defmodule ChesstrainerWeb.UserLive.Settings do
use ChesstrainerWeb, :live_view
on_mount {ChesstrainerWeb.UserAuth, :require_sudo_mode}
alias Chesstrainer.Accounts
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="text-center">
<.header>
Account Settings
<:subtitle>Manage your account email address and password settings</:subtitle>
</.header>
</div>
<.form for={@email_form} id="email_form" phx-submit="update_email" phx-change="validate_email">
<.input
field={@email_form[:email]}
type="email"
label="Email"
autocomplete="username"
spellcheck="false"
required
/>
<.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
</.form>
<hr class="my-6 border-base-200" />
<.form
for={@password_form}
id="password_form"
action={~p"/users/update-password"}
method="post"
phx-change="validate_password"
phx-submit="update_password"
phx-trigger-action={@trigger_submit}
>
<input
name={@password_form[:email].name}
type="hidden"
id="hidden_user_email"
spellcheck="false"
value={@current_email}
/>
<.input
field={@password_form[:password]}
type="password"
label="New password"
autocomplete="new-password"
spellcheck="false"
required
/>
<.input
field={@password_form[:password_confirmation]}
type="password"
label="Confirm new password"
autocomplete="new-password"
spellcheck="false"
/>
<.button variant="primary" phx-disable-with="Saving...">
Save Password
</.button>
</.form>
<hr class="my-6 border-base-200" />
<section id="delete_account" class="space-y-4">
<.header>
Delete account
<:subtitle>This action is permanent and cannot be undone.</:subtitle>
</.header>
<p class="text-sm text-base-content/70">
Deleting your account permanently removes your profile, rating and training history.
Nothing can be recovered.
</p>
<.button
id="delete_account_button"
variant="danger"
phx-click="delete_account"
data-confirm="This permanently deletes your account and all of your data. Nothing can be recovered. Are you sure?"
>
Delete my account
</.button>
</section>
</Layouts.app>
"""
end
@impl true
def mount(%{"token" => token}, _session, socket) do
socket =
case Accounts.update_user_email(socket.assigns.current_scope.user, token) do
{:ok, _user} ->
put_flash(socket, :info, "Email changed successfully.")
{:error, _} ->
put_flash(socket, :error, "Email change link is invalid or it has expired.")
end
{:ok, push_navigate(socket, to: ~p"/users/settings")}
end
def mount(_params, _session, socket) do
user = socket.assigns.current_scope.user
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
password_changeset = Accounts.change_user_password(user, %{}, hash_password: false)
socket =
socket
|> assign(:current_email, user.email)
|> assign(:email_form, to_form(email_changeset))
|> assign(:password_form, to_form(password_changeset))
|> assign(:trigger_submit, false)
{:ok, socket}
end
@impl true
def handle_event("validate_email", params, socket) do
%{"user" => user_params} = params
email_form =
socket.assigns.current_scope.user
|> Accounts.change_user_email(user_params, validate_unique: false)
|> Map.put(:action, :validate)
|> to_form()
{:noreply, assign(socket, email_form: email_form)}
end
def handle_event("update_email", params, socket) do
%{"user" => user_params} = params
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
case Accounts.change_user_email(user, user_params) do
%{valid?: true} = changeset ->
Accounts.deliver_user_update_email_instructions(
Ecto.Changeset.apply_action!(changeset, :insert),
user.email,
&url(~p"/users/settings/confirm-email/#{&1}")
)
info = "A link to confirm your email change has been sent to the new address."
{:noreply, socket |> put_flash(:info, info)}
changeset ->
{:noreply, assign(socket, :email_form, to_form(changeset, action: :insert))}
end
end
def handle_event("validate_password", params, socket) do
%{"user" => user_params} = params
password_form =
socket.assigns.current_scope.user
|> Accounts.change_user_password(user_params, hash_password: false)
|> Map.put(:action, :validate)
|> to_form()
{:noreply, assign(socket, password_form: password_form)}
end
def handle_event("update_password", params, socket) do
%{"user" => user_params} = params
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
case Accounts.change_user_password(user, user_params) do
%{valid?: true} = changeset ->
{:noreply, assign(socket, trigger_submit: true, password_form: to_form(changeset))}
changeset ->
{:noreply, assign(socket, password_form: to_form(changeset, action: :insert))}
end
end
def handle_event("delete_account", _params, socket) do
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
{:ok, _user} = Accounts.delete_user(user)
{:noreply,
socket
|> put_flash(:info, "Your account has been deleted.")
|> redirect(to: ~p"/")}
end
end
+7 -2
View File
@@ -68,11 +68,16 @@ defmodule ChesstrainerWeb.Router do
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
live "/endgames", EndgameLive.PlayerIndex, :index
live "/train", EndgameLive.Train, :train
live "/users/settings", UserLive.Settings, :edit
live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email
live "/users/profile", UserLive.Profile, :account
live "/users/profile/settings", UserLive.Profile, :settings
live "/users/profile/data", UserLive.Profile, :data
# Legacy settings URL; keep old links and emails working.
live "/users/settings", UserLive.Profile, :account
live "/users/settings/confirm-email/:token", UserLive.Profile, :confirm_email
end
post "/users/update-password", UserSessionController, :update_password
get "/users/profile/export/:format", UserDataController, :export
end
scope "/", ChesstrainerWeb do
+2 -2
View File
@@ -283,9 +283,9 @@ defmodule ChesstrainerWeb.UserAuth do
end
@doc "Returns the path to redirect to after log in."
# the user was already logged in, redirect to settings
# the user was already logged in, redirect to their profile
def signed_in_path(%Plug.Conn{assigns: %{current_scope: %Scope{user: %Accounts.User{}}}}) do
~p"/users/settings"
~p"/users/profile"
end
def signed_in_path(_), do: ~p"/"
+59
View File
@@ -59,6 +59,65 @@ defmodule Chesstrainer.AttemptsTest do
end
end
describe "stats_for_user/1" do
test "summarises attempts, outcomes and distinct puzzles" do
user = user_fixture()
first = endgame_fixture()
second = endgame_fixture()
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), first, :solved)
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), first, :failed)
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), second, :solved)
assert %{attempts: 3, solved: 2, failed: 1, endgames: 2} =
Attempts.stats_for_user(user.id)
end
test "returns zeroes for a user with no attempts" do
user = user_fixture()
assert %{attempts: 0, solved: 0, failed: 0, endgames: 0} =
Attempts.stats_for_user(user.id)
end
end
describe "list_attempts_for_user/2" do
test "returns the user's attempts newest first with endgames preloaded" do
user = user_fixture()
first = endgame_fixture(fen: "8/8/3k4/8/8/3K1Q2/8/8 w - - 0 1")
second = endgame_fixture(fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
{:ok, first_attempt} = Attempts.record_attempt(Scope.for_user(user), first, :solved)
{:ok, second_attempt} = Attempts.record_attempt(Scope.for_user(user), second, :failed)
# Attempts within the same second would otherwise tie on `inserted_at`.
Repo.update_all(from(a in Attempt, where: a.id == ^first_attempt.id),
set: [inserted_at: ~N[2026-01-01 00:00:00]]
)
Repo.update_all(from(a in Attempt, where: a.id == ^second_attempt.id),
set: [inserted_at: ~N[2026-01-02 00:00:00]]
)
attempts = Attempts.list_attempts_for_user(user.id)
assert Enum.map(attempts, & &1.id) == [second_attempt.id, first_attempt.id]
assert Enum.all?(attempts, &match?(%Chesstrainer.Endgames.Endgame{}, &1.endgame))
end
test "excludes other users and honours the limit" do
user = user_fixture()
other = user_fixture()
endgame = endgame_fixture()
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :failed)
{:ok, _} = Attempts.record_attempt(Scope.for_user(other), endgame, :solved)
assert length(Attempts.list_attempts_for_user(user.id)) == 2
assert length(Attempts.list_attempts_for_user(user.id, limit: 1)) == 1
end
end
describe "cascade" do
test "deleting a user removes their attempts" do
user = user_fixture()
@@ -3,8 +3,33 @@ defmodule ChesstrainerWeb.LayoutsTest do
import Phoenix.LiveViewTest
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Accounts.User
alias ChesstrainerWeb.Layouts
describe "navbar/1" do
test "signed-in users get a profile menu" do
scope = Scope.for_user(%User{username: "alice"})
html = render_component(&Layouts.navbar/1, %{current_scope: scope})
assert html =~ "alice"
assert html =~ ~s(class="nav-user-menu")
assert html =~ ~p"/users/profile"
assert html =~ ~p"/users/profile/settings"
assert html =~ ~p"/users/profile/data"
assert html =~ ~p"/users/log-out"
end
test "guests get log in and register links" do
html = render_component(&Layouts.navbar/1, %{current_scope: nil})
assert html =~ ~p"/users/log-in"
assert html =~ ~p"/users/register"
refute html =~ ~s(class="nav-user-menu")
end
end
describe "colour_mode_toggle/1" do
test "renders all three modes as a labelled radiogroup" do
html = render_component(&Layouts.colour_mode_toggle/1, %{})
@@ -174,17 +174,17 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert html =~ ~p"/users/log-in"
assert html =~ ~p"/users/register"
refute html =~ ~p"/users/settings"
refute html =~ ~p"/users/profile"
end
test "signed-in navbar links to settings and log out", %{conn: conn} do
test "signed-in navbar links to the profile and log out", %{conn: conn} do
html =
conn
|> log_in_user(user_fixture())
|> get(~p"/")
|> html_response(200)
assert html =~ ~p"/users/settings"
assert html =~ ~p"/users/profile"
assert html =~ ~p"/users/log-out"
refute html =~ ~p"/users/register"
end
@@ -0,0 +1,111 @@
defmodule ChesstrainerWeb.UserDataControllerTest do
use ChesstrainerWeb.ConnCase, async: true
import Chesstrainer.AccountsFixtures
import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
setup %{conn: conn} do
user = user_fixture()
endgame = endgame_fixture()
{:ok, _attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
%{conn: log_in_user(conn, user), user: user, endgame: endgame}
end
test "redirects anonymous visitors to log in" do
conn = build_conn() |> get(~p"/users/profile/export/csv")
assert redirected_to(conn) == ~p"/users/log-in"
end
test "downloads the user details and attempts as CSV", %{
conn: conn,
user: user,
endgame: endgame
} do
conn = get(conn, ~p"/users/profile/export/csv")
assert response(conn, 200) =~
"user_username,user_email,user_rating,user_rating_deviation,user_plan,user_joined_at," <>
"played_at,puzzle,public_code,color,result,outcome,rated_at"
assert response(conn, 200) =~ user.username
assert response(conn, 200) =~ user.email
assert response(conn, 200) =~ to_string(user.rating)
assert response(conn, 200) =~ endgame.key
assert response(conn, 200) =~ "solved"
assert get_resp_header(conn, "content-type") == ["text/csv; charset=utf-8"]
assert get_resp_header(conn, "content-disposition") == [
~s(attachment; filename="lucid-chess-data-#{Date.utc_today()}.csv")
]
end
test "downloads the user details and attempts as JSON", %{
conn: conn,
user: user,
endgame: endgame
} do
conn = get(conn, ~p"/users/profile/export/json")
body = Jason.decode!(response(conn, 200))
assert %{
"user" => %{
"username" => username,
"email" => email,
"rating" => 1500.0,
"rating_deviation" => 350.0,
"plan" => "free",
"joined_at" => joined_at
},
"attempts" => [
%{
"puzzle" => puzzle,
"public_code" => public_code,
"color" => "white",
"result" => "win",
"outcome" => "solved",
"rated_at" => nil
}
]
} = body
assert username == user.username
assert email == user.email
assert is_binary(joined_at)
assert puzzle == endgame.key
assert public_code == endgame.public_code
assert get_resp_header(conn, "content-type") == ["application/json; charset=utf-8"]
end
test "includes user details when there are no attempts", %{conn: conn} do
user = user_fixture()
conn = log_in_user(conn, user) |> get(~p"/users/profile/export/csv")
[header, row] =
conn
|> response(200)
|> String.trim_trailing("\n")
|> String.split("\n")
assert header =~ "user_username"
assert row =~ user.username
assert row =~ user.email
end
test "only exports the signed-in user's attempts", %{conn: conn} do
other = user_fixture()
other_endgame = endgame_fixture(fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
{:ok, _} = Attempts.record_attempt(Scope.for_user(other), other_endgame, :failed)
body = conn |> get(~p"/users/profile/export/json") |> response(200)
refute body =~ other_endgame.public_code
end
end
@@ -22,7 +22,7 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
conn = get(conn, ~p"/")
response = html_response(conn, 200)
assert response =~ user.username
assert response =~ ~p"/users/settings"
assert response =~ ~p"/users/profile"
assert response =~ ~p"/users/log-out"
end
@@ -161,6 +161,22 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
assert Enum.any?(endgames, &(&1.id == second.id))
end
test "keeps next puzzle available while reviewing", %{conn: conn} do
{view, endgames} = start_medium_session(conn, 2)
first = :sys.get_state(view.pid).socket.assigns.endgame
solve_current(view)
view |> element("button", "Review") |> render_click()
assert has_element?(view, "#next-puzzle-button")
view |> element("#next-puzzle-button") |> render_click()
second = :sys.get_state(view.pid).socket.assigns.endgame
assert second.id != first.id
assert Enum.any?(endgames, &(&1.id == second.id))
refute :sys.get_state(view.pid).socket.assigns.reviewing
end
test "a retry does not count toward the average again", %{conn: conn} do
{view, [_endgame]} = start_medium_session(conn, 1)
@@ -1,23 +1,79 @@
defmodule ChesstrainerWeb.UserLive.SettingsTest do
defmodule ChesstrainerWeb.UserLive.ProfileTest do
use ChesstrainerWeb.ConnCase, async: true
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
import Chesstrainer.EndgamesFixtures
describe "Settings page" do
test "renders settings page", %{conn: conn} do
describe "profile sections" do
setup %{conn: conn} do
user = user_fixture()
%{conn: log_in_user(conn, user), user: user}
end
test "links to the account, settings and data tabs", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/users/profile")
assert has_element?(view, "#profile-tabs")
assert has_element?(view, ~s{a#profile-tab-account[href="/users/profile"]})
assert has_element?(view, ~s{a#profile-tab-settings[href="/users/profile/settings"]})
assert has_element?(view, ~s{a#profile-tab-data[href="/users/profile/data"]})
end
test "settings tab shows the current plan", %{conn: conn} do
{:ok, view, html} = live(conn, ~p"/users/profile/settings")
assert has_element?(view, "#membership-settings")
assert html =~ "Free"
end
test "data tab shows progress, export links and recent attempts", %{conn: conn, user: user} do
endgame = endgame_fixture()
{:ok, _attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
{:ok, view, html} = live(conn, ~p"/users/profile/data")
assert has_element?(view, "#training-stats")
assert html =~ "100%"
assert html =~ endgame.key
assert has_element?(view, ~s{a#export-csv[href="/users/profile/export/csv"]})
assert has_element?(view, ~s{a#export-json[href="/users/profile/export/json"]})
end
test "data tab shows an empty state without attempts", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/users/profile/data")
assert render(view) =~ "No attempts yet"
end
test "data tab does not require sudo mode", %{conn: conn, user: user} do
conn =
log_in_user(conn, user,
token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
)
{:ok, view, _html} = live(conn, ~p"/users/profile/data")
assert has_element?(view, "#training-stats")
end
end
describe "Account tab" do
test "renders the account forms", %{conn: conn} do
{:ok, _lv, html} =
conn
|> log_in_user(user_fixture())
|> live(~p"/users/settings")
|> live(~p"/users/profile")
assert html =~ "Change Email"
assert html =~ "Save Password"
end
test "redirects if user is not logged in", %{conn: conn} do
assert {:error, redirect} = live(conn, ~p"/users/settings")
assert {:error, redirect} = live(conn, ~p"/users/profile")
assert {:redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/log-in"
@@ -30,7 +86,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|> log_in_user(user_fixture(),
token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
)
|> live(~p"/users/settings")
|> live(~p"/users/profile")
|> follow_redirect(conn, ~p"/users/log-in")
assert conn.resp_body =~ "You must re-authenticate to access this page."
@@ -46,7 +102,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
test "updates the user email", %{conn: conn, user: user} do
new_email = unique_user_email()
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
result =
lv
@@ -60,7 +116,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "renders errors with invalid data (phx-change)", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
result =
lv
@@ -75,7 +131,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "renders errors with invalid data (phx-submit)", %{conn: conn, user: user} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
result =
lv
@@ -98,7 +154,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
test "updates the user password", %{conn: conn, user: user} do
new_password = valid_user_password()
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
form =
form(lv, "#password_form", %{
@@ -113,7 +169,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
new_password_conn = follow_trigger_action(form, conn)
assert redirected_to(new_password_conn) == ~p"/users/settings"
assert redirected_to(new_password_conn) == ~p"/users/profile"
assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token)
@@ -124,7 +180,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "renders errors with invalid data (phx-change)", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
result =
lv
@@ -142,7 +198,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "renders errors with invalid data (phx-submit)", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
result =
lv
@@ -167,7 +223,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "renders the permanent deletion warning", %{conn: conn} do
{:ok, _lv, html} = live(conn, ~p"/users/settings")
{:ok, _lv, html} = live(conn, ~p"/users/profile")
assert html =~ "Delete account"
assert html =~ "permanent and cannot be undone"
@@ -175,7 +231,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "deletes the user and redirects home", %{conn: conn, user: user} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
assert {:error, {:redirect, %{to: "/"}}} =
result = lv |> element("#delete_account_button") |> render_click()
@@ -187,11 +243,11 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
end
test "logs the deleted user out", %{conn: conn, user: user} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
{:ok, lv, _html} = live(conn, ~p"/users/profile")
lv |> element("#delete_account_button") |> render_click()
assert {:error, redirect} = live(conn, ~p"/users/settings")
assert {:error, redirect} = live(conn, ~p"/users/profile")
assert {:redirect, %{to: path}} = redirect
assert path == ~p"/users/log-in"
refute Accounts.get_user_by_email(user.email)
@@ -215,7 +271,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/settings"
assert path == ~p"/users/profile"
assert %{"info" => message} = flash
assert message == "Email changed successfully."
refute Accounts.get_user_by_email(user.email)
@@ -224,7 +280,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
# use confirm token again
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/settings"
assert path == ~p"/users/profile"
assert %{"error" => message} = flash
assert message == "Email change link is invalid or it has expired."
end
@@ -232,7 +288,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
test "does not update email with invalid token", %{conn: conn, user: user} do
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/oops")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/settings"
assert path == ~p"/users/profile"
assert %{"error" => message} = flash
assert message == "Email change link is invalid or it has expired."
assert Accounts.get_user_by_email(user.email)
+2 -2
View File
@@ -74,13 +74,13 @@ defmodule ChesstrainerWeb.UserAuthTest do
assert max_age == @remember_me_cookie_max_age
end
test "redirects to settings when user is already logged in", %{conn: conn, user: user} do
test "redirects to the profile when user is already logged in", %{conn: conn, user: user} do
conn =
conn
|> assign(:current_scope, Scope.for_user(user))
|> UserAuth.log_in_user(user)
assert redirected_to(conn) == ~p"/users/settings"
assert redirected_to(conn) == ~p"/users/profile"
end
test "writes a cookie if remember_me was set in previous session", %{conn: conn, user: user} do