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:
@@ -39,6 +39,16 @@ config :chesstrainer,
|
|||||||
ecto_repos: [Chesstrainer.Repo],
|
ecto_repos: [Chesstrainer.Repo],
|
||||||
generators: [timestamp_type: :utc_datetime]
|
generators: [timestamp_type: :utc_datetime]
|
||||||
|
|
||||||
|
# Password-login throttle. Failures are counted in fixed windows for each
|
||||||
|
# client address and each normalised login. The address bucket is deliberately
|
||||||
|
# wider so one account stays protected from distributed guessing while one
|
||||||
|
# address cannot spray many accounts.
|
||||||
|
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||||
|
window_ms: :timer.minutes(15),
|
||||||
|
max_per_login: 5,
|
||||||
|
max_per_ip: 10,
|
||||||
|
confirmation_cooldown_ms: :timer.minutes(15)
|
||||||
|
|
||||||
# Glicko rating system.
|
# Glicko rating system.
|
||||||
#
|
#
|
||||||
# `system_constant` is the volatility constraint passed through to the Glicko
|
# `system_constant` is the volatility constraint passed through to the Glicko
|
||||||
|
|||||||
+25
-2
@@ -3,11 +3,34 @@
|
|||||||
# This file is not installed automatically. On the shared VPS, add this block
|
# This file is not installed automatically. On the shared VPS, add this block
|
||||||
# to the existing Caddy config by hand, then validate and reload Caddy.
|
# to the existing Caddy config by hand, then validate and reload Caddy.
|
||||||
#
|
#
|
||||||
# The app listens on loopback only; Caddy is the public entry point.
|
# Cloudflare sits in front of Caddy. Two things matter here:
|
||||||
|
#
|
||||||
|
# 1. Only accept requests from Cloudflare's published edge ranges.
|
||||||
|
# 2. Replace X-Forwarded-For with Cloudflare's single-value CF-Connecting-IP
|
||||||
|
# header, so the app's TRUST_FORWARDED_FOR=true path sees the visitor, not a
|
||||||
|
# Cloudflare edge address.
|
||||||
|
#
|
||||||
|
# The ranges live in cloudflare-ranges.caddy next to this file. A systemd
|
||||||
|
# timer refreshes them from https://www.cloudflare.com/ips-v4 and /ips-v6;
|
||||||
|
# see deploy/update-cloudflare-ranges.sh and deploy/README.md.
|
||||||
|
|
||||||
innersquare.app {
|
innersquare.app {
|
||||||
encode zstd gzip
|
encode zstd gzip
|
||||||
reverse_proxy 127.0.0.1:4100
|
|
||||||
|
@cloudflare {
|
||||||
|
import cloudflare-ranges.caddy
|
||||||
|
}
|
||||||
|
|
||||||
|
handle @cloudflare {
|
||||||
|
reverse_proxy 127.0.0.1:4100 {
|
||||||
|
header_up X-Forwarded-For {http.request.header.CF-Connecting-IP}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Direct-to-origin requests cannot spoof Cloudflare's client-IP header.
|
||||||
|
handle {
|
||||||
|
respond "Access Denied" 403
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
www.innersquare.app {
|
www.innersquare.app {
|
||||||
|
|||||||
+169
-6
@@ -4,7 +4,8 @@ Phoenix release on the shared Ubuntu VPS, behind Caddy, with Postgres in Docker.
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
Internet
|
Internet
|
||||||
└─ Caddy :443
|
└─ Cloudflare (TLS, WAF, edge rate limiting)
|
||||||
|
└─ Caddy :443 (cloudflare ranges only)
|
||||||
└─ Phoenix release 127.0.0.1:4100
|
└─ Phoenix release 127.0.0.1:4100
|
||||||
└─ Postgres 127.0.0.1:5432
|
└─ Postgres 127.0.0.1:5432
|
||||||
```
|
```
|
||||||
@@ -442,13 +443,30 @@ is in place.
|
|||||||
|
|
||||||
## Caddy
|
## Caddy
|
||||||
|
|
||||||
On the current VPS the Caddyfile is a single file with no imports. Add the block
|
Add the site block from `deploy/Caddyfile` by hand. It imports
|
||||||
from `deploy/Caddyfile` by hand:
|
`cloudflare-ranges.caddy`, which is generated by
|
||||||
|
`deploy/update-cloudflare-ranges.sh` and refreshed by a systemd timer.
|
||||||
|
|
||||||
|
Caddy must only accept Cloudflare traffic and must replace `X-Forwarded-For`
|
||||||
|
with Cloudflare's `CF-Connecting-IP` value:
|
||||||
|
|
||||||
```caddy
|
```caddy
|
||||||
innersquare.app {
|
innersquare.app {
|
||||||
encode zstd gzip
|
encode zstd gzip
|
||||||
reverse_proxy 127.0.0.1:4100
|
|
||||||
|
@cloudflare {
|
||||||
|
import cloudflare-ranges.caddy
|
||||||
|
}
|
||||||
|
|
||||||
|
handle @cloudflare {
|
||||||
|
reverse_proxy 127.0.0.1:4100 {
|
||||||
|
header_up X-Forwarded-For {http.request.header.CF-Connecting-IP}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handle {
|
||||||
|
respond "Access Denied" 403
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
www.innersquare.app {
|
www.innersquare.app {
|
||||||
@@ -456,7 +474,72 @@ www.innersquare.app {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
If a new VPS uses imports, put the block in its own site file instead.
|
Install the range file and the hourly refresh timer:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo install -m 0755 /opt/chesstrainer/src/deploy/update-cloudflare-ranges.sh \
|
||||||
|
/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||||
|
sudo install -m 0644 /opt/chesstrainer/src/deploy/cloudflare-ranges.caddy \
|
||||||
|
/etc/caddy/cloudflare-ranges.caddy
|
||||||
|
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.service \
|
||||||
|
/etc/systemd/system/chesstrainer-cloudflare-ranges.service
|
||||||
|
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.timer \
|
||||||
|
/etc/systemd/system/chesstrainer-cloudflare-ranges.timer
|
||||||
|
```
|
||||||
|
|
||||||
|
The installed pieces are:
|
||||||
|
|
||||||
|
| Path | Mode | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `/usr/local/sbin/chesstrainer-update-cloudflare-ranges` | `0755` | fetch/validate/reload script |
|
||||||
|
| `/etc/caddy/cloudflare-ranges.caddy` | `0644` | generated `remote_ip` list |
|
||||||
|
| `/etc/systemd/system/chesstrainer-cloudflare-ranges.service` | `0644` | oneshot service |
|
||||||
|
| `/etc/systemd/system/chesstrainer-cloudflare-ranges.timer` | `0644` | hourly timer |
|
||||||
|
|
||||||
|
If `/opt/chesstrainer/src/deploy` is not present on the VPS, create the same
|
||||||
|
four files directly with `sudo tee` from the canonical contents in `deploy/`.
|
||||||
|
The timer only depends on the installed copies; it does not read the repo.
|
||||||
|
|
||||||
|
Run it once manually and enable the timer:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer
|
||||||
|
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||||
|
sudo journalctl -u chesstrainer-cloudflare-ranges.service -n 50 --no-pager
|
||||||
|
```
|
||||||
|
|
||||||
|
The script fetches <https://www.cloudflare.com/ips-v4> and
|
||||||
|
<https://www.cloudflare.com/ips-v6>, validates the result, and reloads Caddy
|
||||||
|
only when the ranges actually changed. If the download, Caddy validation or
|
||||||
|
reload fails, it keeps or restores the previous file.
|
||||||
|
|
||||||
|
Check the timer and last run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl list-timers chesstrainer-cloudflare-ranges.timer
|
||||||
|
systemctl status chesstrainer-cloudflare-ranges.service
|
||||||
|
journalctl -u chesstrainer-cloudflare-ranges.service --since "24 hours ago"
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not edit `/etc/caddy/cloudflare-ranges.caddy` by hand; the next timer run
|
||||||
|
overwrites it.
|
||||||
|
|
||||||
|
To update the refresher itself, replace the installed script or unit files from
|
||||||
|
the deploy directory, then:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl restart chesstrainer-cloudflare-ranges.timer
|
||||||
|
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||||
|
```
|
||||||
|
|
||||||
|
Without this, `TRUST_FORWARDED_FOR=true` records a Cloudflare edge address
|
||||||
|
instead of the visitor, and the login throttle and guest puzzle limit bucket
|
||||||
|
whole Cloudflare POPs together.
|
||||||
|
|
||||||
|
If a new VPS uses imports, put the site block in its own file instead; keep the
|
||||||
|
`import cloudflare-ranges.caddy` path next to the Caddyfile.
|
||||||
|
|
||||||
Do **not** switch Caddy until a release is running and verified on
|
Do **not** switch Caddy until a release is running and verified on
|
||||||
`127.0.0.1:4100`. Before that, keep the static coming-soon site live.
|
`127.0.0.1:4100`. Before that, keep the static coming-soon site live.
|
||||||
@@ -468,8 +551,16 @@ sudo caddy validate --config /etc/caddy/Caddyfile
|
|||||||
sudo systemctl reload caddy
|
sudo systemctl reload caddy
|
||||||
```
|
```
|
||||||
|
|
||||||
|
A direct request to the origin with a forged `CF-Connecting-IP` header should
|
||||||
|
receive `403 Access Denied`.
|
||||||
|
|
||||||
Do not let a deploy overwrite the shared Caddyfile.
|
Do not let a deploy overwrite the shared Caddyfile.
|
||||||
|
|
||||||
|
See `docs/security.md` for the application throttle, real-IP setup and the
|
||||||
|
Cloudflare edge controls. Production currently has Bot Fight Mode enabled and
|
||||||
|
the free-plan login flood rule: 10 POSTs per 10 seconds per IP, blocked for 10
|
||||||
|
seconds.
|
||||||
|
|
||||||
## Building a release
|
## Building a release
|
||||||
|
|
||||||
Build on a machine matching Ubuntu 24.04 / glibc 2.39, or let CI do it.
|
Build on a machine matching Ubuntu 24.04 / glibc 2.39, or let CI do it.
|
||||||
@@ -694,6 +785,75 @@ Set `Storage=persistent` and a `SystemMaxUse=` value in
|
|||||||
rate-limits bursts; if a crash storm drops lines, raise `RateLimitBurst` or
|
rate-limits bursts; if a crash storm drops lines, raise `RateLimitBurst` or
|
||||||
`RateLimitIntervalSec` there.
|
`RateLimitIntervalSec` there.
|
||||||
|
|
||||||
|
## Interactive shell and user management
|
||||||
|
|
||||||
|
Attach an IEx shell to the **running** release. This does not restart the
|
||||||
|
service and does not require direct database access:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/chesstrainer/current/bin/chesstrainer remote
|
||||||
|
```
|
||||||
|
|
||||||
|
You should get a prompt like `iex(chesstrainer@<host>)1>`. Exit with **Ctrl-C
|
||||||
|
twice**. Never call `System.halt/0`, `:init.stop/0`, or
|
||||||
|
`Application.stop(:chesstrainer)` from this shell — those stop production.
|
||||||
|
|
||||||
|
Use it for account and role management. Go through the application contexts
|
||||||
|
(not SQL) so changesets, bcrypt hashing, timestamps, and token bookkeeping stay
|
||||||
|
consistent:
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
# Look up by email or username
|
||||||
|
u = Chesstrainer.Accounts.get_user_by_login("owen")
|
||||||
|
|
||||||
|
# Promote or demote
|
||||||
|
{:ok, u} = Chesstrainer.Accounts.update_user_role(u, :super_admin)
|
||||||
|
|
||||||
|
# Confirm an account without sending email
|
||||||
|
{:ok, u} = Chesstrainer.Repo.update(Chesstrainer.Accounts.User.confirm_changeset(u))
|
||||||
|
|
||||||
|
# Create an account, generating its password server-side
|
||||||
|
pw = :crypto.strong_rand_bytes(18) |> Base.url_encode64(padding: false)
|
||||||
|
|
||||||
|
{:ok, u} =
|
||||||
|
Chesstrainer.Accounts.register_user(%{
|
||||||
|
email: "you@example.com",
|
||||||
|
username: "owen",
|
||||||
|
password: pw
|
||||||
|
})
|
||||||
|
|
||||||
|
{:ok, u} = Chesstrainer.Repo.update(Chesstrainer.Accounts.User.confirm_changeset(u))
|
||||||
|
pw
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- `register_user/1` hashes the password with bcrypt; `password` is virtual and
|
||||||
|
is never written to the database.
|
||||||
|
- Do not type passwords into the shell if you can avoid it — IEx may keep a
|
||||||
|
history file — and never paste a password from shell history. Generate one as
|
||||||
|
above and change it later at `/users/profile/settings`.
|
||||||
|
- `mix accounts.promote` still works when a compiled source checkout is present
|
||||||
|
on the host, but the release shell is the supported production path.
|
||||||
|
- There is no guard against demoting the last `super_admin` outside the future
|
||||||
|
admin UI, so check the result before demoting.
|
||||||
|
|
||||||
|
If `remote` fails while booting its client VM (for example
|
||||||
|
`Kernel pid terminated (logger)` with `code_server`/`persistent_term` in the
|
||||||
|
trace), the deployed release is stale, mixed, or missing IEx: rebuild and
|
||||||
|
redeploy it. To attach in the meantime, use the release's own ERTS:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo bash -c '
|
||||||
|
COOKIE=$(cat /opt/chesstrainer/current/releases/COOKIE)
|
||||||
|
exec /opt/chesstrainer/current/erts-*/bin/erl \
|
||||||
|
-sname debug -setcookie "$COOKIE" -remsh chesstrainer
|
||||||
|
'
|
||||||
|
```
|
||||||
|
|
||||||
|
That shell speaks Erlang syntax, so quote Elixir module atoms, e.g.
|
||||||
|
`'Elixir.Chesstrainer.Accounts':register_user(...)`.
|
||||||
|
|
||||||
## Backups
|
## Backups
|
||||||
|
|
||||||
`docker exec` connects over the container's Unix socket, which the Postgres
|
`docker exec` connects over the container's Unix socket, which the Postgres
|
||||||
@@ -753,6 +913,9 @@ the VPS regularly. A backup that is only on the VPS is not a backup.
|
|||||||
until a release exists.
|
until a release exists.
|
||||||
6. Release built on a matching Ubuntu runner and activated.
|
6. Release built on a matching Ubuntu runner and activated.
|
||||||
7. `/health` and `/` verified on `127.0.0.1:4100`.
|
7. `/health` and `/` verified on `127.0.0.1:4100`.
|
||||||
8. Caddy block added, validated, reloaded.
|
8. Caddy block, `cloudflare-ranges.caddy`, and the CIDR refresh timer added;
|
||||||
|
validated and reloaded.
|
||||||
9. Public `/`, `/privacy`, `/terms-conditions`, and `/health` verified.
|
9. Public `/`, `/privacy`, `/terms-conditions`, and `/health` verified.
|
||||||
10. Read-only role created, tunnel verified, backups scheduled and tested.
|
10. Read-only role created, tunnel verified, backups scheduled and tested.
|
||||||
|
11. Remote shell attaches and exits cleanly:
|
||||||
|
`sudo /opt/chesstrainer/current/bin/chesstrainer remote` (Ctrl-C twice).
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Refresh Cloudflare CIDRs for Caddy
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/docs/security.md
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||||
|
TimeoutStartSec=2min
|
||||||
|
Nice=10
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Hourly refresh of Cloudflare CIDRs for Caddy
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=hourly
|
||||||
|
RandomizedDelaySec=10m
|
||||||
|
Persistent=true
|
||||||
|
Unit=chesstrainer-cloudflare-ranges.service
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Generated by deploy/update-cloudflare-ranges.sh.
|
||||||
|
# Source: https://www.cloudflare.com/ips-v4 and /ips-v6
|
||||||
|
remote_ip 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
|
||||||
Executable
+115
@@ -0,0 +1,115 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Refresh Caddy's Cloudflare origin allowlist from Cloudflare's published
|
||||||
|
# ranges. Called by chesstrainer-cloudflare-ranges.timer.
|
||||||
|
#
|
||||||
|
# The generated file is imported by /etc/caddy/Caddyfile:
|
||||||
|
#
|
||||||
|
# @cloudflare {
|
||||||
|
# import cloudflare-ranges.caddy
|
||||||
|
# }
|
||||||
|
#
|
||||||
|
# The script validates the candidate Caddyfile before reloading Caddy. If the
|
||||||
|
# download or validation fails, the previous ranges stay in place.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
CADDYFILE="${CADDYFILE:-/etc/caddy/Caddyfile}"
|
||||||
|
RANGES_FILE="${RANGES_FILE:-/etc/caddy/cloudflare-ranges.caddy}"
|
||||||
|
CADDY_BIN="${CADDY_BIN:-caddy}"
|
||||||
|
RELOAD_CMD="${RELOAD_CMD:-systemctl reload caddy}"
|
||||||
|
LOCK_FILE="${LOCK_FILE:-/run/lock/chesstrainer-cloudflare-ranges.lock}"
|
||||||
|
|
||||||
|
tmpdir="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$tmpdir"' EXIT
|
||||||
|
|
||||||
|
exec 9>"$LOCK_FILE"
|
||||||
|
if ! flock -n 9; then
|
||||||
|
echo "another Cloudflare range update is already running" >&2
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
fetch() {
|
||||||
|
local url="$1"
|
||||||
|
local output="$2"
|
||||||
|
|
||||||
|
curl --fail --silent --show-error --location \
|
||||||
|
--proto '=https' \
|
||||||
|
--retry 3 --retry-delay 2 --connect-timeout 10 \
|
||||||
|
"$url" --output "$output"
|
||||||
|
}
|
||||||
|
|
||||||
|
validate_download() {
|
||||||
|
local file="$1"
|
||||||
|
|
||||||
|
[[ -s "$file" ]] || return 1
|
||||||
|
|
||||||
|
# One CIDR per line. Caddy performs the real validation; this prevents
|
||||||
|
# obviously malformed or injected content from being written.
|
||||||
|
if grep -Evq '^[0-9A-Fa-f:.]+/[0-9]{1,3}$' "$file"; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch "https://www.cloudflare.com/ips-v4" "$tmpdir/ips-v4"
|
||||||
|
fetch "https://www.cloudflare.com/ips-v6" "$tmpdir/ips-v6"
|
||||||
|
|
||||||
|
validate_download "$tmpdir/ips-v4"
|
||||||
|
validate_download "$tmpdir/ips-v6"
|
||||||
|
|
||||||
|
ranges="$(awk 'NF { printf "%s ", $0 }' "$tmpdir/ips-v4" "$tmpdir/ips-v6" | sed -e 's/[[:space:]]*$//')"
|
||||||
|
|
||||||
|
if [[ -z "$ranges" ]]; then
|
||||||
|
echo "Cloudflare returned an empty CIDR list" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
candidate="$tmpdir/cloudflare-ranges.caddy"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "# Generated by deploy/update-cloudflare-ranges.sh."
|
||||||
|
echo "# Source: https://www.cloudflare.com/ips-v4 and /ips-v6"
|
||||||
|
echo "remote_ip $ranges"
|
||||||
|
} >"$candidate"
|
||||||
|
|
||||||
|
if cmp -s "$candidate" "$RANGES_FILE"; then
|
||||||
|
echo "Cloudflare ranges are unchanged"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
install -d -m 0755 "$(dirname "$RANGES_FILE")"
|
||||||
|
|
||||||
|
backup="$tmpdir/previous-ranges.caddy"
|
||||||
|
if [[ -e "$RANGES_FILE" ]]; then
|
||||||
|
cp -a "$RANGES_FILE" "$backup"
|
||||||
|
fi
|
||||||
|
|
||||||
|
install -m 0644 "$candidate" "$RANGES_FILE"
|
||||||
|
|
||||||
|
if ! "$CADDY_BIN" validate --config "$CADDYFILE" --adapter caddyfile; then
|
||||||
|
echo "Caddy rejected the new Cloudflare ranges; restoring the previous file" >&2
|
||||||
|
|
||||||
|
if [[ -e "$backup" ]]; then
|
||||||
|
install -m 0644 "$backup" "$RANGES_FILE"
|
||||||
|
else
|
||||||
|
rm -f "$RANGES_FILE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
read -r -a reload_command <<<"$RELOAD_CMD"
|
||||||
|
|
||||||
|
if ! "${reload_command[@]}"; then
|
||||||
|
echo "Caddy reload failed; restoring the previous ranges" >&2
|
||||||
|
|
||||||
|
if [[ -e "$backup" ]]; then
|
||||||
|
install -m 0644 "$backup" "$RANGES_FILE"
|
||||||
|
else
|
||||||
|
rm -f "$RANGES_FILE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Cloudflare ranges updated and Caddy reloaded"
|
||||||
@@ -115,6 +115,21 @@ Prefer identifiers such as `user_id` or `table` over emails, and never log
|
|||||||
params or request bodies. The formatter is a safety net, not a licence to log
|
params or request bodies. The formatter is a safety net, not a licence to log
|
||||||
PII.
|
PII.
|
||||||
|
|
||||||
|
## Authentication events
|
||||||
|
|
||||||
|
`ChesstrainerWeb.UserSessionController` emits warning lines consumed by
|
||||||
|
host-level tooling such as fail2ban:
|
||||||
|
|
||||||
|
| Message | Metadata | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `auth.login.failed` | `reason` (`invalid_credentials` / `unconfirmed`), `ip` | A password login failed. |
|
||||||
|
| `auth.login.throttled` | `reason` (`ip` / `login`), `ip` | The address or login bucket blocked the attempt before bcrypt. |
|
||||||
|
|
||||||
|
`ip` is a boot-scoped HMAC of the client address, not the address itself. The
|
||||||
|
raw login identifier and password are never included. The login throttle is
|
||||||
|
configured in `config/config.exs` and defaults to five failures per login and
|
||||||
|
ten per address in a fifteen-minute window.
|
||||||
|
|
||||||
## Querying logs
|
## Querying logs
|
||||||
|
|
||||||
`journalctl` prints the raw line only with `-o cat`; the default output wraps it
|
`journalctl` prints the raw line only with `-o cat`; the default output wraps it
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
# Login and edge security
|
||||||
|
|
||||||
|
The login surface is protected in layers. The application throttle is the
|
||||||
|
primary control; Cloudflare is the edge backstop for volume. There is no
|
||||||
|
origin-level fail2ban for HTTP logins, because it would require storing raw IP
|
||||||
|
addresses and would ban Cloudflare edge addresses on this deployment.
|
||||||
|
|
||||||
|
## Current production configuration
|
||||||
|
|
||||||
|
- Caddy accepts only Cloudflare's published ranges and forwards
|
||||||
|
`CF-Connecting-IP` as `X-Forwarded-For`. The ranges are refreshed hourly by
|
||||||
|
`chesstrainer-cloudflare-ranges.timer`.
|
||||||
|
- `TRUST_FORWARDED_FOR=true`, so the app throttles by the real visitor address.
|
||||||
|
- Cloudflare Bot Fight Mode is enabled.
|
||||||
|
- The free-plan login flood rule allows 10 login POSTs per 10 seconds per IP and
|
||||||
|
blocks for 10 seconds.
|
||||||
|
|
||||||
|
The short Cloudflare block is rate smoothing, not a credential lockout. The
|
||||||
|
application's 5-per-login and 10-per-address failures in a 15-minute window are
|
||||||
|
the real control.
|
||||||
|
|
||||||
|
## 1. Application login throttle
|
||||||
|
|
||||||
|
`ChesstrainerWeb.LoginThrottle` counts failures in two buckets:
|
||||||
|
|
||||||
|
| Bucket | Limit | Window |
|
||||||
|
|---|---|---|
|
||||||
|
| Normalised login (email or username) | 5 failures | 15 minutes |
|
||||||
|
| Client address | 10 failures | 15 minutes |
|
||||||
|
|
||||||
|
Blocked attempts are rejected before the database lookup and bcrypt, so they do
|
||||||
|
not consume password-hashing CPU. A successful login clears the login bucket
|
||||||
|
only, keeping the address bucket in place so one address cannot spray many
|
||||||
|
accounts.
|
||||||
|
|
||||||
|
The bucket keys are boot-scoped HMACs. Raw addresses and raw login identifiers
|
||||||
|
are never stored in ETS or written to the application logs. The login form
|
||||||
|
returns the same generic error for unknown accounts, bad passwords and
|
||||||
|
unconfirmed accounts.
|
||||||
|
|
||||||
|
Configured in `config/config.exs`:
|
||||||
|
|
||||||
|
```elixir
|
||||||
|
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||||
|
window_ms: :timer.minutes(15),
|
||||||
|
max_per_login: 5,
|
||||||
|
max_per_ip: 10,
|
||||||
|
confirmation_cooldown_ms: :timer.minutes(15)
|
||||||
|
```
|
||||||
|
|
||||||
|
`auth.login.failed` and `auth.login.throttled` are documented in
|
||||||
|
`docs/logging.md`.
|
||||||
|
|
||||||
|
## 2. Real client IPs behind Cloudflare and Caddy
|
||||||
|
|
||||||
|
The production chain is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Internet
|
||||||
|
└─ Cloudflare
|
||||||
|
└─ Caddy :443
|
||||||
|
└─ Phoenix 127.0.0.1:4100
|
||||||
|
```
|
||||||
|
|
||||||
|
Caddy ignores incoming `X-Forwarded-*` values by default and replaces them with
|
||||||
|
the immediate peer address. Behind Cloudflare that peer is a Cloudflare edge
|
||||||
|
node, so without configuration the app would throttle whole Cloudflare POPs
|
||||||
|
rather than individual visitors.
|
||||||
|
|
||||||
|
`deploy/Caddyfile` fixes this by:
|
||||||
|
|
||||||
|
1. accepting only Cloudflare's published ranges, and
|
||||||
|
2. setting `X-Forwarded-For` from Cloudflare's single-value `CF-Connecting-IP`
|
||||||
|
header.
|
||||||
|
|
||||||
|
That keeps `TRUST_FORWARDED_FOR=true` safe: direct clients cannot reach the app
|
||||||
|
through Caddy, so they cannot forge the header.
|
||||||
|
|
||||||
|
`deploy/Caddyfile` imports `cloudflare-ranges.caddy`. The file is generated by
|
||||||
|
`deploy/update-cloudflare-ranges.sh`; do not edit it by hand.
|
||||||
|
|
||||||
|
The script is run hourly by `chesstrainer-cloudflare-ranges.timer`. It:
|
||||||
|
|
||||||
|
- downloads <https://www.cloudflare.com/ips-v4> and
|
||||||
|
<https://www.cloudflare.com/ips-v6>,
|
||||||
|
- rejects empty or malformed responses,
|
||||||
|
- validates the candidate Caddyfile,
|
||||||
|
- reloads Caddy only when the ranges changed.
|
||||||
|
|
||||||
|
If the download, validation or Caddy reload fails, the previous ranges stay in
|
||||||
|
place.
|
||||||
|
|
||||||
|
Install and run it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo install -m 0755 /opt/chesstrainer/src/deploy/update-cloudflare-ranges.sh \
|
||||||
|
/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||||
|
sudo install -m 0644 /opt/chesstrainer/src/deploy/cloudflare-ranges.caddy \
|
||||||
|
/etc/caddy/cloudflare-ranges.caddy
|
||||||
|
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.service \
|
||||||
|
/etc/systemd/system/chesstrainer-cloudflare-ranges.service
|
||||||
|
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.timer \
|
||||||
|
/etc/systemd/system/chesstrainer-cloudflare-ranges.timer
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer
|
||||||
|
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||||
|
```
|
||||||
|
|
||||||
|
If `/opt/chesstrainer/src/deploy` is not present on the VPS, create the same
|
||||||
|
four files directly with `sudo tee` from the canonical contents in `deploy/`.
|
||||||
|
The timer only uses the installed copies.
|
||||||
|
|
||||||
|
Check the timer and last run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl list-timers chesstrainer-cloudflare-ranges.timer
|
||||||
|
systemctl status chesstrainer-cloudflare-ranges.service
|
||||||
|
journalctl -u chesstrainer-cloudflare-ranges.service --since "24 hours ago"
|
||||||
|
```
|
||||||
|
|
||||||
|
Apply the site block by hand on the shared Caddy host, then validate and
|
||||||
|
reload:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||||
|
sudo systemctl reload caddy
|
||||||
|
```
|
||||||
|
|
||||||
|
Direct requests to the origin with a spoofed `CF-Connecting-IP` must receive
|
||||||
|
`403 Access Denied`; only Cloudflare's ranges should reach the Phoenix app. A
|
||||||
|
host firewall allowlist for Cloudflare on ports 80 and 443 is a useful
|
||||||
|
defence-in-depth addition.
|
||||||
|
|
||||||
|
## 3. Cloudflare edge rate limiting
|
||||||
|
|
||||||
|
This is for connection and request floods, not credential guessing. The
|
||||||
|
application already stops password attempts cheaply.
|
||||||
|
|
||||||
|
The production rule is the free-plan version:
|
||||||
|
|
||||||
|
| Setting | Value |
|
||||||
|
|---|---|
|
||||||
|
| Name | Login POST flood |
|
||||||
|
| Expression | `(http.request.method eq "POST" and http.request.uri.path in {"/admin/log-in" "/users/log-in"})` |
|
||||||
|
| Characteristic | IP |
|
||||||
|
| Period | 10 seconds |
|
||||||
|
| Requests | 10 |
|
||||||
|
| Action | Block |
|
||||||
|
| Duration | 10 seconds |
|
||||||
|
|
||||||
|
Because the free plan only offers a 10-second period and a 10-second block, this
|
||||||
|
is a burst limiter rather than a lasting ban. An attacker can retry after ten
|
||||||
|
seconds, but the application still stops that login after five failures and that
|
||||||
|
address after ten failures within fifteen minutes. A slow attacker staying under
|
||||||
|
10 requests per 10 seconds never gets to make useful guesses because of the app
|
||||||
|
throttle.
|
||||||
|
|
||||||
|
Bot Fight Mode is enabled as the plan-level bot control. If the plan later gains
|
||||||
|
longer rate-limit windows or managed WAF rules, raise the block duration and
|
||||||
|
consider a broader site-wide rule, such as 100 requests per 10 seconds per IP
|
||||||
|
with a managed challenge. Use Under Attack Mode during an active incident.
|
||||||
|
|
||||||
|
### Registration cannot be limited this way
|
||||||
|
|
||||||
|
`/users/register` is a LiveView. The form submit is a LiveView event sent over
|
||||||
|
the shared `/live/websocket` connection, not a `POST /users/register` request.
|
||||||
|
Cloudflare therefore cannot count account creations with a rule on the
|
||||||
|
registration path.
|
||||||
|
|
||||||
|
A Cloudflare rule on `GET /users/register` only limits page opens; a bot can
|
||||||
|
open one page and submit many registrations over the socket. If registration
|
||||||
|
spam becomes a problem, add an application-level registration throttle keyed by
|
||||||
|
`ChesstrainerWeb.ClientAddress.from_socket/1`, and/or add Cloudflare Turnstile
|
||||||
|
to the form.
|
||||||
|
|
||||||
|
While `PRELAUNCH=true`, registration is blocked entirely by the prelaunch plug
|
||||||
|
and LiveView mount redirect.
|
||||||
|
|
||||||
|
## 4. Why not fail2ban for HTTP?
|
||||||
|
|
||||||
|
fail2ban needs the raw client address to build a firewall rule. The application
|
||||||
|
deliberately logs only a boot-scoped HMAC, and this deployment sits behind
|
||||||
|
Cloudflare. Banning the address that reaches the origin would ban Cloudflare
|
||||||
|
edges, not attackers.
|
||||||
|
|
||||||
|
fail2ban remains useful for services that terminate connections directly on the
|
||||||
|
VPS, such as SSH. It is not part of the HTTP login defence.
|
||||||
@@ -4,11 +4,14 @@ defmodule Chesstrainer.Accounts do
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import Ecto.Query, warn: false
|
import Ecto.Query, warn: false
|
||||||
|
require Logger
|
||||||
alias Chesstrainer.Repo
|
alias Chesstrainer.Repo
|
||||||
|
|
||||||
alias Chesstrainer.Accounts.{User, UserToken, UserNotifier}
|
alias Chesstrainer.Accounts.{Policy, Role, Scope, User, UserToken, UserNotifier}
|
||||||
alias Chesstrainer.MailingList
|
alias Chesstrainer.MailingList
|
||||||
|
|
||||||
|
@admin_users_per_page 25
|
||||||
|
|
||||||
## Database getters
|
## Database getters
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
@@ -165,6 +168,308 @@ defmodule Chesstrainer.Accounts do
|
|||||||
|> Repo.update()
|
|> Repo.update()
|
||||||
end
|
end
|
||||||
|
|
||||||
|
## Admin user management
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Returns a page of users the scope may administer, newest first.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
|
||||||
|
* `:search` - case-insensitive match on email or username
|
||||||
|
* `:page` - 1-based page number (defaults to 1)
|
||||||
|
* `:per_page` - page size (defaults to 25, capped at 100)
|
||||||
|
|
||||||
|
Admins only see members and moderators; super admins see every role.
|
||||||
|
Returns `{:error, :unauthorized}` when the scope lacks user management.
|
||||||
|
"""
|
||||||
|
def list_users_for_admin(scope, opts \\ []) do
|
||||||
|
with :ok <- ensure_manage_users(scope) do
|
||||||
|
page = normalize_page(Keyword.get(opts, :page, 1))
|
||||||
|
per_page = normalize_per_page(Keyword.get(opts, :per_page, @admin_users_per_page))
|
||||||
|
offset = (page - 1) * per_page
|
||||||
|
|
||||||
|
users =
|
||||||
|
scope
|
||||||
|
|> admin_users_query(opts)
|
||||||
|
|> order_by([u], desc: u.inserted_at, desc: u.id)
|
||||||
|
|> limit(^per_page)
|
||||||
|
|> offset(^offset)
|
||||||
|
|> Repo.all()
|
||||||
|
|
||||||
|
{:ok, users}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Counts the users visible to the scope, using the same filters as
|
||||||
|
`list_users_for_admin/2`.
|
||||||
|
"""
|
||||||
|
def count_users_for_admin(scope, opts \\ []) do
|
||||||
|
with :ok <- ensure_manage_users(scope) do
|
||||||
|
count =
|
||||||
|
scope
|
||||||
|
|> admin_users_query(opts)
|
||||||
|
|> select([u], count(u.id))
|
||||||
|
|> Repo.one()
|
||||||
|
|
||||||
|
{:ok, count}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Fetches a user for the admin detail page.
|
||||||
|
|
||||||
|
Returns `{:error, :unauthorized}` when the scope may not view the target and
|
||||||
|
`{:error, :not_found}` for an unknown id.
|
||||||
|
"""
|
||||||
|
def get_user_for_admin(scope, id) do
|
||||||
|
with :ok <- ensure_manage_users(scope) do
|
||||||
|
case fetch_user(id) do
|
||||||
|
nil ->
|
||||||
|
{:error, :not_found}
|
||||||
|
|
||||||
|
%User{} = user ->
|
||||||
|
if Policy.can_view_user?(scope, user) do
|
||||||
|
{:ok, user}
|
||||||
|
else
|
||||||
|
{:error, :unauthorized}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Returns an `%Ecto.Changeset{}` for the admin-editable fields (role and plan).
|
||||||
|
"""
|
||||||
|
def change_user_as_admin(%User{} = user, attrs \\ %{}) do
|
||||||
|
User.admin_changeset(user, attrs)
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Updates a user's role and plan after enforcing the admin capability matrix.
|
||||||
|
|
||||||
|
The last-super-admin check runs inside the update transaction with a row lock,
|
||||||
|
so concurrent demotions cannot remove the final super admin.
|
||||||
|
|
||||||
|
Returns `{:error, :unauthorized}`, `{:error, :own_role}`,
|
||||||
|
`{:error, :last_super_admin}` or `{:error, %Ecto.Changeset{}}` instead of
|
||||||
|
raising.
|
||||||
|
"""
|
||||||
|
def update_user_as_admin(scope, %User{} = user, attrs) do
|
||||||
|
changeset = User.admin_changeset(user, attrs)
|
||||||
|
role_change = Ecto.Changeset.get_change(changeset, :role)
|
||||||
|
|
||||||
|
with :ok <- ensure_manage_users(scope),
|
||||||
|
:ok <- ensure_not_own_role_change(scope, user, role_change),
|
||||||
|
:ok <- ensure_can_manage_user(scope, user),
|
||||||
|
:ok <- ensure_can_assign_role(scope, role_change),
|
||||||
|
{:ok, updated} <- persist_user_changes(user, changeset) do
|
||||||
|
log_user_update(scope, user, changeset)
|
||||||
|
{:ok, updated}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Creates an invitation and emails the recipient a link to choose a password.
|
||||||
|
|
||||||
|
The account is confirmed but has no password until the invitee follows the
|
||||||
|
link. `invite_url_fun` receives the encoded token and must return a URL.
|
||||||
|
"""
|
||||||
|
def invite_user_as_admin(scope, attrs, invite_url_fun)
|
||||||
|
when is_function(invite_url_fun, 1) do
|
||||||
|
role = normalize_role(role_param(attrs) || :member)
|
||||||
|
|
||||||
|
with :ok <- ensure_manage_users(scope),
|
||||||
|
:ok <- ensure_can_assign_role(scope, role) do
|
||||||
|
changeset =
|
||||||
|
%User{}
|
||||||
|
|> User.invite_changeset(attrs)
|
||||||
|
|> User.admin_changeset(attrs)
|
||||||
|
|
||||||
|
case Repo.insert(changeset) do
|
||||||
|
{:ok, user} ->
|
||||||
|
Logger.info("admin.user.invited",
|
||||||
|
actor_id: scope.user.id,
|
||||||
|
target_id: user.id,
|
||||||
|
fields: [:invite]
|
||||||
|
)
|
||||||
|
|
||||||
|
case deliver_invite_instructions(user, invite_url_fun) do
|
||||||
|
{:ok, _email} -> {:ok, user}
|
||||||
|
{:error, reason} -> {:error, reason}
|
||||||
|
end
|
||||||
|
|
||||||
|
{:error, changeset} ->
|
||||||
|
{:error, changeset}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Sends a password-reset email on behalf of an administrator.
|
||||||
|
|
||||||
|
Uses the same policy as the editable user screen: an admin cannot trigger a
|
||||||
|
reset for another admin or a super admin.
|
||||||
|
"""
|
||||||
|
def send_user_reset_password_instructions_as_admin(scope, %User{} = user, reset_url_fun)
|
||||||
|
when is_function(reset_url_fun, 1) do
|
||||||
|
with :ok <- ensure_manage_users(scope),
|
||||||
|
:ok <- ensure_can_manage_user(scope, user) do
|
||||||
|
case deliver_user_reset_password_instructions(user, reset_url_fun) do
|
||||||
|
{:ok, email} ->
|
||||||
|
Logger.info("admin.user.password_reset_sent",
|
||||||
|
actor_id: scope.user.id,
|
||||||
|
target_id: user.id
|
||||||
|
)
|
||||||
|
|
||||||
|
{:ok, email}
|
||||||
|
|
||||||
|
error ->
|
||||||
|
error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Resends the account-confirmation email on behalf of an administrator.
|
||||||
|
"""
|
||||||
|
def resend_user_confirmation_instructions_as_admin(scope, %User{} = user, confirmation_url_fun)
|
||||||
|
when is_function(confirmation_url_fun, 1) do
|
||||||
|
with :ok <- ensure_manage_users(scope),
|
||||||
|
:ok <- ensure_can_manage_user(scope, user) do
|
||||||
|
case deliver_user_confirmation_instructions(user, confirmation_url_fun) do
|
||||||
|
{:ok, email} ->
|
||||||
|
Logger.info("admin.user.confirmation_resent",
|
||||||
|
actor_id: scope.user.id,
|
||||||
|
target_id: user.id
|
||||||
|
)
|
||||||
|
|
||||||
|
{:ok, email}
|
||||||
|
|
||||||
|
error ->
|
||||||
|
error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp admin_users_query(scope, opts) do
|
||||||
|
roles = Policy.visible_roles(scope)
|
||||||
|
search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim()
|
||||||
|
|
||||||
|
query = from(u in User, where: u.role in ^roles)
|
||||||
|
|
||||||
|
if search == "" do
|
||||||
|
query
|
||||||
|
else
|
||||||
|
pattern = "%#{search}%"
|
||||||
|
|
||||||
|
where(
|
||||||
|
query,
|
||||||
|
[u],
|
||||||
|
ilike(u.email, ^pattern) or ilike(u.username, ^pattern)
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp persist_user_changes(user, changeset) do
|
||||||
|
Repo.transact(fn ->
|
||||||
|
with :ok <- ensure_not_last_super_admin(user, changeset),
|
||||||
|
{:ok, updated} <- Repo.update(changeset) do
|
||||||
|
{:ok, updated}
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_not_last_super_admin(%User{role: :super_admin}, changeset) do
|
||||||
|
case Ecto.Changeset.get_change(changeset, :role) do
|
||||||
|
role when role in [nil, :super_admin] ->
|
||||||
|
:ok
|
||||||
|
|
||||||
|
_role ->
|
||||||
|
super_admins =
|
||||||
|
Repo.all(from(u in User, where: u.role == :super_admin, lock: "FOR UPDATE"))
|
||||||
|
|
||||||
|
if length(super_admins) <= 1 do
|
||||||
|
{:error, :last_super_admin}
|
||||||
|
else
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_not_last_super_admin(_user, _changeset), do: :ok
|
||||||
|
|
||||||
|
defp log_user_update(scope, user, changeset) do
|
||||||
|
fields = changeset.changes |> Map.keys() |> Enum.sort()
|
||||||
|
|
||||||
|
if fields != [] do
|
||||||
|
Logger.info("admin.user.updated",
|
||||||
|
actor_id: scope.user.id,
|
||||||
|
target_id: user.id,
|
||||||
|
fields: fields
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp deliver_invite_instructions(user, invite_url_fun) do
|
||||||
|
{encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
|
||||||
|
Repo.insert!(user_token)
|
||||||
|
UserNotifier.deliver_invite_instructions(user, invite_url_fun.(encoded_token))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_manage_users(scope) do
|
||||||
|
if Policy.can?(scope, :manage_users), do: :ok, else: {:error, :unauthorized}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_can_manage_user(scope, user) do
|
||||||
|
if Policy.can_manage_user?(scope, user), do: :ok, else: {:error, :unauthorized}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_can_assign_role(_scope, nil), do: :ok
|
||||||
|
|
||||||
|
defp ensure_can_assign_role(scope, role) do
|
||||||
|
if Policy.can_assign_role?(scope, role), do: :ok, else: {:error, :unauthorized}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp ensure_not_own_role_change(%Scope{user: %User{id: id}}, %User{id: id}, role)
|
||||||
|
when not is_nil(role),
|
||||||
|
do: {:error, :own_role}
|
||||||
|
|
||||||
|
defp ensure_not_own_role_change(_scope, _user, _role), do: :ok
|
||||||
|
|
||||||
|
defp fetch_user(id) do
|
||||||
|
Repo.get(User, id)
|
||||||
|
rescue
|
||||||
|
Ecto.Query.CastError -> nil
|
||||||
|
end
|
||||||
|
|
||||||
|
defp role_param(attrs), do: Map.get(attrs, "role") || Map.get(attrs, :role)
|
||||||
|
|
||||||
|
defp normalize_role(role) do
|
||||||
|
cond do
|
||||||
|
role in Role.values() -> role
|
||||||
|
is_binary(role) -> Enum.find(Role.values(), &(Atom.to_string(&1) == role))
|
||||||
|
true -> nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp normalize_page(page) when is_integer(page) and page > 0, do: page
|
||||||
|
|
||||||
|
defp normalize_page(page) when is_binary(page) do
|
||||||
|
case Integer.parse(page) do
|
||||||
|
{number, ""} when number > 0 -> number
|
||||||
|
_ -> 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp normalize_page(_page), do: 1
|
||||||
|
|
||||||
|
defp normalize_per_page(per_page) when is_integer(per_page) and per_page > 0 do
|
||||||
|
min(per_page, 100)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp normalize_per_page(_per_page), do: @admin_users_per_page
|
||||||
|
|
||||||
## Settings
|
## Settings
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
|
|||||||
@@ -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`.
|
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]
|
@values [:member, :moderator, :admin, :super_admin]
|
||||||
|
|
||||||
@ranks %{
|
@ranks %{
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.Scope do
|
|||||||
|
|
||||||
defstruct user: nil
|
defstruct user: nil
|
||||||
|
|
||||||
|
@type t :: %__MODULE__{user: User.t() | nil}
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
Creates a scope for the given user.
|
Creates a scope for the given user.
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.User do
|
|||||||
timestamps(type: :utc_datetime)
|
timestamps(type: :utc_datetime)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@type t :: %__MODULE__{}
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
A user changeset for registration.
|
A user changeset for registration.
|
||||||
|
|
||||||
@@ -53,6 +55,32 @@ defmodule Chesstrainer.Accounts.User do
|
|||||||
|> validate_required([:role])
|
|> validate_required([:role])
|
||||||
end
|
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 """
|
@doc """
|
||||||
A user changeset for registering or changing the email.
|
A user changeset for registering or changing the email.
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,31 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
|||||||
""")
|
""")
|
||||||
end
|
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 """
|
@doc """
|
||||||
Deliver instructions to reset a user password.
|
Deliver instructions to reset a user password.
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ defmodule Chesstrainer.Application do
|
|||||||
# Start a worker by calling: Chesstrainer.Worker.start_link(arg)
|
# Start a worker by calling: Chesstrainer.Worker.start_link(arg)
|
||||||
# {Chesstrainer.Worker, arg},
|
# {Chesstrainer.Worker, arg},
|
||||||
Chesstrainer.GuestLimits,
|
Chesstrainer.GuestLimits,
|
||||||
|
ChesstrainerWeb.LoginThrottle,
|
||||||
# Start to serve requests, typically the last entry
|
# Start to serve requests, typically the last entry
|
||||||
ChesstrainerWeb.Endpoint,
|
ChesstrainerWeb.Endpoint,
|
||||||
{Registry, keys: :unique, name: Chesstrainer.CacheRegistry},
|
{Registry, keys: :unique, name: Chesstrainer.CacheRegistry},
|
||||||
|
|||||||
@@ -21,6 +21,43 @@ defmodule Chesstrainer.Themes do
|
|||||||
Repo.all(Theme)
|
Repo.all(Theme)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Lists themes for the admin index with their endgame usage count.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
|
||||||
|
* `:search` - case-insensitive match on the theme name
|
||||||
|
* `:category` - one of `:endgame`, `:opening`, `:tactic`, or blank for all
|
||||||
|
|
||||||
|
Returns `{theme, usage_count}` tuples sorted by name.
|
||||||
|
"""
|
||||||
|
def list_themes_for_admin(opts \\ []) do
|
||||||
|
search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim()
|
||||||
|
category = normalize_category(Keyword.get(opts, :category, ""))
|
||||||
|
|
||||||
|
query = from(t in Theme, order_by: [asc: t.name])
|
||||||
|
|
||||||
|
query =
|
||||||
|
if search == "" do
|
||||||
|
query
|
||||||
|
else
|
||||||
|
where(query, [t], ilike(t.name, ^"%#{search}%"))
|
||||||
|
end
|
||||||
|
|
||||||
|
query =
|
||||||
|
if category do
|
||||||
|
where(query, [t], t.category == ^category)
|
||||||
|
else
|
||||||
|
query
|
||||||
|
end
|
||||||
|
|
||||||
|
query
|
||||||
|
|> join(:left, [t], j in "endgames_themes", on: j.theme_id == t.id)
|
||||||
|
|> group_by([t], t.id)
|
||||||
|
|> select([t, j], {t, count(j.endgame_id)})
|
||||||
|
|> Repo.all()
|
||||||
|
end
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
Gets a single theme.
|
Gets a single theme.
|
||||||
|
|
||||||
@@ -153,4 +190,13 @@ defmodule Chesstrainer.Themes do
|
|||||||
def names(themes) when is_list(themes) do
|
def names(themes) when is_list(themes) do
|
||||||
themes |> Enum.map(& &1.name) |> Enum.sort()
|
themes |> Enum.map(& &1.name) |> Enum.sort()
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defp normalize_category(category) when category in [:endgame, :opening, :tactic],
|
||||||
|
do: category
|
||||||
|
|
||||||
|
defp normalize_category(category) when is_binary(category) do
|
||||||
|
Enum.find([:endgame, :opening, :tactic], &(Atom.to_string(&1) == category))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp normalize_category(_category), do: nil
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -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
|
use ChesstrainerWeb, :html
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Policy
|
||||||
alias Chesstrainer.Accounts.Role
|
alias Chesstrainer.Accounts.Role
|
||||||
alias Chesstrainer.Accounts.Scope
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
|
||||||
@@ -133,6 +134,42 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
"""
|
"""
|
||||||
end
|
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
|
defp nav_links(scope) do
|
||||||
marketing =
|
marketing =
|
||||||
if Scope.premium?(scope) do
|
if Scope.premium?(scope) do
|
||||||
@@ -187,6 +224,7 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
<a href="/privacy">Privacy Policy</a>
|
<a href="/privacy">Privacy Policy</a>
|
||||||
<a href="/terms-conditions">Terms & Conditions</a>
|
<a href="/terms-conditions">Terms & Conditions</a>
|
||||||
<a href="/mentions-legales">Mentions légales</a>
|
<a href="/mentions-legales">Mentions légales</a>
|
||||||
|
<a href="/sitemap.xml">Sitemap</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<small>© {@year} {Branding.name()}</small>
|
<small>© {@year} {Branding.name()}</small>
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
defmodule ChesstrainerWeb.UserSessionController do
|
defmodule ChesstrainerWeb.UserSessionController do
|
||||||
use ChesstrainerWeb, :controller
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
|
require Logger
|
||||||
|
|
||||||
alias Chesstrainer.Accounts
|
alias Chesstrainer.Accounts
|
||||||
|
alias ChesstrainerWeb.ClientAddress
|
||||||
|
alias ChesstrainerWeb.LoginThrottle
|
||||||
alias ChesstrainerWeb.UserAuth
|
alias ChesstrainerWeb.UserAuth
|
||||||
|
|
||||||
def create(conn, %{"user" => user_params}) do
|
def create(conn, %{"user" => user_params}) do
|
||||||
@@ -17,30 +21,76 @@ defmodule ChesstrainerWeb.UserSessionController do
|
|||||||
end
|
end
|
||||||
|
|
||||||
defp authenticate(conn, user_params, failure_path, success_path) do
|
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
|
%{"email" => login, "password" => password} = user_params
|
||||||
|
|
||||||
case Accounts.get_user_by_login_and_password(login, password) do
|
case Accounts.get_user_by_login_and_password(login, password) do
|
||||||
nil ->
|
nil ->
|
||||||
invalid_credentials(conn, login, failure_path)
|
authentication_failed(conn, address, login, :invalid_credentials, failure_path)
|
||||||
|
|
||||||
user ->
|
user ->
|
||||||
if user.confirmed_at do
|
if user.confirmed_at do
|
||||||
|
LoginThrottle.record_success(login)
|
||||||
|
|
||||||
conn
|
conn
|
||||||
|> maybe_put_return_to(success_path)
|
|> maybe_put_return_to(success_path)
|
||||||
|> put_flash(:info, "Welcome back!")
|
|> put_flash(:info, "Welcome back!")
|
||||||
|> UserAuth.log_in_user(user, user_params)
|
|> UserAuth.log_in_user(user, user_params)
|
||||||
else
|
else
|
||||||
{:ok, _} =
|
maybe_resend_confirmation(user, login)
|
||||||
Accounts.deliver_user_confirmation_instructions(
|
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,
|
user,
|
||||||
&url(~p"/users/confirm/#{&1}")
|
&url(~p"/users/confirm/#{&1}")
|
||||||
)
|
) do
|
||||||
|
{:ok, _email} -> :ok
|
||||||
|
{:error, _reason} -> Logger.warning("auth.confirmation.resend_failed")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
# In order to prevent user enumeration attacks, report the same error
|
:ok
|
||||||
# as invalid credentials.
|
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)
|
invalid_credentials(conn, login, failure_path)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defp log_auth_event(message, address, metadata) do
|
||||||
|
Logger.warning(message, Keyword.put(metadata, :ip, LoginThrottle.fingerprint(address)))
|
||||||
end
|
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
|
end
|
||||||
|
|
||||||
defp invalid_credentials(conn, login, path) do
|
defp invalid_credentials(conn, login, path) do
|
||||||
|
|||||||
@@ -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
|
def render(assigns) do
|
||||||
~H"""
|
~H"""
|
||||||
<Layouts.app flash={@flash}>
|
<Layouts.app flash={@flash}>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
<.header>
|
<.header>
|
||||||
{@page_title}
|
{@page_title}
|
||||||
<:subtitle>Use this form to manage endgame records in your database.</:subtitle>
|
<: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…"
|
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}>
|
<li :for={theme <- @theme_results}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
|||||||
|
|
||||||
alias Chesstrainer.Endgames
|
alias Chesstrainer.Endgames
|
||||||
alias Chesstrainer.GuestLimits
|
alias Chesstrainer.GuestLimits
|
||||||
|
alias ChesstrainerWeb.ClientAddress
|
||||||
alias ChesstrainerWeb.EndgameLive.PlayCore
|
alias ChesstrainerWeb.EndgameLive.PlayCore
|
||||||
alias ChesstrainerWeb.PlayComponents
|
alias ChesstrainerWeb.PlayComponents
|
||||||
|
|
||||||
@@ -112,7 +113,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
|||||||
{:ok, redirect(socket, to: ~p"/train")}
|
{:ok, redirect(socket, to: ~p"/train")}
|
||||||
|
|
||||||
connected?(socket) ->
|
connected?(socket) ->
|
||||||
take_puzzle(socket, client_address(socket))
|
take_puzzle(socket, ClientAddress.from_socket(socket))
|
||||||
|
|
||||||
true ->
|
true ->
|
||||||
{:ok,
|
{:ok,
|
||||||
@@ -222,46 +223,6 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
|||||||
end
|
end
|
||||||
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
|
defp signed_in?(socket) do
|
||||||
case socket.assigns.current_scope do
|
case socket.assigns.current_scope do
|
||||||
%{user: %{}} -> true
|
%{user: %{}} -> true
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
|
|||||||
def render(assigns) do
|
def render(assigns) do
|
||||||
~H"""
|
~H"""
|
||||||
<Layouts.app flash={@flash} wide>
|
<Layouts.app flash={@flash} wide>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
<.header>
|
<.header>
|
||||||
Listing Endgames
|
Listing Endgames
|
||||||
<:actions>
|
<:actions>
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
|
|||||||
|
|
||||||
~H"""
|
~H"""
|
||||||
<Layouts.app flash={@flash} wide>
|
<Layouts.app flash={@flash} wide>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
<.header>
|
<.header>
|
||||||
Endgame {@endgame.id}
|
Endgame {@endgame.id}
|
||||||
<:subtitle>This is a endgame record from your database.</:subtitle>
|
<:subtitle>This is a endgame record from your database.</:subtitle>
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -43,7 +43,7 @@ defmodule ChesstrainerWeb.Router do
|
|||||||
scope "/admin", ChesstrainerWeb do
|
scope "/admin", ChesstrainerWeb do
|
||||||
pipe_through [:browser, :noindex, :require_admin_user]
|
pipe_through [:browser, :noindex, :require_admin_user]
|
||||||
|
|
||||||
live_session :endgames,
|
live_session :admin,
|
||||||
on_mount: [
|
on_mount: [
|
||||||
{ChesstrainerWeb.UserAuth, :enforce_prelaunch},
|
{ChesstrainerWeb.UserAuth, :enforce_prelaunch},
|
||||||
{ChesstrainerWeb.UserAuth, :require_admin}
|
{ChesstrainerWeb.UserAuth, :require_admin}
|
||||||
@@ -52,6 +52,14 @@ defmodule ChesstrainerWeb.Router do
|
|||||||
live "/endgames/new", EndgameLive.Form, :new
|
live "/endgames/new", EndgameLive.Form, :new
|
||||||
live "/endgames/:id", EndgameLive.Show, :show
|
live "/endgames/:id", EndgameLive.Show, :show
|
||||||
live "/endgames/:id/edit", EndgameLive.Form, :edit
|
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
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -218,7 +218,12 @@ defmodule ChesstrainerWeb.UserAuth do
|
|||||||
ChesstrainerWeb.UserLive.Profile,
|
ChesstrainerWeb.UserLive.Profile,
|
||||||
ChesstrainerWeb.EndgameLive.Index,
|
ChesstrainerWeb.EndgameLive.Index,
|
||||||
ChesstrainerWeb.EndgameLive.Form,
|
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
|
def on_mount(:enforce_prelaunch, _params, _session, socket) do
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ defmodule Mix.Tasks.Accounts.Promote do
|
|||||||
Roles, from least to most authority: `member`, `moderator`, `admin`,
|
Roles, from least to most authority: `member`, `moderator`, `admin`,
|
||||||
`super_admin`.
|
`super_admin`.
|
||||||
|
|
||||||
Role changes are deliberately CLI-only for now; there is no admin UI.
|
This task remains the CLI fallback for bootstrapping a role. Once an admin
|
||||||
|
exists, roles and plans can also be managed at `/admin/users`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@impl Mix.Task
|
@impl Mix.Task
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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"/"
|
assert redirected_to(conn) == ~p"/"
|
||||||
end
|
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
|
test "admins are admitted", %{conn: conn} do
|
||||||
{:ok, user} = Accounts.update_user_role(user_fixture(), :admin)
|
{: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
|
defmodule ChesstrainerWeb.UserSessionControllerTest do
|
||||||
use ChesstrainerWeb.ConnCase, async: true
|
use ChesstrainerWeb.ConnCase, async: false
|
||||||
|
|
||||||
|
@moduletag :capture_log
|
||||||
|
|
||||||
import Chesstrainer.AccountsFixtures
|
import Chesstrainer.AccountsFixtures
|
||||||
|
import ExUnit.CaptureLog
|
||||||
import Swoosh.TestAssertions
|
import Swoosh.TestAssertions
|
||||||
|
|
||||||
|
alias ChesstrainerWeb.LoginThrottle
|
||||||
|
|
||||||
setup do
|
setup do
|
||||||
|
LoginThrottle.reset()
|
||||||
%{user: user_fixture()}
|
%{user: user_fixture()}
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -77,7 +83,7 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
|
|||||||
assert redirected_to(conn) == ~p"/users/log-in"
|
assert redirected_to(conn) == ~p"/users/log-in"
|
||||||
end
|
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
|
conn: conn
|
||||||
} do
|
} do
|
||||||
user = unconfirmed_user_fixture()
|
user = unconfirmed_user_fixture()
|
||||||
@@ -94,6 +100,146 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
|
|||||||
|
|
||||||
assert redirected_to(conn) == ~p"/users/log-in"
|
assert redirected_to(conn) == ~p"/users/log-in"
|
||||||
assert_email_sent(subject: "Confirmation instructions")
|
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
|
||||||
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'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
|
defmodule ChesstrainerWeb.UserLive.LoginTest do
|
||||||
use ChesstrainerWeb.ConnCase, async: true
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
|
@moduletag :capture_log
|
||||||
|
|
||||||
import Phoenix.LiveViewTest
|
import Phoenix.LiveViewTest
|
||||||
import Chesstrainer.AccountsFixtures
|
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
|
||||||
Reference in New Issue
Block a user