mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
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:
@@ -0,0 +1,100 @@
|
||||
defmodule Chesstrainer.Accounts.Policy do
|
||||
@moduledoc """
|
||||
The single source of truth for administrator capabilities.
|
||||
|
||||
Roles are ordered by `Chesstrainer.Accounts.Role`. An administrator may only
|
||||
manage users below their own rank; a `super_admin` may also manage admins and
|
||||
other super admins, but never changes their own role.
|
||||
|
||||
The router uses `can?/2` to gate the admin area, and every mutating admin
|
||||
LiveView calls back into this module or into the scoped `Accounts` functions
|
||||
so hidden buttons are never the only protection.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Accounts.{Role, Scope, User}
|
||||
|
||||
@capabilities %{
|
||||
manage_endgames: [:admin, :super_admin],
|
||||
manage_themes: [:admin, :super_admin],
|
||||
manage_users: [:admin, :super_admin]
|
||||
}
|
||||
|
||||
@doc "All admin capabilities."
|
||||
@spec capabilities() :: [atom()]
|
||||
def capabilities, do: Map.keys(@capabilities)
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may perform the given admin capability.
|
||||
|
||||
A nil scope or a member/moderator never satisfies an admin capability.
|
||||
"""
|
||||
@spec can?(Scope.t() | nil, atom()) :: boolean()
|
||||
def can?(%Scope{user: %User{role: role}}, capability) when is_atom(capability) do
|
||||
role in Map.get(@capabilities, capability, [])
|
||||
end
|
||||
|
||||
def can?(_scope, _capability), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may edit the target user's role and plan.
|
||||
|
||||
An actor may only modify a user whose role rank is strictly lower, except a
|
||||
`super_admin`, who may also modify admins and other super admins. Nobody may
|
||||
modify themselves through the admin area.
|
||||
"""
|
||||
@spec can_manage_user?(Scope.t() | nil, User.t()) :: boolean()
|
||||
def can_manage_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do
|
||||
cond do
|
||||
not can?(scope, :manage_users) -> false
|
||||
actor.id == target.id -> false
|
||||
actor.role == :super_admin -> true
|
||||
Role.rank(actor.role) > Role.rank(target.role) -> true
|
||||
true -> false
|
||||
end
|
||||
end
|
||||
|
||||
def can_manage_user?(_scope, _target), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may view the target user in the admin area.
|
||||
|
||||
Admins can see themselves and lower-ranked users read-only; super admins can
|
||||
see everyone. This is deliberately wider than `can_manage_user?/2`, which
|
||||
controls the editable form.
|
||||
"""
|
||||
@spec can_view_user?(Scope.t() | nil, User.t()) :: boolean()
|
||||
def can_view_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do
|
||||
can?(scope, :manage_users) and
|
||||
(actor.id == target.id or actor.role == :super_admin or
|
||||
Role.rank(actor.role) > Role.rank(target.role))
|
||||
end
|
||||
|
||||
def can_view_user?(_scope, _target), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may assign the given role.
|
||||
|
||||
Admins can only assign member or moderator. Super admins can assign any role.
|
||||
"""
|
||||
@spec can_assign_role?(Scope.t() | nil, Role.value()) :: boolean()
|
||||
def can_assign_role?(%Scope{user: %User{role: :super_admin}}, role) do
|
||||
role in Role.values()
|
||||
end
|
||||
|
||||
def can_assign_role?(%Scope{user: %User{role: actor_role}}, role) do
|
||||
role in Role.values() and Role.rank(actor_role) > Role.rank(role)
|
||||
end
|
||||
|
||||
def can_assign_role?(_scope, _role), do: false
|
||||
|
||||
@doc """
|
||||
Returns the roles whose users the scope may see in the admin user list.
|
||||
|
||||
Admins only see members and moderators; super admins see every role.
|
||||
"""
|
||||
@spec visible_roles(Scope.t() | nil) :: [Role.value()]
|
||||
def visible_roles(%Scope{user: %User{role: :super_admin}}), do: Role.values()
|
||||
|
||||
def visible_roles(%Scope{user: %User{role: :admin}}), do: [:member, :moderator]
|
||||
def visible_roles(_scope), do: []
|
||||
end
|
||||
@@ -6,6 +6,8 @@ defmodule Chesstrainer.Accounts.Role do
|
||||
should ask for the minimum tier they need via `at_least?/2`.
|
||||
"""
|
||||
|
||||
@type value :: :member | :moderator | :admin | :super_admin
|
||||
|
||||
@values [:member, :moderator, :admin, :super_admin]
|
||||
|
||||
@ranks %{
|
||||
|
||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.Scope do
|
||||
|
||||
defstruct user: nil
|
||||
|
||||
@type t :: %__MODULE__{user: User.t() | nil}
|
||||
|
||||
@doc """
|
||||
Creates a scope for the given user.
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.User do
|
||||
timestamps(type: :utc_datetime)
|
||||
end
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@doc """
|
||||
A user changeset for registration.
|
||||
|
||||
@@ -53,6 +55,32 @@ defmodule Chesstrainer.Accounts.User do
|
||||
|> validate_required([:role])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for an admin-created invitation.
|
||||
|
||||
The account is created without a password and marked confirmed, so the
|
||||
recipient can choose a password from the emailed invitation link and log in
|
||||
immediately afterwards. Role and plan are applied separately by
|
||||
`admin_changeset/2` after the caller has checked the policy.
|
||||
"""
|
||||
def invite_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:email, :username])
|
||||
|> validate_email([])
|
||||
|> validate_username([])
|
||||
|> put_change(:confirmed_at, DateTime.utc_now(:second))
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for the fields an administrator may edit.
|
||||
|
||||
These values are programmatic, so this changeset is only used by the scoped
|
||||
admin functions in `Chesstrainer.Accounts`.
|
||||
"""
|
||||
def admin_changeset(user, attrs) do
|
||||
cast(user, attrs, [:role, :plan])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for registering or changing the email.
|
||||
|
||||
|
||||
@@ -38,6 +38,31 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver an invitation to choose a password.
|
||||
|
||||
Admins create the account without a password; the invitation link uses the
|
||||
same reset-password token flow so the recipient can set one.
|
||||
"""
|
||||
def deliver_invite_instructions(user, url) do
|
||||
deliver(user.email, "You're invited to #{Branding.name()}", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.username},
|
||||
|
||||
An administrator has created an account for you on #{Branding.name()}.
|
||||
|
||||
Choose your password by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you weren't expecting this invitation, please ignore this email.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to reset a user password.
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user