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
+137
View File
@@ -0,0 +1,137 @@
defmodule Chesstrainer.Accounts.PolicyTest do
use Chesstrainer.DataCase, async: true
import Chesstrainer.AccountsFixtures
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Accounts.Scope
describe "can?/2" do
test "members and moderators have no admin capabilities" do
for role <- [:member, :moderator], capability <- Policy.capabilities() do
refute Policy.can?(scope_for(role), capability)
end
end
test "admins and super admins have every admin capability" do
for role <- [:admin, :super_admin], capability <- Policy.capabilities() do
assert Policy.can?(scope_for(role), capability)
end
end
test "a nil scope has no capabilities" do
refute Policy.can?(nil, :manage_users)
end
end
describe "can_manage_user?/2" do
test "an admin can manage members and moderators" do
scope = scope_for(:admin)
assert Policy.can_manage_user?(scope, user_with_role(:member))
assert Policy.can_manage_user?(scope, user_with_role(:moderator))
end
test "an admin cannot manage admins, super admins, or themselves" do
admin = user_with_role(:admin)
scope = Scope.for_user(admin)
refute Policy.can_manage_user?(scope, admin)
refute Policy.can_manage_user?(scope, user_with_role(:admin))
refute Policy.can_manage_user?(scope, user_with_role(:super_admin))
end
test "a super admin can manage everyone except themselves" do
super = user_with_role(:super_admin)
scope = Scope.for_user(super)
refute Policy.can_manage_user?(scope, super)
assert Policy.can_manage_user?(scope, user_with_role(:member))
assert Policy.can_manage_user?(scope, user_with_role(:moderator))
assert Policy.can_manage_user?(scope, user_with_role(:admin))
assert Policy.can_manage_user?(scope, user_with_role(:super_admin))
end
test "moderators and members cannot manage anyone" do
for role <- [:member, :moderator] do
scope = scope_for(role)
refute Policy.can_manage_user?(scope, user_with_role(:member))
refute Policy.can_manage_user?(scope, user_with_role(:moderator))
end
end
end
describe "can_view_user?/2" do
test "an admin can view lower-ranked users and themselves" do
admin = user_with_role(:admin)
scope = Scope.for_user(admin)
assert Policy.can_view_user?(scope, admin)
assert Policy.can_view_user?(scope, user_with_role(:member))
assert Policy.can_view_user?(scope, user_with_role(:moderator))
refute Policy.can_view_user?(scope, user_with_role(:admin))
refute Policy.can_view_user?(scope, user_with_role(:super_admin))
end
test "a super admin can view everyone" do
super = user_with_role(:super_admin)
scope = Scope.for_user(super)
assert Policy.can_view_user?(scope, super)
assert Policy.can_view_user?(scope, user_with_role(:member))
assert Policy.can_view_user?(scope, user_with_role(:moderator))
assert Policy.can_view_user?(scope, user_with_role(:admin))
assert Policy.can_view_user?(scope, user_with_role(:super_admin))
end
end
describe "can_assign_role?/2" do
test "admins can assign member and moderator only" do
scope = scope_for(:admin)
assert Policy.can_assign_role?(scope, :member)
assert Policy.can_assign_role?(scope, :moderator)
refute Policy.can_assign_role?(scope, :admin)
refute Policy.can_assign_role?(scope, :super_admin)
end
test "super admins can assign every role" do
scope = scope_for(:super_admin)
for role <- [:member, :moderator, :admin, :super_admin] do
assert Policy.can_assign_role?(scope, role)
end
end
end
describe "visible_roles/1" do
test "admins only see members and moderators" do
assert Policy.visible_roles(scope_for(:admin)) == [:member, :moderator]
end
test "super admins see every role" do
assert Policy.visible_roles(scope_for(:super_admin)) ==
[:member, :moderator, :admin, :super_admin]
end
test "members and moderators see no users" do
assert Policy.visible_roles(scope_for(:member)) == []
assert Policy.visible_roles(scope_for(:moderator)) == []
end
end
defp scope_for(role) do
role
|> user_with_role()
|> Scope.for_user()
end
defp user_with_role(:member), do: user_fixture()
defp user_with_role(role) do
{:ok, user} = Accounts.update_user_role(user_fixture(), role)
user
end
end
+387
View File
@@ -0,0 +1,387 @@
defmodule Chesstrainer.AccountsAdminTest do
use Chesstrainer.DataCase, async: false
require Logger
import Chesstrainer.AccountsFixtures
import ExUnit.CaptureLog
import Swoosh.TestAssertions
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
describe "list_users_for_admin/2" do
test "an admin only sees members and moderators" do
admin = user_with_role(:admin)
member = user_fixture()
moderator = user_with_role(:moderator)
other_admin = user_with_role(:admin)
super_admin = user_with_role(:super_admin)
assert {:ok, users} = Accounts.list_users_for_admin(Scope.for_user(admin))
ids = users |> Enum.map(& &1.id) |> MapSet.new()
assert ids == MapSet.new([member.id, moderator.id])
refute MapSet.member?(ids, other_admin.id)
refute MapSet.member?(ids, super_admin.id)
assert {:ok, 2} = Accounts.count_users_for_admin(Scope.for_user(admin))
end
test "a super admin sees every role, including themselves" do
super_admin = user_with_role(:super_admin)
member = user_fixture()
moderator = user_with_role(:moderator)
admin = user_with_role(:admin)
assert {:ok, users} = Accounts.list_users_for_admin(Scope.for_user(super_admin))
ids = users |> Enum.map(& &1.id) |> MapSet.new()
assert MapSet.new([super_admin.id, member.id, moderator.id, admin.id]) == ids
end
test "search matches email and username case-insensitively" do
admin = user_with_role(:admin)
target = user_fixture(%{email: "FindMe@Example.com", username: "searchable_name"})
user_fixture()
assert {:ok, [found]} =
Accounts.list_users_for_admin(Scope.for_user(admin), search: "findme")
assert found.id == target.id
assert {:ok, [found]} =
Accounts.list_users_for_admin(Scope.for_user(admin), search: "SEARCHABLE")
assert found.id == target.id
assert {:ok, []} = Accounts.list_users_for_admin(Scope.for_user(admin), search: "no-match")
end
test "paginates 25 users per page" do
admin = user_with_role(:admin)
for _ <- 1..26 do
user_fixture()
end
assert {:ok, 26} = Accounts.count_users_for_admin(Scope.for_user(admin))
assert {:ok, page_one} = Accounts.list_users_for_admin(Scope.for_user(admin), page: 1)
assert length(page_one) == 25
assert {:ok, page_two} = Accounts.list_users_for_admin(Scope.for_user(admin), page: 2)
assert length(page_two) == 1
end
test "members and moderators are rejected" do
for role <- [:member, :moderator] do
scope = scope_for(role)
assert {:error, :unauthorized} = Accounts.list_users_for_admin(scope)
assert {:error, :unauthorized} = Accounts.count_users_for_admin(scope)
assert {:error, :unauthorized} = Accounts.get_user_for_admin(scope, user_fixture().id)
end
end
end
describe "update_user_as_admin/3" do
test "an admin can change a member's role and plan" do
admin = user_with_role(:admin)
member = user_fixture()
previous_level = Logger.level()
Logger.configure(level: :info)
log =
try do
capture_log(
[format: "$message $metadata\n", metadata: [:actor_id, :target_id, :fields]],
fn ->
assert {:ok, updated} =
Accounts.update_user_as_admin(Scope.for_user(admin), member, %{
"role" => "moderator",
"plan" => "premium"
})
assert updated.role == :moderator
assert updated.plan == :premium
end
)
after
Logger.configure(level: previous_level)
end
assert log =~ "admin.user.updated"
assert log =~ admin.id
assert log =~ member.id
refute log =~ member.email
end
test "an admin can change a moderator" do
admin = user_with_role(:admin)
moderator = user_with_role(:moderator)
assert {:ok, updated} =
Accounts.update_user_as_admin(Scope.for_user(admin), moderator, %{
"role" => "member"
})
assert updated.role == :member
end
test "an admin cannot change another admin or a super admin" do
admin = user_with_role(:admin)
for target <- [user_with_role(:admin), user_with_role(:super_admin)] do
assert {:error, :unauthorized} =
Accounts.update_user_as_admin(Scope.for_user(admin), target, %{
"plan" => "premium"
})
assert Accounts.get_user!(target.id).plan == :free
end
end
test "an admin cannot promote a member above their own rank" do
admin = user_with_role(:admin)
member = user_fixture()
assert {:error, :unauthorized} =
Accounts.update_user_as_admin(Scope.for_user(admin), member, %{"role" => "admin"})
assert Accounts.get_user!(member.id).role == :member
end
test "a super admin can change an admin's role and plan" do
super_admin = user_with_role(:super_admin)
admin = user_with_role(:admin)
assert {:ok, updated} =
Accounts.update_user_as_admin(Scope.for_user(super_admin), admin, %{
"role" => "moderator",
"plan" => "premium"
})
assert updated.role == :moderator
assert updated.plan == :premium
end
test "a super admin can change another super admin's plan" do
super_admin = user_with_role(:super_admin)
other_super_admin = user_with_role(:super_admin)
assert {:ok, updated} =
Accounts.update_user_as_admin(
Scope.for_user(super_admin),
other_super_admin,
%{"plan" => "premium"}
)
assert updated.plan == :premium
end
test "a super admin cannot change their own role" do
super_admin = user_with_role(:super_admin)
assert {:error, :own_role} =
Accounts.update_user_as_admin(
Scope.for_user(super_admin),
super_admin,
%{"role" => "admin"}
)
assert Accounts.get_user!(super_admin.id).role == :super_admin
end
test "the last super admin cannot be demoted" do
# The actor has the super-admin capability but is not persisted, leaving
# exactly one super admin in the database.
actor = %{user_fixture() | role: :super_admin}
target = user_with_role(:super_admin)
assert {:error, :last_super_admin} =
Accounts.update_user_as_admin(Scope.for_user(actor), target, %{
"role" => "admin"
})
assert Accounts.get_user!(target.id).role == :super_admin
end
test "members and moderators are rejected" do
for role <- [:member, :moderator] do
target = user_fixture()
assert {:error, :unauthorized} =
Accounts.update_user_as_admin(scope_for(role), target, %{"plan" => "premium"})
end
end
end
describe "invite_user_as_admin/3" do
test "an admin can invite a member and an email is sent" do
admin = user_with_role(:admin)
attrs = invite_attrs()
assert {:ok, invited} =
Accounts.invite_user_as_admin(Scope.for_user(admin), attrs, &password_reset_url/1)
assert invited.email == attrs["email"]
assert invited.username == attrs["username"]
assert invited.role == :member
assert invited.plan == :free
assert invited.confirmed_at
assert_email_sent(
to: invited.email,
subject: "You're invited to Inner Square Chess"
)
end
test "a super admin can invite an admin" do
super_admin = user_with_role(:super_admin)
assert {:ok, invited} =
Accounts.invite_user_as_admin(
Scope.for_user(super_admin),
Map.put(invite_attrs(), "role", "admin"),
&password_reset_url/1
)
assert invited.role == :admin
end
test "an admin cannot invite an admin or super admin" do
admin = user_with_role(:admin)
for role <- ["admin", "super_admin"] do
attrs = Map.put(invite_attrs(), "role", role)
assert {:error, :unauthorized} =
Accounts.invite_user_as_admin(
Scope.for_user(admin),
attrs,
&password_reset_url/1
)
refute Accounts.get_user_by_email(attrs["email"])
end
end
test "duplicate emails return the changeset error" do
admin = user_with_role(:admin)
existing = user_fixture()
attrs = Map.put(invite_attrs(), "email", existing.email)
assert {:error, changeset} =
Accounts.invite_user_as_admin(
Scope.for_user(admin),
attrs,
&password_reset_url/1
)
assert changeset.errors[:email]
end
test "moderators and members are rejected" do
for role <- [:member, :moderator] do
assert {:error, :unauthorized} =
Accounts.invite_user_as_admin(
scope_for(role),
invite_attrs(),
&password_reset_url/1
)
end
end
end
describe "admin-initiated account emails" do
test "an admin can send a password reset to a member" do
admin = user_with_role(:admin)
member = user_fixture()
assert {:ok, _email} =
Accounts.send_user_reset_password_instructions_as_admin(
Scope.for_user(admin),
member,
&password_reset_url/1
)
assert_email_sent(to: member.email, subject: "Reset password instructions")
end
test "an admin cannot send a password reset to another admin" do
admin = user_with_role(:admin)
other_admin = user_with_role(:admin)
assert {:error, :unauthorized} =
Accounts.send_user_reset_password_instructions_as_admin(
Scope.for_user(admin),
other_admin,
&password_reset_url/1
)
refute_email_sent()
end
test "a super admin can send a password reset to an admin" do
super_admin = user_with_role(:super_admin)
admin = user_with_role(:admin)
assert {:ok, _email} =
Accounts.send_user_reset_password_instructions_as_admin(
Scope.for_user(super_admin),
admin,
&password_reset_url/1
)
assert_email_sent(to: admin.email, subject: "Reset password instructions")
end
test "an admin can resend confirmation to an unconfirmed member" do
admin = user_with_role(:admin)
member = unconfirmed_user_fixture()
assert {:ok, _email} =
Accounts.resend_user_confirmation_instructions_as_admin(
Scope.for_user(admin),
member,
&confirmation_url/1
)
assert_email_sent(to: member.email, subject: "Confirmation instructions")
end
test "resending confirmation to a confirmed user reports the error" do
admin = user_with_role(:admin)
member = user_fixture()
assert {:error, :already_confirmed} =
Accounts.resend_user_confirmation_instructions_as_admin(
Scope.for_user(admin),
member,
&confirmation_url/1
)
end
end
defp password_reset_url(token), do: "http://localhost/users/reset-password/#{token}"
defp confirmation_url(token), do: "http://localhost/users/confirm/#{token}"
defp invite_attrs do
%{
"email" => unique_user_email(),
"username" => unique_username(),
"role" => "member",
"plan" => "free"
}
end
defp scope_for(role), do: role |> user_with_role() |> Scope.for_user()
defp user_with_role(:member), do: user_fixture()
defp user_with_role(role) do
{:ok, user} = Accounts.update_user_role(user_fixture(), role)
user
end
end
@@ -37,6 +37,22 @@ defmodule ChesstrainerWeb.AdminGatingTest do
assert redirected_to(conn) == ~p"/"
end
test "members and moderators are redirected from themes and users", _context do
for role <- [:member, :moderator] do
{:ok, user} = Accounts.update_user_role(user_fixture(), role)
conn = log_in_user(build_conn(), user)
for path <- [
~p"/admin/themes",
~p"/admin/themes/new",
~p"/admin/users",
~p"/admin/users/new"
] do
assert redirected_to(get(conn, path)) == ~p"/"
end
end
end
test "admins are admitted", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :admin)
@@ -0,0 +1,83 @@
defmodule ChesstrainerWeb.ClientAddressTest do
use ExUnit.Case, async: false
import Plug.Test
alias Chesstrainer.GuestLimits
alias ChesstrainerWeb.ClientAddress
@peer {10, 0, 0, 1}
@forwarded {203, 0, 113, 9}
setup do
previous = Application.get_env(:chesstrainer, GuestLimits, [])
on_exit(fn -> Application.put_env(:chesstrainer, GuestLimits, previous) end)
:ok
end
test "ignores X-Forwarded-For when trust is off" do
trust_forwarded_for(false)
conn =
conn(:post, "/users/log-in")
|> Map.put(:remote_ip, @peer)
|> Map.put(:req_headers, [{"x-forwarded-for", "203.0.113.9"}])
assert ClientAddress.from_conn(conn) == @peer
end
test "honours the rightmost X-Forwarded-For entry when trust is on" do
trust_forwarded_for(true)
conn =
conn(:post, "/users/log-in")
|> Map.put(:remote_ip, @peer)
|> Map.put(:req_headers, [{"x-forwarded-for", "198.51.100.2, 203.0.113.9"}])
assert ClientAddress.from_conn(conn) == @forwarded
end
test "falls back to the peer address for an invalid forwarded header" do
trust_forwarded_for(true)
conn =
conn(:post, "/users/log-in")
|> Map.put(:remote_ip, @peer)
|> Map.put(:req_headers, [{"x-forwarded-for", "not-an-address"}])
assert ClientAddress.from_conn(conn) == @peer
end
test "ignores socket X-Forwarded-For when trust is off" do
trust_forwarded_for(false)
assert ClientAddress.from_socket(socket()) == @peer
end
test "honours socket X-Forwarded-For when trust is on" do
trust_forwarded_for(true)
assert ClientAddress.from_socket(socket()) == @forwarded
end
defp socket do
%Phoenix.LiveView.Socket{
private: %{
connect_info: %{
peer_data: %{address: @peer},
x_headers: [{"x-forwarded-for", "203.0.113.9"}]
}
}
}
end
defp trust_forwarded_for(enabled?) do
config = Application.get_env(:chesstrainer, GuestLimits, [])
Application.put_env(
:chesstrainer,
GuestLimits,
Keyword.put(config, :trust_forwarded_for, enabled?)
)
end
end
@@ -1,10 +1,16 @@
defmodule ChesstrainerWeb.UserSessionControllerTest do
use ChesstrainerWeb.ConnCase, async: true
use ChesstrainerWeb.ConnCase, async: false
@moduletag :capture_log
import Chesstrainer.AccountsFixtures
import ExUnit.CaptureLog
import Swoosh.TestAssertions
alias ChesstrainerWeb.LoginThrottle
setup do
LoginThrottle.reset()
%{user: user_fixture()}
end
@@ -77,7 +83,7 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
assert redirected_to(conn) == ~p"/users/log-in"
end
test "does not log in an unconfirmed user and resends confirmation instructions", %{
test "does not log in an unconfirmed user and resends confirmation instructions once", %{
conn: conn
} do
user = unconfirmed_user_fixture()
@@ -94,6 +100,146 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
assert redirected_to(conn) == ~p"/users/log-in"
assert_email_sent(subject: "Confirmation instructions")
second =
post(build_conn(), ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
refute get_session(second, :user_token)
refute_email_sent()
end
test "blocks further attempts after the login limit is reached", %{
conn: conn,
user: user
} do
for _ <- 1..LoginThrottle.max_per_login() do
blocked =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => "wrong password"}
})
assert Phoenix.Flash.get(blocked.assigns.flash, :error) ==
"Invalid email, username or password"
end
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
refute get_session(conn, :user_token)
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"Too many attempts. Try again in 15 minutes."
assert redirected_to(conn) == ~p"/users/log-in"
end
test "the address bucket blocks spraying many logins", %{conn: conn, user: user} do
for index <- 1..LoginThrottle.max_per_ip() do
blocked =
post(conn, ~p"/users/log-in", %{
"user" => %{
"email" => "unknown#{index}@example.com",
"password" => "wrong password"
}
})
assert Phoenix.Flash.get(blocked.assigns.flash, :error) ==
"Invalid email, username or password"
end
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
refute get_session(conn, :user_token)
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "Too many attempts."
end
test "a successful login clears the login bucket", %{conn: conn, user: user} do
for _ <- 1..(LoginThrottle.max_per_login() - 1) do
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => "wrong password"}
})
end
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
assert get_session(conn, :user_token)
post(build_conn(), ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => "wrong password"}
})
conn =
post(build_conn(), ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
assert get_session(conn, :user_token)
end
test "the admin login uses the same throttle", %{conn: conn, user: user} do
for _ <- 1..LoginThrottle.max_per_login() do
post(conn, ~p"/admin/log-in", %{
"user" => %{"email" => user.email, "password" => "wrong password"}
})
end
conn =
post(conn, ~p"/admin/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
refute get_session(conn, :user_token)
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "Too many attempts."
end
test "log events contain no raw address or password", %{conn: conn, user: user} do
log =
capture_log(
[format: "$message $metadata\n", metadata: [:ip, :reason]],
fn ->
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => "secret-wrong-password"}
})
end
)
assert log =~ "auth.login.failed"
assert log =~ "invalid_credentials"
refute log =~ "127.0.0.1"
refute log =~ "secret-wrong-password"
refute log =~ user.email
end
test "a throttled request logs auth.login.throttled", %{conn: conn, user: user} do
for _ <- 1..LoginThrottle.max_per_login() do
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => "wrong password"}
})
end
log =
capture_log(
[format: "$message $metadata\n", metadata: [:ip, :reason]],
fn ->
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
end
)
assert log =~ "auth.login.throttled"
assert log =~ "login"
refute log =~ "127.0.0.1"
end
end
@@ -0,0 +1,71 @@
defmodule ChesstrainerWeb.Admin.ThemeLive.FormTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.ThemesFixtures
alias Chesstrainer.Themes
setup :register_and_log_in_admin
test "creates a theme", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/themes/new")
view
|> form("#theme-form", theme: %{name: " Lucena ", category: "endgame"})
|> render_submit()
assert_redirect(view, ~p"/admin/themes")
assert [%{name: "Lucena", category: :endgame}] = Themes.search("Lucena", "endgame")
end
test "renames and recategorises a theme", %{conn: conn} do
theme = theme_fixture(%{name: "Lucena", category: :endgame})
{:ok, view, _html} = live(conn, ~p"/admin/themes/#{theme.id}/edit")
view
|> form("#theme-form", theme: %{name: "Lucena", category: "opening"})
|> render_submit()
assert_redirect(view, ~p"/admin/themes")
updated = Themes.get_theme!(theme.id)
assert updated.name == "Lucena"
assert updated.category == :opening
end
test "shows the existing duplicate-name validation error", %{conn: conn} do
theme_fixture(%{name: "Lucena", category: :endgame})
{:ok, view, _html} = live(conn, ~p"/admin/themes/new")
html =
view
|> form("#theme-form", theme: %{name: "lucena", category: "endgame"})
|> render_submit()
assert html =~ "already exists"
assert length(Themes.list_themes()) == 1
end
test "validates a blank name", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/themes/new")
html =
view
|> form("#theme-form", theme: %{name: "", category: "endgame"})
|> render_submit()
assert html =~ "can&#39;t be blank"
end
test "shows the admin sub-navigation", %{conn: conn} do
{:ok, _view, html} = live(conn, ~p"/admin/themes/new")
assert html =~ ~p"/admin/endgames"
assert html =~ ~p"/admin/themes"
assert html =~ ~p"/admin/users"
end
end
@@ -0,0 +1,72 @@
defmodule ChesstrainerWeb.Admin.ThemeLive.IndexTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.EndgamesFixtures
import Chesstrainer.ThemesFixtures
alias Chesstrainer.Endgames
alias Chesstrainer.Repo
alias Chesstrainer.Themes
setup :register_and_log_in_admin
test "lists themes with their usage count", %{conn: conn} do
used_theme = theme_fixture(%{name: "Lucena"})
unused_theme = theme_fixture(%{name: "Philidor"})
endgame = endgame_fixture()
{:ok, _} = Endgames.update_endgame(endgame, %{}, [used_theme])
{:ok, view, _html} = live(conn, ~p"/admin/themes")
assert has_element?(view, "#theme-#{used_theme.id}")
assert has_element?(view, "#theme-usage-#{used_theme.id}", "1 endgame")
assert has_element?(view, "#theme-usage-#{unused_theme.id}", "0 endgames")
end
test "filters by name and category", %{conn: conn} do
theme_fixture(%{name: "Lucena", category: :endgame})
theme_fixture(%{name: "Philidor", category: :endgame})
theme_fixture(%{name: "Pin", category: :tactic})
{:ok, view, _html} = live(conn, ~p"/admin/themes")
view |> form("#theme-admin-filter-form", %{search: "Luc"}) |> render_change()
assert has_element?(view, "td", "Lucena")
refute has_element?(view, "td", "Philidor")
refute has_element?(view, "td", "Pin")
view |> form("#theme-admin-filter-form", %{search: "", category: "tactic"}) |> render_change()
assert has_element?(view, "td", "Pin")
refute has_element?(view, "td", "Lucena")
end
test "shows an empty state that explains what themes do", %{conn: conn} do
{:ok, _view, html} = live(conn, ~p"/admin/themes")
assert html =~ "No themes yet"
assert html =~ "Themes power endgame filtering"
end
test "deleting a theme detaches it from endgames and keeps the endgame", %{conn: conn} do
theme = theme_fixture(%{name: "Lucena"})
endgame = endgame_fixture()
{:ok, _} = Endgames.update_endgame(endgame, %{}, [theme])
{:ok, view, html} = live(conn, ~p"/admin/themes")
assert html =~ "Used by 1 endgame"
assert html =~ "The endgames will be kept"
view |> element("#theme-#{theme.id} a", "Delete") |> render_click()
assert_raise Ecto.NoResultsError, fn -> Themes.get_theme!(theme.id) end
assert Endgames.get_endgame!(endgame.id)
endgame = Endgames.get_endgame!(endgame.id) |> Repo.preload(:themes)
assert endgame.themes == []
end
end
@@ -0,0 +1,77 @@
defmodule ChesstrainerWeb.Admin.UserLive.IndexTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
alias Chesstrainer.Accounts
setup :register_and_log_in_admin
test "lists the users an admin may manage", %{conn: conn} do
member = user_fixture()
moderator = user_with_role(:moderator)
other_admin = user_with_role(:admin)
super_admin = user_with_role(:super_admin)
{:ok, view, _html} = live(conn, ~p"/admin/users")
assert has_element?(view, "#user-" <> member.id)
assert has_element?(view, "#user-" <> moderator.id)
refute has_element?(view, "#user-" <> other_admin.id)
refute has_element?(view, "#user-" <> super_admin.id)
end
test "searches by email or username", %{conn: conn} do
target = user_fixture(%{email: "FindMe@Example.com", username: "searchable_name"})
user_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/users")
view |> form("#admin-user-search-form", %{search: "findme"}) |> render_change()
assert has_element?(view, "#user-" <> target.id)
assert has_element?(view, "td", target.email)
view |> form("#admin-user-search-form", %{search: "searchable"}) |> render_change()
assert has_element?(view, "#user-" <> target.id)
view |> form("#admin-user-search-form", %{search: "nobody"}) |> render_change()
assert render(view) =~ "No users match"
end
test "paginates 25 users per page", %{conn: conn} do
for _ <- 1..26 do
user_fixture()
end
{:ok, view, _html} = live(conn, ~p"/admin/users")
assert row_count(view) == 25
assert render(view) =~ "Page 1 of 2"
view |> element("#next-page") |> render_click()
assert row_count(view) == 1
assert render(view) =~ "Page 2 of 2"
end
test "shows the admin navigation and invite action", %{conn: conn} do
{:ok, view, html} = live(conn, ~p"/admin/users")
assert html =~ ~p"/admin/endgames"
assert html =~ ~p"/admin/themes"
assert html =~ ~p"/admin/users/new"
assert has_element?(view, "#admin-user-search-form")
end
defp row_count(view) do
document = LazyHTML.from_fragment(render(view))
document |> LazyHTML.query("#admin-users tr") |> LazyHTML.to_tree() |> length()
end
defp user_with_role(role) do
{:ok, user} = Accounts.update_user_role(user_fixture(), role)
user
end
end
@@ -0,0 +1,87 @@
defmodule ChesstrainerWeb.Admin.UserLive.NewTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
import Swoosh.TestAssertions
alias Chesstrainer.Accounts
setup :register_and_log_in_admin
test "invites a new member", %{conn: conn} do
email = unique_user_email()
username = unique_username()
{:ok, view, _html} = live(conn, ~p"/admin/users/new")
{:ok, _view, html} =
view
|> form("#invite-user-form", user: %{email: email, username: username, role: "member"})
|> render_submit()
|> follow_redirect(conn, ~p"/admin/users")
assert html =~ "Invitation sent to #{email}."
invited = Accounts.get_user_by_email(email)
assert invited.username == username
assert invited.confirmed_at
assert_email_sent(to: email, subject: "You're invited to Inner Square Chess")
end
test "does not offer admin roles to an admin", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/users/new")
html = render(view)
assert html =~ "Moderator"
refute html =~ ~s(value="admin")
refute html =~ ~s(value="super_admin")
end
test "rejects a direct attempt to invite an admin", %{conn: conn} do
email = unique_user_email()
{:ok, view, _html} = live(conn, ~p"/admin/users/new")
html =
render_click(view, "save", %{
"user" => %{
"email" => email,
"username" => unique_username(),
"role" => "admin"
}
})
assert html =~ "You are not authorized to assign that role."
refute Accounts.get_user_by_email(email)
end
test "shows duplicate email errors", %{conn: conn} do
existing = user_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/users/new")
html =
view
|> form("#invite-user-form",
user: %{
email: existing.email,
username: unique_username(),
role: "member"
}
)
|> render_submit()
assert html =~ "has already been taken"
end
test "shows the admin sub-navigation", %{conn: conn} do
{:ok, _view, html} = live(conn, ~p"/admin/users/new")
assert html =~ ~p"/admin/endgames"
assert html =~ ~p"/admin/themes"
assert html =~ ~p"/admin/users"
end
end
@@ -0,0 +1,126 @@
defmodule ChesstrainerWeb.Admin.UserLive.ShowTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
import Swoosh.TestAssertions
alias Chesstrainer.Accounts
setup :register_and_log_in_admin
test "shows the user's identity and editable fields", %{conn: conn} do
member = user_fixture()
{:ok, view, html} = live(conn, ~p"/admin/users/#{member.id}")
assert html =~ member.email
assert html =~ member.username
assert has_element?(view, "#admin-user-form")
assert has_element?(view, "#send-password-reset")
refute has_element?(view, "#resend-confirmation")
end
test "an admin can change a member's role and plan", %{conn: conn} do
member = user_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/users/#{member.id}")
html =
view
|> form("#admin-user-form", user: %{role: "moderator", plan: "premium"})
|> render_submit()
assert html =~ "User updated successfully"
assert Accounts.get_user!(member.id).role == :moderator
assert Accounts.get_user!(member.id).plan == :premium
end
test "an admin cannot promote a member through a direct event", %{conn: conn} do
member = user_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/users/#{member.id}")
html = render_click(view, "save", %{"user" => %{"role" => "admin"}})
assert html =~ "You are not authorized to modify this user."
assert Accounts.get_user!(member.id).role == :member
end
test "an admin can view themselves read-only but has no editable form", %{
conn: conn,
user: admin
} do
{:ok, view, html} = live(conn, ~p"/admin/users/#{admin.id}")
assert html =~ "You can view this account but not change its role or plan."
refute has_element?(view, "#admin-user-form")
end
test "an admin is redirected away from another admin's detail page", %{conn: conn} do
other_admin = user_with_role(:admin)
{:ok, _view, html} =
live(conn, ~p"/admin/users/#{other_admin.id}")
|> follow_redirect(conn, ~p"/admin/users")
assert html =~ "You are not authorized to view that user."
end
test "a super admin can change an admin's role and plan" do
super_admin = user_with_role(:super_admin)
admin = user_with_role(:admin)
conn = build_conn() |> log_in_user(super_admin)
{:ok, view, _html} = live(conn, ~p"/admin/users/#{admin.id}")
html =
view
|> form("#admin-user-form", user: %{role: "moderator", plan: "premium"})
|> render_submit()
assert html =~ "User updated successfully"
assert Accounts.get_user!(admin.id).role == :moderator
assert Accounts.get_user!(admin.id).plan == :premium
end
test "a super admin cannot change their own role, even through a direct event" do
super_admin = user_with_role(:super_admin)
conn = build_conn() |> log_in_user(super_admin)
{:ok, view, _html} = live(conn, ~p"/admin/users/#{super_admin.id}")
html = render_click(view, "save", %{"user" => %{"role" => "admin"}})
assert html =~ "You cannot change your own role."
assert Accounts.get_user!(super_admin.id).role == :super_admin
end
test "resends a confirmation email to an unconfirmed member", %{conn: conn} do
member = unconfirmed_user_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/users/#{member.id}")
html = view |> element("#resend-confirmation") |> render_click()
assert html =~ "Confirmation email sent."
assert_email_sent(to: member.email, subject: "Confirmation instructions")
end
test "sends a password reset email to a member", %{conn: conn} do
member = user_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/users/#{member.id}")
html = view |> element("#send-password-reset") |> render_click()
assert html =~ "Password reset email sent."
assert_email_sent(to: member.email, subject: "Reset password instructions")
end
defp user_with_role(role) do
{:ok, user} = Accounts.update_user_role(user_fixture(), role)
user
end
end
@@ -1,6 +1,8 @@
defmodule ChesstrainerWeb.UserLive.LoginTest do
use ChesstrainerWeb.ConnCase, async: true
@moduletag :capture_log
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
@@ -0,0 +1,93 @@
defmodule ChesstrainerWeb.LoginThrottleTest do
use ExUnit.Case, async: false
alias ChesstrainerWeb.LoginThrottle
@address {203, 0, 113, 7}
@other_address {198, 51, 100, 9}
@login "someone@example.com"
setup do
LoginThrottle.reset()
:ok
end
test "uses the tightened limits and a 15 minute window" do
assert LoginThrottle.max_per_login() == 5
assert LoginThrottle.max_per_ip() == 10
assert LoginThrottle.window_ms() == :timer.minutes(15)
end
test "blocks the next attempt after the login limit is reached" do
for _ <- 1..(LoginThrottle.max_per_login() - 1) do
assert :ok = LoginThrottle.record_failure(@address, @login)
end
assert :ok = LoginThrottle.check(@address, @login)
assert :ok = LoginThrottle.record_failure(@address, @login)
assert {:throttled, :login, retry_in_ms} = LoginThrottle.check(@address, @login)
assert retry_in_ms > 0
end
test "blocks the next attempt after the address limit is reached across logins" do
for index <- 1..LoginThrottle.max_per_ip() do
assert :ok = LoginThrottle.record_failure(@address, "user#{index}@example.com")
end
assert {:throttled, :ip, retry_in_ms} =
LoginThrottle.check(@address, "fresh@example.com")
assert retry_in_ms > 0
end
test "a successful login clears only the login bucket" do
for _ <- 1..(LoginThrottle.max_per_login() - 1) do
LoginThrottle.record_failure(@address, @login)
end
assert :ok = LoginThrottle.record_success(@login)
for _ <- 1..(LoginThrottle.max_per_login() - 1) do
LoginThrottle.record_failure(@address, @login)
end
assert :ok = LoginThrottle.check(@address, @login)
end
test "addresses are independent" do
for index <- 1..LoginThrottle.max_per_ip() do
LoginThrottle.record_failure(@address, "user#{index}@example.com")
end
assert {:throttled, :ip, _} = LoginThrottle.check(@address, "fresh@example.com")
assert :ok = LoginThrottle.check(@other_address, "fresh@example.com")
end
test "log fingerprints are stable and do not expose the address" do
fingerprint = LoginThrottle.fingerprint(@address)
assert is_binary(fingerprint)
assert fingerprint == LoginThrottle.fingerprint(@address)
refute fingerprint =~ "203.0.113.7"
end
test "confirmation resends are claimed at most once per cooldown" do
assert LoginThrottle.claim_confirmation_resend(@login)
refute LoginThrottle.claim_confirmation_resend(@login)
assert LoginThrottle.claim_confirmation_resend("another@example.com")
end
test "reset clears every bucket" do
for index <- 1..LoginThrottle.max_per_ip() do
LoginThrottle.record_failure(@address, "user#{index}@example.com")
end
assert {:throttled, :ip, _} = LoginThrottle.check(@address, "fresh@example.com")
LoginThrottle.reset()
assert :ok = LoginThrottle.check(@address, "fresh@example.com")
end
end