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
+84
View File
@@ -0,0 +1,84 @@
defmodule ChesstrainerWeb.ClientAddress do
@moduledoc """
Resolves the client's IP address from either a controller connection or a
LiveView socket.
`X-Forwarded-For` is only read when
`Chesstrainer.GuestLimits.trust_forwarded_for?/0` is enabled. In that case the
rightmost entry is used, because that is the value our own proxy appended.
Invalid or missing headers fall back to the peer address.
Production is Cloudflare -> Caddy -> Phoenix. `deploy/Caddyfile` makes Caddy
overwrite `X-Forwarded-For` with Cloudflare's `CF-Connecting-IP` and rejects
direct-to-origin requests, so the rightmost value is the real visitor rather
than a Cloudflare edge address.
"""
alias Chesstrainer.GuestLimits
@typedoc "An IPv4/IPv6 address, or `nil` when no peer data is available."
@type address :: :inet.ip_address() | nil
@doc "Returns the client address for a controller connection."
@spec from_conn(Plug.Conn.t()) :: address()
def from_conn(conn) do
if GuestLimits.trust_forwarded_for?() do
conn
|> Plug.Conn.get_req_header("x-forwarded-for")
|> parse_forwarded_header()
|> fallback(conn.remote_ip)
else
conn.remote_ip
end
end
@doc "Returns the client address for a connected LiveView socket."
@spec from_socket(Phoenix.LiveView.Socket.t()) :: address()
def from_socket(socket) do
if GuestLimits.trust_forwarded_for?() do
socket
|> Phoenix.LiveView.get_connect_info(:x_headers)
|> parse_x_headers()
|> fallback(peer_address(socket))
else
peer_address(socket)
end
end
defp peer_address(socket) do
case Phoenix.LiveView.get_connect_info(socket, :peer_data) do
%{address: address} -> address
_ -> nil
end
end
defp parse_forwarded_header([value | _]) when is_binary(value), do: parse_address(value)
defp parse_forwarded_header(_headers), do: nil
defp parse_x_headers(headers) when is_list(headers) do
case List.keyfind(headers, "x-forwarded-for", 0) do
{_, value} when is_binary(value) -> parse_address(value)
_ -> nil
end
end
defp parse_x_headers(_headers), do: nil
# The rightmost entry is the one our own proxy appended.
defp parse_address(value) do
value
|> String.split(",")
|> List.last()
|> to_string()
|> String.trim()
|> String.to_charlist()
|> :inet.parse_address()
|> case do
{:ok, address} -> address
{:error, _} -> nil
end
end
defp fallback(nil, fallback), do: fallback
defp fallback(address, _fallback), do: address
end
@@ -5,6 +5,7 @@ defmodule ChesstrainerWeb.Layouts do
"""
use ChesstrainerWeb, :html
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Accounts.Role
alias Chesstrainer.Accounts.Scope
@@ -133,6 +134,42 @@ defmodule ChesstrainerWeb.Layouts do
"""
end
@doc """
Renders the shared sub-navigation for admin pages.
Items are filtered by capability, so the same component is safe to render on
every admin screen.
"""
attr :current_scope, :map, default: nil
def admin_nav(assigns) do
links =
for {capability, label, href} <- [
{:manage_endgames, "Endgames", ~p"/admin/endgames"},
{:manage_themes, "Themes", ~p"/admin/themes"},
{:manage_users, "Users", ~p"/admin/users"}
],
Policy.can?(assigns.current_scope, capability),
do: %{label: label, href: href}
assigns = assign(assigns, :links, links)
~H"""
<nav
aria-label="Admin"
class="mb-6 flex flex-wrap items-center gap-1 border-b border-base-200 pb-3 text-sm font-semibold"
>
<.link
:for={link <- @links}
navigate={link.href}
class="rounded-md px-3 py-1.5 text-base-content/70 hover:bg-base-200 hover:text-base-content"
>
{link.label}
</.link>
</nav>
"""
end
defp nav_links(scope) do
marketing =
if Scope.premium?(scope) do
@@ -187,6 +224,7 @@ defmodule ChesstrainerWeb.Layouts do
<a href="/privacy">Privacy Policy</a>
<a href="/terms-conditions">Terms & Conditions</a>
<a href="/mentions-legales">Mentions légales</a>
<a href="/sitemap.xml">Sitemap</a>
</nav>
<small>© {@year} {Branding.name()}</small>
@@ -1,7 +1,11 @@
defmodule ChesstrainerWeb.UserSessionController do
use ChesstrainerWeb, :controller
require Logger
alias Chesstrainer.Accounts
alias ChesstrainerWeb.ClientAddress
alias ChesstrainerWeb.LoginThrottle
alias ChesstrainerWeb.UserAuth
def create(conn, %{"user" => user_params}) do
@@ -17,32 +21,78 @@ defmodule ChesstrainerWeb.UserSessionController do
end
defp authenticate(conn, user_params, failure_path, success_path) do
%{"email" => login} = user_params
address = ClientAddress.from_conn(conn)
case LoginThrottle.check(address, login) do
:ok ->
attempt_login(conn, address, user_params, failure_path, success_path)
{:throttled, bucket, retry_in_ms} ->
log_auth_event("auth.login.throttled", address, reason: bucket)
conn
|> put_flash(:error, throttle_message(retry_in_ms))
|> redirect(to: failure_path)
end
end
defp attempt_login(conn, address, user_params, failure_path, success_path) do
%{"email" => login, "password" => password} = user_params
case Accounts.get_user_by_login_and_password(login, password) do
nil ->
invalid_credentials(conn, login, failure_path)
authentication_failed(conn, address, login, :invalid_credentials, failure_path)
user ->
if user.confirmed_at do
LoginThrottle.record_success(login)
conn
|> maybe_put_return_to(success_path)
|> put_flash(:info, "Welcome back!")
|> UserAuth.log_in_user(user, user_params)
else
{:ok, _} =
Accounts.deliver_user_confirmation_instructions(
user,
&url(~p"/users/confirm/#{&1}")
)
# In order to prevent user enumeration attacks, report the same error
# as invalid credentials.
invalid_credentials(conn, login, failure_path)
maybe_resend_confirmation(user, login)
authentication_failed(conn, address, login, :unconfirmed, failure_path)
end
end
end
defp maybe_resend_confirmation(user, login) do
if LoginThrottle.claim_confirmation_resend(login) do
case Accounts.deliver_user_confirmation_instructions(
user,
&url(~p"/users/confirm/#{&1}")
) do
{:ok, _email} -> :ok
{:error, _reason} -> Logger.warning("auth.confirmation.resend_failed")
end
end
:ok
end
defp authentication_failed(conn, address, login, reason, failure_path) do
LoginThrottle.record_failure(address, login)
log_auth_event("auth.login.failed", address, reason: reason)
# In order to prevent user enumeration attacks, report the same error as
# invalid credentials.
invalid_credentials(conn, login, failure_path)
end
defp log_auth_event(message, address, metadata) do
Logger.warning(message, Keyword.put(metadata, :ip, LoginThrottle.fingerprint(address)))
end
defp throttle_message(retry_in_ms) do
minutes = max(div(retry_in_ms + 59_999, 60_000), 1)
unit = if minutes == 1, do: "minute", else: "minutes"
"Too many attempts. Try again in #{minutes} #{unit}."
end
defp invalid_credentials(conn, login, path) do
conn
|> put_flash(:error, "Invalid email, username or password")
@@ -0,0 +1,114 @@
defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Themes
alias Chesstrainer.Themes.Theme
@category_options [
{"Endgame", "endgame"},
{"Opening", "opening"},
{"Tactic", "tactic"}
]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash}>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
{@page_title}
<:subtitle>
Themes group endgames for filtering. Names must be unique within a category,
ignoring case.
</:subtitle>
</.header>
<.form for={@form} id="theme-form" phx-change="validate" phx-submit="save">
<.input field={@form[:name]} type="text" label="Name" autocomplete="off" required />
<.input
field={@form[:category]}
type="select"
label="Category"
options={@category_options}
/>
<footer>
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
<.button navigate={~p"/admin/themes"}>Cancel</.button>
</footer>
</.form>
</Layouts.app>
"""
end
@impl true
def mount(params, _session, socket) do
{:ok, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :new, _params) do
theme = %Theme{}
socket
|> assign(:page_title, "New theme")
|> assign(:theme, theme)
|> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme)))
end
defp apply_action(socket, :edit, %{"id" => id}) do
theme = Themes.get_theme!(id)
socket
|> assign(:page_title, "Edit theme")
|> assign(:theme, theme)
|> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme)))
end
@impl true
def handle_event("validate", %{"theme" => theme_params}, socket) do
changeset =
socket.assigns.theme
|> Themes.change_theme(theme_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
end
def handle_event("save", %{"theme" => theme_params}, socket) do
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
save_theme(socket, socket.assigns.live_action, theme_params)
else
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
end
end
defp save_theme(socket, :new, theme_params) do
case Themes.create_theme(theme_params) do
{:ok, _theme} ->
{:noreply,
socket
|> put_flash(:info, "Theme created successfully.")
|> push_navigate(to: ~p"/admin/themes")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end
end
defp save_theme(socket, :edit, theme_params) do
case Themes.update_theme(socket.assigns.theme, theme_params) do
{:ok, _theme} ->
{:noreply,
socket
|> put_flash(:info, "Theme updated successfully.")
|> push_navigate(to: ~p"/admin/themes")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end
end
end
@@ -0,0 +1,160 @@
defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Themes
@category_options [
{"All categories", ""},
{"Endgame", "endgame"},
{"Opening", "opening"},
{"Tactic", "tactic"}
]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} wide>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
Themes
<:subtitle>
Themes group endgames for filtering and puzzle selection. Deleting a theme detaches
it from every endgame and leaves the endgames intact.
</:subtitle>
<:actions>
<.button variant="primary" navigate={~p"/admin/themes/new"}>
<.icon name="hero-plus" /> New theme
</.button>
</:actions>
</.header>
<.form
for={@filter_form}
id="theme-admin-filter-form"
phx-change="filter"
class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end"
>
<div class="flex-1 [&>div]:mb-0">
<.input
field={@filter_form[:search]}
type="text"
label="Search by name"
autocomplete="off"
phx-debounce="200"
placeholder="Theme name…"
/>
</div>
<div class="[&>div]:mb-0 sm:w-56">
<.input
field={@filter_form[:category]}
type="select"
label="Category"
options={@category_options}
/>
</div>
</.form>
<p :if={@themes == []} class="text-base-content/70">
<%= if @has_filters do %>
No themes match these filters.
<% else %>
No themes yet. Themes power endgame filtering and puzzle selection, so start by
creating one and attaching it to an endgame.
<% end %>
</p>
<table :if={@themes != []} class={table_class()}>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Used by</th>
<th><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody id="themes">
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
<td>{theme.name}</td>
<td>{theme.category}</td>
<td>
<span id={"theme-usage-#{theme.id}"}>{usage_label(usage_count)}</span>
</td>
<td class="w-0 font-semibold">
<div class="flex gap-4">
<.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit</.link>
<.link
phx-click="delete"
phx-value-id={theme.id}
data-confirm={
"Delete #{theme.name}? Used by #{usage_label(usage_count)}. " <>
"The endgames will be kept and simply detached."
}
>
Delete
</.link>
</div>
</td>
</tr>
</tbody>
</table>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:page_title, "Themes")
|> assign(:search, "")
|> assign(:category, "")
|> assign(:has_filters, false)
|> assign(:category_options, @category_options)
|> assign(:filter_form, to_form(%{"search" => "", "category" => ""}))
|> load_themes()}
end
@impl true
def handle_event("filter", params, socket) do
search = Map.get(params, "search", socket.assigns.search)
category = Map.get(params, "category", socket.assigns.category)
{:noreply,
socket
|> assign(:search, search)
|> assign(:category, category)
|> assign(:has_filters, String.trim(search) != "" or category != "")
|> load_themes()}
end
def handle_event("delete", %{"id" => id}, socket) do
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
theme = Themes.get_theme!(id)
{:ok, _theme} = Themes.delete_theme(theme)
socket =
socket
|> put_flash(:info, "Theme deleted. Attached endgames were kept.")
|> load_themes()
{:noreply, socket}
else
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
end
end
defp load_themes(socket) do
themes =
Themes.list_themes_for_admin(
search: socket.assigns.search,
category: socket.assigns.category
)
assign(socket, :themes, themes)
end
defp usage_label(1), do: "1 endgame"
defp usage_label(count), do: "#{count} endgames"
end
@@ -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
@@ -13,6 +13,8 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
def render(assigns) do
~H"""
<Layouts.app flash={@flash}>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
{@page_title}
<:subtitle>Use this form to manage endgame records in your database.</:subtitle>
@@ -48,7 +50,7 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
placeholder="Search or create a theme…"
/>
<ul class="mt-2 w-full rounded-md border border-base-300 bg-base-100 p-1 shadow-sm">
<ul>
<li :for={theme <- @theme_results}>
<button
type="button"
@@ -14,6 +14,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
alias Chesstrainer.Endgames
alias Chesstrainer.GuestLimits
alias ChesstrainerWeb.ClientAddress
alias ChesstrainerWeb.EndgameLive.PlayCore
alias ChesstrainerWeb.PlayComponents
@@ -112,7 +113,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
{:ok, redirect(socket, to: ~p"/train")}
connected?(socket) ->
take_puzzle(socket, client_address(socket))
take_puzzle(socket, ClientAddress.from_socket(socket))
true ->
{:ok,
@@ -222,46 +223,6 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
end
end
defp client_address(socket) do
if GuestLimits.trust_forwarded_for?() do
forwarded_address(socket) || peer_address(socket)
else
peer_address(socket)
end
end
defp peer_address(socket) do
case get_connect_info(socket, :peer_data) do
%{address: address} -> address
_ -> nil
end
end
defp forwarded_address(socket) do
with headers when is_list(headers) <- get_connect_info(socket, :x_headers),
{_, value} <- List.keyfind(headers, "x-forwarded-for", 0),
address when address != nil <- parse_address(value) do
address
else
_ -> nil
end
end
# The rightmost entry is the one our own proxy appended.
defp parse_address(value) do
value
|> String.split(",")
|> List.last()
|> to_string()
|> String.trim()
|> String.to_charlist()
|> :inet.parse_address()
|> case do
{:ok, address} -> address
{:error, _} -> nil
end
end
defp signed_in?(socket) do
case socket.assigns.current_scope do
%{user: %{}} -> true
@@ -9,6 +9,8 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
def render(assigns) do
~H"""
<Layouts.app flash={@flash} wide>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
Listing Endgames
<:actions>
@@ -26,6 +26,8 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
~H"""
<Layouts.app flash={@flash} wide>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
Endgame {@endgame.id}
<:subtitle>This is a endgame record from your database.</:subtitle>
+236
View File
@@ -0,0 +1,236 @@
defmodule ChesstrainerWeb.LoginThrottle do
@moduledoc """
In-memory failure throttle for password logins.
Failures are counted in two independent fixed windows: one per client address
and one per normalised login (email or username). A successful login clears
the login bucket only, so one account stays protected from distributed
guessing while one address stays protected from spraying many accounts.
Addresses and logins are HMACed with a per-boot secret before they reach ETS;
raw values are never stored or logged. The table is per node and is cleared on
restart, which is acceptable for the current single-node deployment.
"""
use GenServer
@table :login_throttle
@sweep_interval :timer.minutes(1)
@default_window_ms :timer.minutes(15)
@default_max_per_ip 10
@default_max_per_login 5
@typedoc "An IPv4/IPv6 address, or `nil` when the socket has no peer data."
@type address :: :inet.ip_address() | nil
@typedoc "Which bucket blocked the attempt."
@type bucket :: :ip | :login
@doc "Starts the throttle."
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
@doc """
Checks both buckets without recording anything.
Returns `:ok`, or `{:throttled, bucket, retry_in_ms}` when that bucket is
already at its limit.
"""
@spec check(address, String.t() | nil) :: :ok | {:throttled, bucket(), non_neg_integer()}
def check(address, login), do: GenServer.call(__MODULE__, {:check, address, login})
@doc "Records one failed authentication in both buckets."
@spec record_failure(address, String.t() | nil) :: :ok
def record_failure(address, login) do
GenServer.call(__MODULE__, {:record_failure, address, login})
end
@doc "Clears the login bucket. The address bucket deliberately stays."
@spec record_success(String.t() | nil) :: :ok
def record_success(login), do: GenServer.call(__MODULE__, {:record_success, login})
@doc """
Claims a confirmation-email resend for `login`.
Returns true at most once per cooldown window, so repeated unconfirmed login
attempts cannot send a fresh confirmation email on every try.
"""
@spec claim_confirmation_resend(String.t() | nil) :: boolean()
def claim_confirmation_resend(login) do
GenServer.call(__MODULE__, {:claim_confirmation_resend, login})
end
@doc """
Returns a stable, non-reversible fingerprint of an address for log metadata.
The digest is scoped to this boot, matching the throttle keys.
"""
@spec fingerprint(address) :: String.t() | nil
def fingerprint(address), do: GenServer.call(__MODULE__, {:fingerprint, address})
@doc "Clears every bucket. Intended for tests."
def reset, do: GenServer.call(__MODULE__, :reset)
@doc "Failures allowed per address before the next attempt is blocked."
def max_per_ip, do: config() |> Keyword.get(:max_per_ip, @default_max_per_ip)
@doc "Failures allowed per login before the next attempt is blocked."
def max_per_login, do: config() |> Keyword.get(:max_per_login, @default_max_per_login)
@doc "How long a bucket stays active, in milliseconds."
def window_ms, do: config() |> Keyword.get(:window_ms, @default_window_ms)
defp config, do: Application.get_env(:chesstrainer, __MODULE__, [])
@impl true
def init(opts) do
:ets.new(@table, [:named_table, :set])
Process.send_after(self(), :sweep, @sweep_interval)
{:ok,
%{
secret: :crypto.strong_rand_bytes(32),
window_ms: Keyword.get(opts, :window_ms, window_ms()),
max_per_ip: Keyword.get(opts, :max_per_ip, max_per_ip()),
max_per_login: Keyword.get(opts, :max_per_login, max_per_login()),
confirmation_cooldown_ms: Keyword.get(opts, :confirmation_cooldown_ms, window_ms())
}}
end
@impl true
def handle_call({:check, address, login}, _from, state) do
now = now_ms()
result =
case blocked(:ip, address, state, now) do
nil -> blocked(:login, normalize_login(login), state, now) || :ok
blocked -> blocked
end
{:reply, result, state}
end
def handle_call({:record_failure, address, login}, _from, state) do
now = now_ms()
bump(:ip, address, state, now)
bump(:login, normalize_login(login), state, now)
{:reply, :ok, state}
end
def handle_call({:record_success, login}, _from, state) do
case normalize_login(login) do
nil -> :ok
login -> :ets.delete(@table, key(state.secret, :login, login))
end
{:reply, :ok, state}
end
def handle_call({:claim_confirmation_resend, login}, _from, state) do
normalized = normalize_login(login)
now = now_ms()
case normalized do
nil ->
{:reply, true, state}
login ->
key = key(state.secret, :confirmation, login)
case count(key, now) do
nil ->
:ets.insert(@table, {key, now + state.confirmation_cooldown_ms, 1})
{:reply, true, state}
_active ->
{:reply, false, state}
end
end
end
def handle_call({:fingerprint, nil}, _from, state), do: {:reply, nil, state}
def handle_call({:fingerprint, address}, _from, state) do
fingerprint =
state.secret
|> key(:ip, address)
|> Base.encode16(case: :lower)
{:reply, fingerprint, state}
end
def handle_call(:reset, _from, state) do
:ets.delete_all_objects(@table)
{:reply, :ok, state}
end
@impl true
def handle_info(:sweep, state) do
:ets.select_delete(@table, [{{:_, :"$1", :_}, [{:"=<", :"$1", now_ms()}], [true]}])
Process.send_after(self(), :sweep, @sweep_interval)
{:noreply, state}
end
defp blocked(_bucket, nil, _state, _now), do: nil
defp blocked(bucket, value, state, now) do
key = key(state.secret, bucket, value)
limit = limit(bucket, state)
case count(key, now) do
{count, expires_at} when count >= limit ->
{:throttled, bucket, max(expires_at - now, 0)}
_ ->
nil
end
end
defp bump(_bucket, nil, _state, _now), do: :ok
defp bump(bucket, value, state, now) do
key = key(state.secret, bucket, value)
case count(key, now) do
{count, expires_at} ->
:ets.insert(@table, {key, expires_at, count + 1})
nil ->
:ets.insert(@table, {key, now + state.window_ms, 1})
end
end
defp count(key, now) do
case :ets.lookup(@table, key) do
[{^key, expires_at, count}] when expires_at > now ->
{count, expires_at}
[{^key, _expires_at, _count}] ->
:ets.delete(@table, key)
nil
[] ->
nil
end
end
defp limit(:ip, state), do: state.max_per_ip
defp limit(:login, state), do: state.max_per_login
defp key(secret, bucket, value) do
:crypto.mac(:hmac, :sha256, secret, [Atom.to_string(bucket), "|", value_binary(value)])
end
defp value_binary(value) when is_binary(value), do: value
defp value_binary(value) when is_tuple(value), do: :erlang.term_to_binary(value)
defp normalize_login(login) when is_binary(login) do
case login |> String.trim() |> String.downcase() do
"" -> nil
login -> login
end
end
defp normalize_login(_login), do: nil
defp now_ms, do: System.system_time(:millisecond)
end
+9 -1
View File
@@ -43,7 +43,7 @@ defmodule ChesstrainerWeb.Router do
scope "/admin", ChesstrainerWeb do
pipe_through [:browser, :noindex, :require_admin_user]
live_session :endgames,
live_session :admin,
on_mount: [
{ChesstrainerWeb.UserAuth, :enforce_prelaunch},
{ChesstrainerWeb.UserAuth, :require_admin}
@@ -52,6 +52,14 @@ defmodule ChesstrainerWeb.Router do
live "/endgames/new", EndgameLive.Form, :new
live "/endgames/:id", EndgameLive.Show, :show
live "/endgames/:id/edit", EndgameLive.Form, :edit
live "/themes", Admin.ThemeLive.Index, :index
live "/themes/new", Admin.ThemeLive.Form, :new
live "/themes/:id/edit", Admin.ThemeLive.Form, :edit
live "/users", Admin.UserLive.Index, :index
live "/users/new", Admin.UserLive.New, :new
live "/users/:id", Admin.UserLive.Show, :show
end
end
+6 -1
View File
@@ -218,7 +218,12 @@ defmodule ChesstrainerWeb.UserAuth do
ChesstrainerWeb.UserLive.Profile,
ChesstrainerWeb.EndgameLive.Index,
ChesstrainerWeb.EndgameLive.Form,
ChesstrainerWeb.EndgameLive.Show
ChesstrainerWeb.EndgameLive.Show,
ChesstrainerWeb.Admin.ThemeLive.Index,
ChesstrainerWeb.Admin.ThemeLive.Form,
ChesstrainerWeb.Admin.UserLive.Index,
ChesstrainerWeb.Admin.UserLive.New,
ChesstrainerWeb.Admin.UserLive.Show
]
def on_mount(:enforce_prelaunch, _params, _session, socket) do