Admin panel, login throttling, and Cloudflare edge hardening (#150)

* Document the remote shell for production user management

* add sitemap to footer links

* remove border under theme selection

* Add admin theme and user management (#144)

Add /admin/themes CRUD and /admin/users list/detail with role and plan editing, guarded by a shared Policy module. Include last-super-admin and self-role protections plus structured id-only admin logs.

Also add admin invitations, confirmation resends and password-reset emails, which work in development through the Swoosh mailbox before SES is configured.

* Rate-limit password logins and emit auth events (#142)

Add a two-bucket login throttle (5 failures per login, 10 per IP in a 15-minute window) and a shared client-address helper for controllers and LiveViews. Blocked attempts skip the database and bcrypt.

Log auth.login.failed and auth.login.throttled warnings with boot-scoped HMAC addresses only, and stop repeated confirmation emails on unconfirmed login attempts.

* Harden the production login edge for Cloudflare

Document the layered login defence: the app throttle is primary, Caddy must pass Cloudflare's CF-Connecting-IP to the app, and Cloudflare edge rate limiting covers request floods.

Update the reference Caddyfile to accept only Cloudflare ranges and reject direct-to-origin traffic, and document the exact Cloudflare dashboard rules.

* Document 10-second Cloudflare rate-limit window

Cloudflare may only offer a 10-second period. Keep the edge rule at 10 login POSTs per 10 seconds per IP and rely on the app's 15-minute login/address throttle for credential guessing.

* Document Cloudflare limits for LiveView registration

Registration submits over the shared LiveView socket, so a Cloudflare rule on POST /users/register will not count account creations. Note the app-level throttle/Turnstile options instead.

* Document current Cloudflare free-plan edge controls

Record the production setup: Cloudflare-only Caddy origins, Bot Fight Mode, and the 10-second login flood rule (10 POSTs per 10 seconds, 10-second block). Clarify that the application's 15-minute throttle remains the real credential lockout.

* Auto-refresh Cloudflare CIDRs for Caddy

Move the origin allowlist into a generated cloudflare-ranges.caddy imported by Caddy. Add an hourly systemd timer and script that fetch Cloudflare's v4/v6 lists, reject malformed responses, validate the candidate Caddyfile, and reload Caddy only when the ranges change. Restore the previous file on validation or reload failure.

* Document Cloudflare CIDR refresher setup and operations

Record the installed paths, permissions, timer checks, manual run, update procedure, and the direct-on-VPS setup fallback when the deploy directory is absent.
This commit is contained in:
2026-11-11 21:27:59 +01:00
committed by GitHub
parent 202b9b1f6a
commit 624ddab644
45 changed files with 3602 additions and 70 deletions
@@ -0,0 +1,177 @@
defmodule ChesstrainerWeb.Admin.UserLive.Index do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts
@per_page 25
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} wide>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
Users
<:subtitle>
Search accounts, review their roles and plans, and open a user to edit them.
Admins only see members and moderators.
</:subtitle>
<:actions>
<.button variant="primary" navigate={~p"/admin/users/new"}>
<.icon name="hero-plus" /> Invite user
</.button>
</:actions>
</.header>
<.form for={@filter_form} id="admin-user-search-form" phx-change="search" class="mb-6">
<.input
field={@filter_form[:search]}
type="search"
label="Search by email or username"
autocomplete="off"
phx-debounce="200"
placeholder="email or username…"
/>
</.form>
<p :if={@users == []} class="text-base-content/70">
<%= if @search == "" do %>
No users are visible to you yet.
<% else %>
No users match “{@search}”.
<% end %>
</p>
<table :if={@users != []} class={table_class()}>
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Plan</th>
<th>Confirmed</th>
<th>Created</th>
<th><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody id="admin-users">
<tr :for={user <- @users} id={"user-" <> user.id}>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.role}</td>
<td>{user.plan}</td>
<td>{confirmed_label(user)}</td>
<td>{format_date(user.inserted_at)}</td>
<td class="w-0 font-semibold">
<.link navigate={~p"/admin/users/#{user.id}"}>View</.link>
</td>
</tr>
</tbody>
</table>
<div class="mt-4 flex flex-wrap items-center justify-between gap-3 text-sm text-base-content/70">
<p>
Page {@page} of {@total_pages} · {@count} {if @count == 1, do: "user", else: "users"}
</p>
<div class="flex gap-2">
<.button
:if={@page > 1}
variant="secondary"
phx-click="previous_page"
id="previous-page"
>
Previous
</.button>
<.button
:if={@page < @total_pages}
variant="secondary"
phx-click="next_page"
id="next-page"
>
Next
</.button>
</div>
</div>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, socket) do
socket =
socket
|> assign(:page_title, "Users")
|> assign(:search, "")
|> assign(:page, 1)
|> assign(:users, [])
|> assign(:count, 0)
|> assign(:total_pages, 1)
|> assign(:filter_form, to_form(%{"search" => ""}))
case load_users(socket) do
{:ok, socket} -> {:ok, socket}
{:error, :unauthorized} -> {:ok, redirect_unauthorized(socket)}
end
end
@impl true
def handle_event("search", %{"search" => search}, socket) do
case load_users(assign(socket, search: search, page: 1)) do
{:ok, socket} -> {:noreply, socket}
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
end
end
def handle_event("previous_page", _params, socket) do
case load_users(assign(socket, :page, max(socket.assigns.page - 1, 1))) do
{:ok, socket} -> {:noreply, socket}
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
end
end
def handle_event("next_page", _params, socket) do
case load_users(assign(socket, :page, socket.assigns.page + 1)) do
{:ok, socket} -> {:noreply, socket}
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
end
end
defp load_users(socket) do
scope = socket.assigns.current_scope
search = socket.assigns.search
case Accounts.count_users_for_admin(scope, search: search) do
{:ok, count} ->
total_pages = max(div(count + @per_page - 1, @per_page), 1)
page = min(socket.assigns.page, total_pages)
case Accounts.list_users_for_admin(scope, search: search, page: page) do
{:ok, users} ->
{:ok,
assign(socket, users: users, count: count, total_pages: total_pages, page: page)}
{:error, :unauthorized} ->
{:error, :unauthorized}
end
{:error, :unauthorized} ->
{:error, :unauthorized}
end
end
defp redirect_unauthorized(socket) do
socket
|> put_flash(:error, "You are not authorized to manage users.")
|> push_navigate(to: ~p"/")
end
defp confirmed_label(%{confirmed_at: nil}), do: "No"
defp confirmed_label(_user), do: "Yes"
defp format_date(nil), do: ""
defp format_date(%DateTime{} = datetime) do
Calendar.strftime(datetime, "%Y-%m-%d")
end
end
@@ -0,0 +1,120 @@
defmodule ChesstrainerWeb.Admin.UserLive.New do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Accounts.Role
alias Chesstrainer.Accounts.User
@plan_options [{"Free", "free"}, {"Premium", "premium"}]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash}>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
Invite user
<:subtitle>
We create the account and email a link so the recipient can choose a password.
The invite is confirmed immediately, so no separate confirmation step is needed.
</:subtitle>
</.header>
<.form for={@form} id="invite-user-form" phx-change="validate" phx-submit="save">
<.input
field={@form[:email]}
type="email"
label="Email"
autocomplete="off"
required
/>
<.input
field={@form[:username]}
type="text"
label="Username"
autocomplete="off"
required
/>
<.input
field={@form[:role]}
type="select"
label="Role"
options={@role_options}
/>
<.input
field={@form[:plan]}
type="select"
label="Plan"
options={@plan_options}
/>
<footer>
<.button phx-disable-with="Sending..." variant="primary">Send invitation</.button>
<.button navigate={~p"/admin/users"}>Cancel</.button>
</footer>
</.form>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:page_title, "Invite user")
|> assign(:role_options, role_options(socket.assigns.current_scope))
|> assign(:plan_options, @plan_options)
|> assign(
:form,
to_form(%{"email" => "", "username" => "", "role" => "member", "plan" => "free"},
as: :user
)
)}
end
@impl true
def handle_event("validate", %{"user" => user_params}, socket) do
changeset =
%User{}
|> User.invite_changeset(user_params)
|> User.admin_changeset(user_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
end
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.invite_user_as_admin(
socket.assigns.current_scope,
user_params,
&url(~p"/users/reset-password/#{&1}")
) do
{:ok, user} ->
{:noreply,
socket
|> put_flash(:info, "Invitation sent to #{user.email}.")
|> push_navigate(to: ~p"/admin/users")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
{:error, :unauthorized} ->
{:noreply, put_flash(socket, :error, "You are not authorized to assign that role.")}
{:error, _reason} ->
{:noreply,
put_flash(socket, :error, "The invitation could not be sent. Please try again.")}
end
end
defp role_options(scope) do
for role <- Role.values(),
Policy.can_assign_role?(scope, role),
do: {role_label(role), role}
end
defp role_label(:super_admin), do: "Super admin"
defp role_label(role), do: role |> Atom.to_string() |> String.capitalize()
end
@@ -0,0 +1,228 @@
defmodule ChesstrainerWeb.Admin.UserLive.Show do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Accounts.Role
@plan_options [{"Free", "free"}, {"Premium", "premium"}]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} wide>
<Layouts.admin_nav current_scope={@current_scope} />
<div id="admin-user-page">
<.header>
{@user.username}
<:subtitle>Account details and administrator controls.</:subtitle>
<:actions>
<.button navigate={~p"/admin/users"}>
<.icon name="hero-arrow-left" /> All users
</.button>
</:actions>
</.header>
<.list>
<:item title="Email">{@user.email}</:item>
<:item title="Username">{@user.username}</:item>
<:item title="Role">{@user.role}</:item>
<:item title="Plan">{@user.plan}</:item>
<:item title="Confirmed">{confirmed_label(@user)}</:item>
<:item title="Rating">{round(@user.rating)}</:item>
<:item title="Created">{format_datetime(@user.inserted_at)}</:item>
<:item title="Last updated">{format_datetime(@user.updated_at)}</:item>
</.list>
<section class="mt-8">
<h2 class="text-lg font-semibold">Role and plan</h2>
<.form
:if={@can_manage}
for={@form}
id="admin-user-form"
phx-change="validate"
phx-submit="save"
class="mt-4"
>
<.input
field={@form[:role]}
type="select"
label="Role"
options={@role_options}
/>
<.input
field={@form[:plan]}
type="select"
label="Plan"
options={@plan_options}
/>
<footer>
<.button phx-disable-with="Saving..." variant="primary">Save changes</.button>
</footer>
</.form>
<p :if={!@can_manage} class="mt-4 text-sm text-base-content/70">
You can view this account but not change its role or plan.
</p>
</section>
<section :if={@can_manage} class="mt-8 border-t border-base-200 pt-6">
<h2 class="text-lg font-semibold">Account emails</h2>
<p class="mt-1 text-sm text-base-content/70">
These actions send email through the configured mailer. In development the messages
appear in the Swoosh mailbox at <code>/dev/mailbox</code>.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button
:if={is_nil(@user.confirmed_at)}
variant="secondary"
phx-click="resend_confirmation"
id="resend-confirmation"
>
Resend confirmation email
</.button>
<.button
variant="secondary"
phx-click="send_password_reset"
id="send-password-reset"
>
Send password reset email
</.button>
</div>
</section>
</div>
</Layouts.app>
"""
end
@impl true
def mount(%{"id" => id}, _session, socket) do
case Accounts.get_user_for_admin(socket.assigns.current_scope, id) do
{:ok, user} ->
{:ok, assign_user(socket, user)}
{:error, :unauthorized} ->
{:ok,
socket
|> put_flash(:error, "You are not authorized to view that user.")
|> push_navigate(to: ~p"/admin/users")}
{:error, :not_found} ->
{:ok,
socket
|> put_flash(:error, "User not found.")
|> push_navigate(to: ~p"/admin/users")}
end
end
@impl true
def handle_event("validate", %{"user" => user_params}, socket) do
if socket.assigns.can_manage do
changeset =
socket.assigns.user
|> Accounts.change_user_as_admin(user_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
else
{:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")}
end
end
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.update_user_as_admin(
socket.assigns.current_scope,
socket.assigns.user,
user_params
) do
{:ok, user} ->
{:noreply,
socket
|> assign_user(user)
|> put_flash(:info, "User updated successfully.")}
{:error, :unauthorized} ->
{:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")}
{:error, :own_role} ->
{:noreply, put_flash(socket, :error, "You cannot change your own role.")}
{:error, :last_super_admin} ->
{:noreply, put_flash(socket, :error, "You cannot demote the last super admin.")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end
end
def handle_event("resend_confirmation", _params, socket) do
case Accounts.resend_user_confirmation_instructions_as_admin(
socket.assigns.current_scope,
socket.assigns.user,
&url(~p"/users/confirm/#{&1}")
) do
{:ok, _email} ->
{:noreply, put_flash(socket, :info, "Confirmation email sent.")}
{:error, :already_confirmed} ->
{:noreply, put_flash(socket, :error, "That account is already confirmed.")}
{:error, :unauthorized} ->
{:noreply, put_flash(socket, :error, "You are not authorized to email this user.")}
{:error, _reason} ->
{:noreply, put_flash(socket, :error, "The confirmation email could not be sent.")}
end
end
def handle_event("send_password_reset", _params, socket) do
case Accounts.send_user_reset_password_instructions_as_admin(
socket.assigns.current_scope,
socket.assigns.user,
&url(~p"/users/reset-password/#{&1}")
) do
{:ok, _email} ->
{:noreply, put_flash(socket, :info, "Password reset email sent.")}
{:error, :unauthorized} ->
{:noreply, put_flash(socket, :error, "You are not authorized to email this user.")}
{:error, _reason} ->
{:noreply, put_flash(socket, :error, "The password reset email could not be sent.")}
end
end
defp assign_user(socket, user) do
can_manage = Policy.can_manage_user?(socket.assigns.current_scope, user)
socket
|> assign(:page_title, user.username)
|> assign(:user, user)
|> assign(:can_manage, can_manage)
|> assign(:plan_options, @plan_options)
|> assign(:role_options, role_options(socket.assigns.current_scope))
|> assign(:form, to_form(Accounts.change_user_as_admin(user)))
end
defp role_options(scope) do
for role <- Role.values(),
Policy.can_assign_role?(scope, role),
do: {role_label(role), role}
end
defp role_label(:super_admin), do: "Super admin"
defp role_label(role), do: role |> Atom.to_string() |> String.capitalize()
defp confirmed_label(%{confirmed_at: nil}), do: "No"
defp confirmed_label(_user), do: "Yes"
defp format_datetime(nil), do: "—"
defp format_datetime(%DateTime{} = datetime) do
Calendar.strftime(datetime, "%Y-%m-%d %H:%M UTC")
end
end