mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
2
Commits
202b9b1f6a
...
9e76045862
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e76045862 | ||
|
|
624ddab644 |
@@ -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
|
||||||
|
|||||||
+27
-4
@@ -3,13 +3,36 @@
|
|||||||
# 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 {
|
||||||
redir https://innersquare.app{uri} permanent
|
redir https://innersquare.app{uri} permanent
|
||||||
}
|
}
|
||||||
|
|||||||
+511
-42
@@ -4,9 +4,10 @@ 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)
|
||||||
└─ Phoenix release 127.0.0.1:4100
|
└─ Caddy :443 (cloudflare ranges only)
|
||||||
└─ Postgres 127.0.0.1:5432
|
└─ Phoenix release 127.0.0.1:4100
|
||||||
|
└─ Postgres 127.0.0.1:5432
|
||||||
```
|
```
|
||||||
|
|
||||||
## Pinned versions
|
## Pinned versions
|
||||||
@@ -102,6 +103,9 @@ also `root:root` and `0600`.
|
|||||||
The app runs as the dedicated `chesstrainer` system user. It must own
|
The app runs as the dedicated `chesstrainer` system user. It must own
|
||||||
`/opt/chesstrainer` so it can write `priv/static/backups`.
|
`/opt/chesstrainer` so it can write `priv/static/backups`.
|
||||||
|
|
||||||
|
Database dumps live in `/var/backups/chesstrainer`, outside `/opt/chesstrainer`
|
||||||
|
and `priv/static`. See §Backups.
|
||||||
|
|
||||||
## Copy the deploy artifacts
|
## Copy the deploy artifacts
|
||||||
|
|
||||||
Run these commands from a checkout of this repo on the VPS, or copy the
|
Run these commands from a checkout of this repo on the VPS, or copy the
|
||||||
@@ -440,15 +444,34 @@ The unit includes `ConditionPathExists=/opt/chesstrainer/current/bin/server`, so
|
|||||||
it is safe to enable before the first release. systemd skips it until a release
|
it is safe to enable before the first release. systemd skips it until a release
|
||||||
is in place.
|
is in place.
|
||||||
|
|
||||||
|
The backup unit and timer are installed separately; see §Backups.
|
||||||
|
|
||||||
## 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 +479,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 +556,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.
|
||||||
@@ -510,12 +606,13 @@ The script:
|
|||||||
|
|
||||||
1. Extracts into `/opt/chesstrainer/releases/<timestamp>`
|
1. Extracts into `/opt/chesstrainer/releases/<timestamp>`
|
||||||
2. Fixes ownership
|
2. Fixes ownership
|
||||||
3. Flips `/opt/chesstrainer/current`
|
3. Takes a verified pre-deploy database dump, aborting if it fails (see §Backups)
|
||||||
4. Restarts `chesstrainer.service`
|
4. Flips `/opt/chesstrainer/current`
|
||||||
5. Migrations run via `ExecStartPre`
|
5. Restarts `chesstrainer.service`
|
||||||
6. Polls `/health`
|
6. Migrations run via `ExecStartPre`
|
||||||
7. Rolls back to the previous release on failure
|
7. Polls `/health`
|
||||||
8. Prunes old releases, keeping 5 by default
|
8. Rolls back to the previous release on failure
|
||||||
|
9. Prunes old releases, keeping 5 by default
|
||||||
|
|
||||||
Verify locally before touching Caddy:
|
Verify locally before touching Caddy:
|
||||||
|
|
||||||
@@ -550,6 +647,10 @@ KEEP_RELEASES=5 \
|
|||||||
sudo -E /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
|
sudo -E /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Every activation takes a verified pre-deploy dump before migrations run. If
|
||||||
|
Postgres is intentionally unavailable and you accept the risk, add
|
||||||
|
`SKIP_PRE_DEPLOY_BACKUP=1` to the override list; see §Backups.
|
||||||
|
|
||||||
## GitHub Actions CD
|
## GitHub Actions CD
|
||||||
|
|
||||||
Merging to `main` (or running the workflow manually) tests, builds, uploads,
|
Merging to `main` (or running the workflow manually) tests, builds, uploads,
|
||||||
@@ -613,7 +714,8 @@ The workflow:
|
|||||||
1. Runs `mix precommit` against Postgres.
|
1. Runs `mix precommit` against Postgres.
|
||||||
2. Builds the release artifact on `ubuntu-24.04`.
|
2. Builds the release artifact on `ubuntu-24.04`.
|
||||||
3. On `main` or `workflow_dispatch`, uploads the tarball, installs the SSH key,
|
3. On `main` or `workflow_dispatch`, uploads the tarball, installs the SSH key,
|
||||||
runs `sudo -n .../activate`, and performs public smoke checks.
|
runs `sudo -n .../activate`, and performs public smoke checks. Activation
|
||||||
|
takes a pre-deploy dump first and fails if it cannot.
|
||||||
4. A failed activation health check rolls back to the previous release.
|
4. A failed activation health check rolls back to the previous release.
|
||||||
|
|
||||||
Manual dispatch is available from the Actions UI or:
|
Manual dispatch is available from the Actions UI or:
|
||||||
@@ -636,6 +738,10 @@ sudo /opt/chesstrainer/src/deploy/rollback 20261109120000
|
|||||||
|
|
||||||
The script flips `current`, restarts the service, and checks `/health`.
|
The script flips `current`, restarts the service, and checks `/health`.
|
||||||
|
|
||||||
|
Rollback reverts the release, not the database: migrations are not reversed. If
|
||||||
|
a migration changed data, restore the matching pre-deploy dump instead; see
|
||||||
|
§Backups.
|
||||||
|
|
||||||
## Logs and health
|
## Logs and health
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -694,54 +800,409 @@ 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
|
Backups are produced on the VPS, encrypted there, and pulled to a workstation.
|
||||||
image trusts locally, so `pg_dump` needs no password. Run it as the owner
|
Nothing leaves the VPS unencrypted, and the VPS never holds the key that could
|
||||||
(`chesstrainer`), not `chesstrainer_ro`: a full dump also needs sequence access
|
read the archives.
|
||||||
and ownership information.
|
|
||||||
|
|
||||||
Take a compressed logical backup (custom format, restorable with `pg_restore`):
|
### What runs
|
||||||
|
|
||||||
|
| Where | What | When | Retention |
|
||||||
|
|---|---|---|---|
|
||||||
|
| VPS | `chesstrainer-backup.timer` → `chesstrainer-backup.service` | daily 03:15 UTC, `Persistent=true`, 5 min jitter | 3 days plaintext, 14 days encrypted |
|
||||||
|
| VPS | the same script, called by `deploy/activate` | before every migration | last 5 pre-deploy sets |
|
||||||
|
| Workstation | `chesstrainer-backup-pull.timer` | daily 12:00 local, 10 min after boot | 7 daily, 4 weekly, 6 monthly |
|
||||||
|
| Workstation | `chesstrainer-backup-drill.timer` | monthly on the 1st at 09:00 | `drills.log` is never pruned |
|
||||||
|
|
||||||
|
Each run writes one JSON line (`backup.completed`, `backup.failed`,
|
||||||
|
`backup.skipped`, `pull.completed`, `pull.failed`, `pull.skipped`,
|
||||||
|
`drill.completed`, `drill.failed`) so #140's log shipping can alert on it. A
|
||||||
|
`skipped` line means another run held the lock; it is not an alarm.
|
||||||
|
|
||||||
|
### What a dump contains
|
||||||
|
|
||||||
|
- `<ts>.dump` — `pg_dump -Fc` of `chesstrainer_prod`
|
||||||
|
- `<ts>.globals.sql` — `pg_dumpall --globals-only`, enough to recreate
|
||||||
|
`chesstrainer` and `chesstrainer_ro` on a fresh cluster
|
||||||
|
- `<ts>.counts` — row counts for `users`, `endgames`, `attempts`, used by the drill
|
||||||
|
- `<ts>.sha256` — checksums for the three files above
|
||||||
|
|
||||||
|
Not backed up, by design: tablebases and the tablebase cache (both are
|
||||||
|
re-fetchable), anything under `priv/static`, and release tarballs. Dumps contain
|
||||||
|
user emails and bcrypt hashes: they are `0600 root` while plaintext, encrypted
|
||||||
|
before they leave the box, and pruned aggressively.
|
||||||
|
|
||||||
|
### RPO and RTO
|
||||||
|
|
||||||
|
RPO is 24 hours on the VPS and "the age of the newest pulled archive" off-box.
|
||||||
|
The pull runs daily, so a laptop that is off for a day leaves the newest
|
||||||
|
off-site copy around 48 hours old; the VPS keeps 14 days of encrypted archives,
|
||||||
|
which bounds how far behind the pull can fall. RTO is under an hour: create the
|
||||||
|
database, restore the newest dump, activate a release (see *Disaster recovery*).
|
||||||
|
|
||||||
|
### One-time setup: VPS
|
||||||
|
|
||||||
|
Install `age`. Encryption happens on the server; only the workstation can
|
||||||
|
decrypt.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
|
sudo apt install age
|
||||||
pg_dump -U chesstrainer -d chesstrainer_prod -Fc \
|
|
||||||
> /var/backups/chesstrainer-$(date -u +%Y%m%d%H%M%S).dump
|
|
||||||
```
|
```
|
||||||
|
|
||||||
For a plain SQL file instead (human-readable, restorable with `psql`):
|
Create the configuration file. Generate `AGE_RECIPIENT` on the workstation
|
||||||
|
first (next section) and paste the public key.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
|
sudo install -m 600 /dev/null /etc/chesstrainer/backup.env
|
||||||
pg_dump -U chesstrainer -d chesstrainer_prod \
|
sudoedit /etc/chesstrainer/backup.env
|
||||||
| gzip > /var/backups/chesstrainer-$(date -u +%Y%m%d%H%M%S).sql.gz
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Check that a custom-format dump is readable before trusting it:
|
Start from `deploy/backup.env.example`. The required values are `AGE_RECIPIENT`
|
||||||
|
and `HEALTHCHECK_URL`.
|
||||||
|
|
||||||
|
Create a healthchecks.io check with a period of 1 day and a grace time of 4
|
||||||
|
hours, then paste its ping URL into `HEALTHCHECK_URL`. The script pings it after
|
||||||
|
a good run and `<url>/fail` after a bad one, so silence means "no backup
|
||||||
|
finished", even when the VPS itself is down.
|
||||||
|
|
||||||
|
Install the script and units:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo docker exec -i chesstrainer-db pg_restore -l \
|
sudo install -m 0755 /opt/chesstrainer/src/deploy/backup \
|
||||||
< /var/backups/<timestamp>.dump > /dev/null
|
/usr/local/sbin/chesstrainer-backup
|
||||||
|
sudo install -m 0644 \
|
||||||
|
/opt/chesstrainer/src/deploy/chesstrainer-backup.service \
|
||||||
|
/opt/chesstrainer/src/deploy/chesstrainer-backup.timer \
|
||||||
|
/opt/chesstrainer/src/deploy/chesstrainer-backup-failure.service \
|
||||||
|
/etc/systemd/system/
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now chesstrainer-backup.timer
|
||||||
```
|
```
|
||||||
|
|
||||||
Restore into a scratch database (do not restore over the live database without
|
The timer runs the installed `/usr/local/sbin/chesstrainer-backup`, not the
|
||||||
stopping `chesstrainer` first):
|
copy under `/opt/chesstrainer/src`, because that tree is writable by the
|
||||||
|
application user. When `deploy/backup` changes, copy it to both places so the
|
||||||
|
timer and `deploy/activate` use the same script.
|
||||||
|
|
||||||
|
Run it once and inspect the result:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
|
sudo systemctl start chesstrainer-backup
|
||||||
createdb -U chesstrainer chesstrainer_restore
|
sudo journalctl -u chesstrainer-backup -n 20 --no-pager -o cat
|
||||||
sudo docker exec -i chesstrainer-db pg_restore -U chesstrainer \
|
sudo ls -l /var/backups/chesstrainer /var/backups/chesstrainer/offsite
|
||||||
-d chesstrainer_restore < /var/backups/<timestamp>.dump
|
systemctl list-timers chesstrainer-backup.timer
|
||||||
```
|
```
|
||||||
|
|
||||||
Example nightly entry in root's crontab (`sudo crontab -e`):
|
Expect a `.dump`, `.globals.sql`, `.counts` and `.sha256` at mode `0600`, and
|
||||||
|
one `.tar.age` in `offsite/` at mode `0644`. `offsite/` is the only thing the
|
||||||
|
workstation reads, which is why the pull needs no `sudo`. The vault directory is
|
||||||
|
`0711`, so the workstation user can traverse into `offsite/` but cannot list the
|
||||||
|
plaintext dumps.
|
||||||
|
|
||||||
```cron
|
### One-time setup: workstation
|
||||||
15 3 * * * docker compose -f /home/<username>/docker-compose.yml exec -T chesstrainer-db pg_dump -U chesstrainer -d chesstrainer_prod -Fc > /var/backups/chesstrainer-$(date +\%Y\%m\%d).dump
|
|
||||||
|
```sh
|
||||||
|
sudo apt install age rsync
|
||||||
|
mkdir -p ~/.config/chesstrainer
|
||||||
|
chmod 700 ~/.config/chesstrainer
|
||||||
|
age-keygen -o ~/.config/chesstrainer/age.key
|
||||||
|
chmod 600 ~/.config/chesstrainer/age.key
|
||||||
|
grep 'public key' ~/.config/chesstrainer/age.key
|
||||||
```
|
```
|
||||||
|
|
||||||
Keep `/var/backups` outside `/opt/chesstrainer/releases` and copy backups off
|
Copy that public key into `AGE_RECIPIENT` on the VPS. **Back up the private
|
||||||
the VPS regularly. A backup that is only on the VPS is not a backup.
|
key** (password manager, printed copy, offline disk): without it every archive
|
||||||
|
is unreadable, and the VPS deliberately cannot decrypt them.
|
||||||
|
|
||||||
|
Create the pull configuration:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
install -m 600 /dev/null ~/.config/chesstrainer/backup-pull.env
|
||||||
|
$EDITOR ~/.config/chesstrainer/backup-pull.env
|
||||||
|
```
|
||||||
|
|
||||||
|
Start from `deploy/workstation/backup-pull.env.example`. `DEST` should point at
|
||||||
|
a real disk, for example `/mnt/Mint Data/chesstrainer-backups`. The script
|
||||||
|
refuses to run when `DEST`'s parent is missing, so an unmounted disk cannot
|
||||||
|
silently fill the root filesystem.
|
||||||
|
|
||||||
|
Set `PULL_HEALTHCHECK_URL` to a second healthchecks.io check with a long period
|
||||||
|
(for example 72 hours) if you want to hear about it when the workstation stops
|
||||||
|
pulling. Leave it empty for journal-only reporting.
|
||||||
|
|
||||||
|
Install the scripts and user units:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
REPO=~/Desktop/chess-trainer # wherever this repo is cloned
|
||||||
|
|
||||||
|
install -d ~/.local/bin
|
||||||
|
install -m 0755 "$REPO/deploy/workstation/backup-pull" ~/.local/bin/chesstrainer-backup-pull
|
||||||
|
install -m 0755 "$REPO/deploy/workstation/backup-drill" ~/.local/bin/chesstrainer-backup-drill
|
||||||
|
|
||||||
|
install -d ~/.config/systemd/user
|
||||||
|
install -m 0644 \
|
||||||
|
"$REPO/deploy/workstation/chesstrainer-backup-pull.service" \
|
||||||
|
"$REPO/deploy/workstation/chesstrainer-backup-pull.timer" \
|
||||||
|
"$REPO/deploy/workstation/chesstrainer-backup-drill.service" \
|
||||||
|
"$REPO/deploy/workstation/chesstrainer-backup-drill.timer" \
|
||||||
|
"$REPO/deploy/workstation/chesstrainer-backup-alert@.service" \
|
||||||
|
~/.config/systemd/user/
|
||||||
|
|
||||||
|
systemctl --user daemon-reload
|
||||||
|
systemctl --user enable --now chesstrainer-backup-pull.timer
|
||||||
|
systemctl --user enable --now chesstrainer-backup-drill.timer
|
||||||
|
sudo loginctl enable-linger "$USER"
|
||||||
|
```
|
||||||
|
|
||||||
|
`enable-linger` lets the user timers run while the laptop is on but you are not
|
||||||
|
logged in. The pull also fires ten minutes after boot, and `Persistent=true`
|
||||||
|
catches up after the machine was off. Verify lingering stuck:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
loginctl show-user "$USER" -p Linger # Linger=yes
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the first pull and drill by hand:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
~/.local/bin/chesstrainer-backup-pull
|
||||||
|
ls -l "/mnt/Mint Data/chesstrainer-backups"
|
||||||
|
~/.local/bin/chesstrainer-backup-drill
|
||||||
|
cat "/mnt/Mint Data/chesstrainer-backups/drills.log"
|
||||||
|
```
|
||||||
|
|
||||||
|
A passing drill line looks like:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"timestamp":"2026-11-11T21:05:46Z","event":"drill.completed","archive":"20261111T120000Z.tar.age","result":"pass","counts":"users=3,endgames=42,attempts=900","duration_s":3}
|
||||||
|
```
|
||||||
|
|
||||||
|
The drill creates a throwaway `postgres:18.6` container, applies the globals
|
||||||
|
dump, asserts that `chesstrainer` and `chesstrainer_ro` exist, restores into
|
||||||
|
`chesstrainer_restore`, and compares the three row counts with the `.counts`
|
||||||
|
file from dump time. Restored counts may be higher (the counts are taken moments
|
||||||
|
before the dump); lower counts fail the drill.
|
||||||
|
|
||||||
|
### Retention
|
||||||
|
|
||||||
|
| Location | Plaintext | Encrypted | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| VPS `/var/backups/chesstrainer` | 3 days | 14 days | pre-deploy sets: last 5 |
|
||||||
|
| Workstation `DEST` | never | 7 daily, 4 weekly, 6 monthly | monthly copies outlive the VPS copies |
|
||||||
|
|
||||||
|
The VPS is a staging area for the workstation; weekly and monthly generations
|
||||||
|
accumulate there. If the laptop is off for more than 14 days, the archives the
|
||||||
|
VPS dropped in the meantime are gone — that is the documented off-site RPO
|
||||||
|
trade-off. Moving to an always-on destination (a second host or object storage
|
||||||
|
with restic) is tracked in #151.
|
||||||
|
|
||||||
|
### Restore a dump
|
||||||
|
|
||||||
|
Always restore into a scratch database first. From an archive on the
|
||||||
|
workstation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
WORK=$(mktemp -d)
|
||||||
|
age --decrypt -i ~/.config/chesstrainer/age.key \
|
||||||
|
-o "$WORK/dump.tar" \
|
||||||
|
"/mnt/Mint Data/chesstrainer-backups/<timestamp>.tar.age"
|
||||||
|
tar -xf "$WORK/dump.tar" -C "$WORK"
|
||||||
|
(cd "$WORK" && sha256sum --check --strict <timestamp>.sha256)
|
||||||
|
```
|
||||||
|
|
||||||
|
Then restore into a scratch container:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run --rm -d --name restore-check \
|
||||||
|
-e POSTGRES_PASSWORD=restore -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18.6
|
||||||
|
docker exec restore-check psql -U postgres -c 'create database chesstrainer_restore'
|
||||||
|
docker exec -i restore-check pg_restore -U postgres -d chesstrainer_restore \
|
||||||
|
--single-transaction --exit-on-error < "$WORK/<timestamp>.dump"
|
||||||
|
docker exec restore-check psql -U postgres -d chesstrainer_restore \
|
||||||
|
-c 'select count(*) from users; select count(*) from attempts;'
|
||||||
|
docker rm -f restore-check
|
||||||
|
rm -rf "$WORK"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Disaster recovery
|
||||||
|
|
||||||
|
1. Build a new VPS following this README through *First-time setup*, without
|
||||||
|
activating a release or switching Caddy.
|
||||||
|
2. Decrypt and unpack the newest archive on the workstation (above).
|
||||||
|
3. Copy the dump and globals to the new VPS:
|
||||||
|
`scp "$WORK/<timestamp>.dump" "$WORK/<timestamp>.globals.sql" <VPS_USER>@<VPS_HOST>:/tmp/`
|
||||||
|
4. Recreate the cluster roles. Connect as `chesstrainer`: it is the container's
|
||||||
|
superuser (`POSTGRES_USER`), and the dump's final grants are issued
|
||||||
|
`GRANTED BY chesstrainer`, which another role cannot replay. The line that
|
||||||
|
recreates `chesstrainer` itself reports "already exists" and is harmless:
|
||||||
|
`sudo docker exec -i chesstrainer-db psql -U chesstrainer < /tmp/<timestamp>.globals.sql`
|
||||||
|
5. Create the database and restore it:
|
||||||
|
`sudo docker exec chesstrainer-db createdb -U chesstrainer chesstrainer_prod`
|
||||||
|
`sudo docker exec -i chesstrainer-db pg_restore -U chesstrainer -d chesstrainer_prod --single-transaction --exit-on-error < /tmp/<timestamp>.dump`
|
||||||
|
6. Verify the row counts, activate a release, then restore the Caddy block.
|
||||||
|
7. Take a fresh backup (`sudo systemctl start chesstrainer-backup`) and pull so
|
||||||
|
the new VPS is covered immediately.
|
||||||
|
|
||||||
|
`pg_dump` and `pg_restore` must come from the container's Postgres 18, not the
|
||||||
|
host.
|
||||||
|
|
||||||
|
### Pre-deploy dump
|
||||||
|
|
||||||
|
`deploy/activate` calls `chesstrainer-backup` with `BACKUP_TAG=predeploy` after
|
||||||
|
extracting the release and before flipping `current`, so the state before
|
||||||
|
`bin/migrate` runs in `ExecStartPre` is always recoverable. A failed dump aborts
|
||||||
|
the activation. The escape hatch is deliberate and should be rare:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo SKIP_PRE_DEPLOY_BACKUP=1 /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
If the installed script is missing, `activate` uses the `backup` next to it; if
|
||||||
|
neither exists it refuses to activate rather than migrate without a dump. The
|
||||||
|
GitHub Actions deploy job inherits the same behaviour.
|
||||||
|
|
||||||
|
### Run it by hand
|
||||||
|
|
||||||
|
Every timer can be triggered directly. On the VPS:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# exactly what the timer runs
|
||||||
|
sudo systemctl start chesstrainer-backup
|
||||||
|
sudo journalctl -u chesstrainer-backup -n 20 -o cat
|
||||||
|
|
||||||
|
# an ad-hoc dump with its own tag
|
||||||
|
sudo BACKUP_TAG=manual /usr/local/sbin/chesstrainer-backup
|
||||||
|
|
||||||
|
# schedule, last result and last exit
|
||||||
|
systemctl list-timers chesstrainer-backup.timer
|
||||||
|
systemctl show chesstrainer-backup.service -p Result -p ExecMainExitTimestamp
|
||||||
|
```
|
||||||
|
|
||||||
|
On the workstation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# pull now, or through the unit (same PATH and OnFailure handling)
|
||||||
|
~/.local/bin/chesstrainer-backup-pull
|
||||||
|
systemctl --user start chesstrainer-backup-pull.service
|
||||||
|
|
||||||
|
# drill the newest archive, or a named one
|
||||||
|
~/.local/bin/chesstrainer-backup-drill
|
||||||
|
~/.local/bin/chesstrainer-backup-drill 20261111T213734Z.tar.age
|
||||||
|
|
||||||
|
# results and schedule
|
||||||
|
cat "/mnt/Mint Data/chesstrainer-backups/drills.log"
|
||||||
|
systemctl --user list-timers 'chesstrainer-backup-*'
|
||||||
|
```
|
||||||
|
|
||||||
|
A `backup.skipped` or `pull.skipped` line means another run held the lock; that
|
||||||
|
run reports the outcome. After fixing a failure, clear the unit with
|
||||||
|
`systemctl --user reset-failed chesstrainer-backup-pull.service` (or
|
||||||
|
`sudo systemctl reset-failed chesstrainer-backup.service`).
|
||||||
|
|
||||||
|
Enabling the pull timer fires it once straight away: its `OnBootSec=10m` is
|
||||||
|
measured from boot, so enabling it hours after boot triggers immediately. That
|
||||||
|
is expected and harmless.
|
||||||
|
|
||||||
|
### Monitoring
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl list-timers chesstrainer-backup.timer
|
||||||
|
sudo journalctl -u chesstrainer-backup --since "2 days ago" -o cat
|
||||||
|
sudo systemctl --failed
|
||||||
|
systemctl --user list-timers chesstrainer-backup-pull.timer chesstrainer-backup-drill.timer
|
||||||
|
journalctl --user -u chesstrainer-backup-pull --since "2 days ago" -o cat
|
||||||
|
```
|
||||||
|
|
||||||
|
A failed run produces both `backup.failed` (from the script) and
|
||||||
|
`backup.unit-failed` (from the `OnFailure` unit). The healthchecks.io check is
|
||||||
|
the backstop: if the VPS dies, the ping stops and you are emailed. The pull
|
||||||
|
fails when the newest archive is more than 48 hours old, which catches a stopped
|
||||||
|
VPS timer the next time the workstation pulls.
|
||||||
|
|
||||||
|
### Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Likely cause |
|
||||||
|
|---|---|
|
||||||
|
| `backup.failed: missing command: age` | `sudo apt install age` |
|
||||||
|
| `backup.failed: only N MB free` | disk full on the VPS; prune old releases or grow the disk |
|
||||||
|
| `backup.failed: pg_dump failed` | `chesstrainer-db` is down or restarting — check `docker ps` |
|
||||||
|
| `backup.failed: globals dump is missing role …` | the role was renamed; update `EXPECTED_ROLES` |
|
||||||
|
| `pull.failed: rsync … failed` | SSH key, host key, or the VPS is unreachable |
|
||||||
|
| `pull.failed: newest archive … is Nh old` | the VPS backup timer stopped; check it before touching the workstation |
|
||||||
|
| `drill.failed: pg_restore failed` | archive is corrupt; keep it for diagnosis and restore an earlier one |
|
||||||
|
|
||||||
|
Never put dumps anywhere under `priv/static` or the release directory, and never
|
||||||
|
restore over `chesstrainer_prod` while the application is running.
|
||||||
|
|
||||||
## New VPS checklist
|
## New VPS checklist
|
||||||
|
|
||||||
@@ -753,6 +1214,14 @@ 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 and tunnel verified.
|
||||||
|
11. `age` installed, `/etc/chesstrainer/backup.env` written, backup script and
|
||||||
|
units installed, timer enabled, and one manual run produces a dump plus a
|
||||||
|
globals file.
|
||||||
|
12. Workstation age key and pull configuration installed, user timers and linger
|
||||||
|
enabled, first pull verified, first drill passes.
|
||||||
|
13. Remote shell attaches and exits cleanly:
|
||||||
|
`sudo /opt/chesstrainer/current/bin/chesstrainer remote` (Ctrl-C twice).
|
||||||
|
|||||||
+27
-1
@@ -7,7 +7,8 @@ set -euo pipefail
|
|||||||
# sudo deploy/activate /tmp/chesstrainer-20261109.tar.gz
|
# sudo deploy/activate /tmp/chesstrainer-20261109.tar.gz
|
||||||
#
|
#
|
||||||
# Environment overrides:
|
# Environment overrides:
|
||||||
# APP_USER, APP_ROOT, SERVICE, HEALTH_URL, KEEP_RELEASES, RELEASE_ID
|
# APP_USER, APP_ROOT, SERVICE, HEALTH_URL, KEEP_RELEASES, RELEASE_ID,
|
||||||
|
# BACKUP_BIN, SKIP_PRE_DEPLOY_BACKUP=1
|
||||||
|
|
||||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
||||||
echo "activate: run with sudo" >&2
|
echo "activate: run with sudo" >&2
|
||||||
@@ -26,6 +27,8 @@ SERVICE="${SERVICE:-chesstrainer}"
|
|||||||
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:4100/health}"
|
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:4100/health}"
|
||||||
KEEP_RELEASES="${KEEP_RELEASES:-5}"
|
KEEP_RELEASES="${KEEP_RELEASES:-5}"
|
||||||
RELEASE_ID="${RELEASE_ID:-$(date -u +%Y%m%d%H%M%S)}"
|
RELEASE_ID="${RELEASE_ID:-$(date -u +%Y%m%d%H%M%S)}"
|
||||||
|
BACKUP_BIN="${BACKUP_BIN:-/usr/local/sbin/chesstrainer-backup}"
|
||||||
|
SKIP_PRE_DEPLOY_BACKUP="${SKIP_PRE_DEPLOY_BACKUP:-0}"
|
||||||
|
|
||||||
if [[ ! "$RELEASE_ID" =~ ^[A-Za-z0-9._-]+$ ]]; then
|
if [[ ! "$RELEASE_ID" =~ ^[A-Za-z0-9._-]+$ ]]; then
|
||||||
echo "activate: RELEASE_ID may contain only letters, digits, dot, underscore and dash" >&2
|
echo "activate: RELEASE_ID may contain only letters, digits, dot, underscore and dash" >&2
|
||||||
@@ -53,6 +56,29 @@ install -d -o "$APP_USER" -g "$APP_USER" "$RELEASE_DIR"
|
|||||||
tar -xzf "$TARBALL" -C "$RELEASE_DIR"
|
tar -xzf "$TARBALL" -C "$RELEASE_DIR"
|
||||||
chown -R "$APP_USER:$APP_USER" "$RELEASE_DIR"
|
chown -R "$APP_USER:$APP_USER" "$RELEASE_DIR"
|
||||||
|
|
||||||
|
if [[ "$SKIP_PRE_DEPLOY_BACKUP" == "1" ]]; then
|
||||||
|
echo "activate: SKIP_PRE_DEPLOY_BACKUP=1, not taking a pre-deploy dump"
|
||||||
|
else
|
||||||
|
backup_script="$BACKUP_BIN"
|
||||||
|
if [[ ! -x "$backup_script" ]]; then
|
||||||
|
backup_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/backup"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -x "$backup_script" ]]; then
|
||||||
|
echo "activate: no backup script at $BACKUP_BIN or next to activate" >&2
|
||||||
|
echo "activate: install deploy/backup or set SKIP_PRE_DEPLOY_BACKUP=1" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Migrations run in ExecStartPre after this, so the dump must exist first.
|
||||||
|
echo "activate: taking a pre-deploy dump"
|
||||||
|
if ! BACKUP_TAG=predeploy LOCK_WAIT=120 "$backup_script"; then
|
||||||
|
echo "activate: pre-deploy dump failed, aborting" >&2
|
||||||
|
echo "activate: fix the backup or re-run with SKIP_PRE_DEPLOY_BACKUP=1" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
echo "activate: pointing current at $RELEASE_DIR"
|
echo "activate: pointing current at $RELEASE_DIR"
|
||||||
ln -sfn "$RELEASE_DIR" "$APP_ROOT/current"
|
ln -sfn "$RELEASE_DIR" "$APP_ROOT/current"
|
||||||
|
|
||||||
|
|||||||
Executable
+266
@@ -0,0 +1,266 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Dump, verify, encrypt, prune and report on the production database.
|
||||||
|
#
|
||||||
|
# Installed as /usr/local/sbin/chesstrainer-backup (root-owned 0755) and run by
|
||||||
|
# chesstrainer-backup.timer. deploy/activate also calls it before migrations.
|
||||||
|
# Do not run the copy under /opt/chesstrainer/src as root: that tree belongs to
|
||||||
|
# the application user.
|
||||||
|
#
|
||||||
|
# sudo systemctl start chesstrainer-backup # daily run, as the timer does
|
||||||
|
# sudo BACKUP_TAG=manual chesstrainer-backup # ad-hoc, pruned by age
|
||||||
|
#
|
||||||
|
# Configuration lives in /etc/chesstrainer/backup.env (root:root 0600). See
|
||||||
|
# deploy/README.md §Backups. Every setting can also be passed as an environment
|
||||||
|
# variable.
|
||||||
|
#
|
||||||
|
# Each run prints exactly one JSON line (backup.completed or backup.failed) so
|
||||||
|
# journald, and #140's log shipping, can pick it up.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
ENV_FILE="${ENV_FILE:-/etc/chesstrainer/backup.env}"
|
||||||
|
if [[ -r "$ENV_FILE" ]]; then
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$ENV_FILE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
DB_CONTAINER="${DB_CONTAINER:-chesstrainer-db}"
|
||||||
|
PG_USER="${PG_USER:-chesstrainer}"
|
||||||
|
PG_DB="${PG_DB:-chesstrainer_prod}"
|
||||||
|
BACKUP_DIR="${BACKUP_DIR:-/var/backups/chesstrainer}"
|
||||||
|
EXPECTED_ROLES="${EXPECTED_ROLES:-chesstrainer chesstrainer_ro}"
|
||||||
|
AGE_RECIPIENT="${AGE_RECIPIENT:-}"
|
||||||
|
HEALTHCHECK_URL="${HEALTHCHECK_URL:-}"
|
||||||
|
SKIP_HEARTBEAT="${SKIP_HEARTBEAT:-0}"
|
||||||
|
MIN_FREE_MB="${MIN_FREE_MB:-2048}"
|
||||||
|
LOCAL_PLAINTEXT_DAYS="${LOCAL_PLAINTEXT_DAYS:-3}"
|
||||||
|
LOCAL_ENCRYPTED_DAYS="${LOCAL_ENCRYPTED_DAYS:-14}"
|
||||||
|
PREDEPLOY_KEEP="${PREDEPLOY_KEEP:-5}"
|
||||||
|
BACKUP_TAG="${BACKUP_TAG:-daily}"
|
||||||
|
LOCK_WAIT="${LOCK_WAIT:-0}"
|
||||||
|
|
||||||
|
START_SECONDS=$SECONDS
|
||||||
|
FAILURE=""
|
||||||
|
|
||||||
|
log_event() {
|
||||||
|
local event="$1"
|
||||||
|
local extra="${2:-}"
|
||||||
|
|
||||||
|
printf '{"timestamp":"%s","event":"%s","tag":"%s"%s}\n' \
|
||||||
|
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$BACKUP_TAG" "$extra"
|
||||||
|
}
|
||||||
|
|
||||||
|
heartbeat() {
|
||||||
|
local outcome="$1"
|
||||||
|
|
||||||
|
[[ "$SKIP_HEARTBEAT" == "1" ]] && return 0
|
||||||
|
[[ -n "$HEALTHCHECK_URL" ]] || return 0
|
||||||
|
|
||||||
|
local url="${HEALTHCHECK_URL%/}"
|
||||||
|
[[ "$outcome" == "fail" ]] && url="$url/fail"
|
||||||
|
|
||||||
|
if ! curl --fail --silent --show-error \
|
||||||
|
--max-time 10 --retry 2 --retry-delay 2 \
|
||||||
|
--output /dev/null "$url"; then
|
||||||
|
echo "backup: heartbeat ping failed (run result is unaffected)" >&2
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
FAILURE="$*"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
on_exit() {
|
||||||
|
local status=$?
|
||||||
|
|
||||||
|
if ((status != 0)); then
|
||||||
|
find "$BACKUP_DIR" -maxdepth 1 -name '*.partial' -delete 2>/dev/null || true
|
||||||
|
log_event backup.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||||
|
heartbeat fail
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
|
||||||
|
trap on_exit EXIT
|
||||||
|
trap 'exit 143' TERM INT
|
||||||
|
|
||||||
|
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
||||||
|
fail "run as root"
|
||||||
|
fi
|
||||||
|
|
||||||
|
[[ "$BACKUP_TAG" =~ ^[a-z0-9]+$ ]] || fail "BACKUP_TAG may contain only lowercase letters and digits"
|
||||||
|
[[ "$MIN_FREE_MB" =~ ^[0-9]+$ ]] || fail "MIN_FREE_MB must be an integer"
|
||||||
|
[[ "$LOCAL_PLAINTEXT_DAYS" =~ ^[0-9]+$ ]] || fail "LOCAL_PLAINTEXT_DAYS must be an integer"
|
||||||
|
[[ "$LOCAL_ENCRYPTED_DAYS" =~ ^[0-9]+$ ]] || fail "LOCAL_ENCRYPTED_DAYS must be an integer"
|
||||||
|
[[ "$PREDEPLOY_KEEP" =~ ^[0-9]+$ ]] || fail "PREDEPLOY_KEEP must be an integer"
|
||||||
|
[[ "$LOCK_WAIT" =~ ^[0-9]+$ ]] || fail "LOCK_WAIT must be an integer"
|
||||||
|
|
||||||
|
[[ "$AGE_RECIPIENT" == age1* ]] || fail "AGE_RECIPIENT is not set to an age public key"
|
||||||
|
|
||||||
|
if [[ "$SKIP_HEARTBEAT" != "1" && -z "$HEALTHCHECK_URL" ]]; then
|
||||||
|
fail "HEALTHCHECK_URL is not set (set SKIP_HEARTBEAT=1 to skip the ping)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
for cmd in docker flock curl age tar sha256sum; do
|
||||||
|
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||||
|
done
|
||||||
|
|
||||||
|
install -d -m 0711 -o root -g root "$BACKUP_DIR"
|
||||||
|
install -d -m 0755 -o root -g root "$BACKUP_DIR/offsite"
|
||||||
|
# 0711 on the vault lets the workstation user traverse to offsite/ without
|
||||||
|
# being able to list the plaintext dumps.
|
||||||
|
chmod 0711 "$BACKUP_DIR"
|
||||||
|
chmod 0755 "$BACKUP_DIR/offsite"
|
||||||
|
|
||||||
|
exec 9>/run/lock/chesstrainer-backup.lock
|
||||||
|
if ! flock -w "$LOCK_WAIT" 9; then
|
||||||
|
if [[ "$LOCK_WAIT" == "0" ]]; then
|
||||||
|
# Overlapping timer/manual runs are not failures; the other run reports.
|
||||||
|
log_event backup.skipped ',"reason":"another backup is running"'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
fail "another backup is still running"
|
||||||
|
fi
|
||||||
|
|
||||||
|
free_mb="$(df -Pm "$BACKUP_DIR" | awk 'NR == 2 { print $4 }')"
|
||||||
|
[[ "$free_mb" =~ ^[0-9]+$ ]] || fail "cannot read free space for $BACKUP_DIR"
|
||||||
|
if ((free_mb < MIN_FREE_MB)); then
|
||||||
|
fail "only ${free_mb}MB free on $BACKUP_DIR, need ${MIN_FREE_MB}MB"
|
||||||
|
fi
|
||||||
|
|
||||||
|
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||||
|
if [[ "$BACKUP_TAG" == "daily" ]]; then
|
||||||
|
prefix="$timestamp"
|
||||||
|
else
|
||||||
|
prefix="$timestamp-$BACKUP_TAG"
|
||||||
|
fi
|
||||||
|
|
||||||
|
dump="$BACKUP_DIR/$prefix.dump"
|
||||||
|
globals="$BACKUP_DIR/$prefix.globals.sql"
|
||||||
|
counts="$BACKUP_DIR/$prefix.counts"
|
||||||
|
checksums="$BACKUP_DIR/$prefix.sha256"
|
||||||
|
archive="$BACKUP_DIR/offsite/$prefix.tar.age"
|
||||||
|
|
||||||
|
# Row counts first: writes between this query and the dump can only push the
|
||||||
|
# restored counts up, so the drill treats this file as a lower bound.
|
||||||
|
read -r -d '' counts_sql <<'SQL' || true
|
||||||
|
select 'users=' || count(*) from users
|
||||||
|
union all select 'endgames=' || count(*) from endgames
|
||||||
|
union all select 'attempts=' || count(*) from attempts;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
docker exec "$DB_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" \
|
||||||
|
-At -v ON_ERROR_STOP=1 -c "$counts_sql" >"$counts.partial" ||
|
||||||
|
fail "row count query failed"
|
||||||
|
[[ -s "$counts.partial" ]] || fail "row count query returned nothing"
|
||||||
|
|
||||||
|
docker exec "$DB_CONTAINER" pg_dump -U "$PG_USER" -d "$PG_DB" -Fc \
|
||||||
|
>"$dump.partial" || fail "pg_dump failed"
|
||||||
|
[[ -s "$dump.partial" ]] || fail "pg_dump produced an empty file"
|
||||||
|
|
||||||
|
# pg_restore -l reads the archive header and table of contents. It needs the
|
||||||
|
# Postgres client matching the server, so run it inside the container.
|
||||||
|
docker exec -i "$DB_CONTAINER" pg_restore -l \
|
||||||
|
<"$dump.partial" >/dev/null || fail "pg_restore -l rejected the dump"
|
||||||
|
|
||||||
|
docker exec "$DB_CONTAINER" pg_dumpall -U "$PG_USER" --globals-only \
|
||||||
|
>"$globals.partial" || fail "pg_dumpall --globals-only failed"
|
||||||
|
[[ -s "$globals.partial" ]] || fail "globals dump is empty"
|
||||||
|
|
||||||
|
# shellcheck disable=SC2086 # EXPECTED_ROLES is a space-separated list
|
||||||
|
for role in $EXPECTED_ROLES; do
|
||||||
|
grep -Eq "^CREATE ROLE \"?${role}\"?( |;)" "$globals.partial" ||
|
||||||
|
fail "globals dump is missing role $role"
|
||||||
|
done
|
||||||
|
|
||||||
|
# Promote only after every check passes, so a broken dump never looks finished.
|
||||||
|
mv "$counts.partial" "$counts"
|
||||||
|
mv "$dump.partial" "$dump"
|
||||||
|
mv "$globals.partial" "$globals"
|
||||||
|
|
||||||
|
(
|
||||||
|
cd "$BACKUP_DIR"
|
||||||
|
sha256sum "${dump##*/}" "${globals##*/}" "${counts##*/}" >"${checksums##*/}"
|
||||||
|
)
|
||||||
|
|
||||||
|
tar -C "$BACKUP_DIR" -cf - \
|
||||||
|
"${dump##*/}" "${globals##*/}" "${counts##*/}" "${checksums##*/}" |
|
||||||
|
age --recipient "$AGE_RECIPIENT" --output "$archive.partial" ||
|
||||||
|
fail "encrypting the dump failed"
|
||||||
|
|
||||||
|
chmod 0644 "$archive.partial"
|
||||||
|
mv "$archive.partial" "$archive"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Retention
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
aged() {
|
||||||
|
[[ -n "$(find "$1" -maxdepth 0 -mtime +"$2" -print -quit 2>/dev/null)" ]]
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_plaintext_set() {
|
||||||
|
local prefix="$1"
|
||||||
|
|
||||||
|
rm -f -- \
|
||||||
|
"$BACKUP_DIR/$prefix.dump" \
|
||||||
|
"$BACKUP_DIR/$prefix.globals.sql" \
|
||||||
|
"$BACKUP_DIR/$prefix.counts" \
|
||||||
|
"$BACKUP_DIR/$prefix.sha256"
|
||||||
|
}
|
||||||
|
|
||||||
|
prune_plaintext_by_age() {
|
||||||
|
local dump base prefix
|
||||||
|
|
||||||
|
while IFS= read -r dump; do
|
||||||
|
base="${dump##*/}"
|
||||||
|
prefix="${base%%.*}"
|
||||||
|
[[ "$base" == *-predeploy.dump ]] && continue
|
||||||
|
|
||||||
|
if aged "$dump" "$LOCAL_PLAINTEXT_DAYS"; then
|
||||||
|
echo "backup: pruning $prefix (plaintext older than ${LOCAL_PLAINTEXT_DAYS}d)" >&2
|
||||||
|
remove_plaintext_set "$prefix"
|
||||||
|
fi
|
||||||
|
done < <(find "$BACKUP_DIR" -maxdepth 1 -type f -name '*.dump')
|
||||||
|
}
|
||||||
|
|
||||||
|
prune_predeploy_plaintext() {
|
||||||
|
local -a dumps
|
||||||
|
local i prefix
|
||||||
|
|
||||||
|
mapfile -t dumps < <(
|
||||||
|
find "$BACKUP_DIR" -maxdepth 1 -type f -name '*-predeploy.dump' -printf '%f\n' | sort -r
|
||||||
|
)
|
||||||
|
|
||||||
|
for ((i = PREDEPLOY_KEEP; i < ${#dumps[@]}; i++)); do
|
||||||
|
prefix="${dumps[i]%%.*}"
|
||||||
|
echo "backup: pruning $prefix (keeping last ${PREDEPLOY_KEEP} pre-deploy dumps)" >&2
|
||||||
|
remove_plaintext_set "$prefix"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
prune_encrypted() {
|
||||||
|
local archive
|
||||||
|
|
||||||
|
while IFS= read -r archive; do
|
||||||
|
echo "backup: pruning ${archive##*/} (encrypted older than ${LOCAL_ENCRYPTED_DAYS}d)" >&2
|
||||||
|
rm -f -- "$archive"
|
||||||
|
done < <(
|
||||||
|
find "$BACKUP_DIR/offsite" -maxdepth 1 -type f -name '*.tar.age' -mtime +"$LOCAL_ENCRYPTED_DAYS"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
prune_plaintext_by_age
|
||||||
|
prune_predeploy_plaintext
|
||||||
|
prune_encrypted
|
||||||
|
|
||||||
|
dump_bytes="$(stat -c %s "$dump")"
|
||||||
|
archive_bytes="$(stat -c %s "$archive")"
|
||||||
|
|
||||||
|
log_event backup.completed ",\"dump\":\"$prefix\",\"dump_bytes\":$dump_bytes,\"offsite_bytes\":$archive_bytes,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||||
|
heartbeat ok
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# /etc/chesstrainer/backup.env -- root:root, mode 0600.
|
||||||
|
#
|
||||||
|
# Sourced by /usr/local/sbin/chesstrainer-backup. Every value below shows the
|
||||||
|
# default; only AGE_RECIPIENT and HEALTHCHECK_URL must be set. Keep secrets out
|
||||||
|
# of the repo and out of world-readable files.
|
||||||
|
|
||||||
|
# age public key, generated on the workstation with `age-keygen`.
|
||||||
|
# The private key never leaves the workstation.
|
||||||
|
AGE_RECIPIENT=age1...
|
||||||
|
|
||||||
|
# healthchecks.io (or compatible) ping URL. The script pings it after a good
|
||||||
|
# run and pings <url>/fail after a bad one. Set SKIP_HEARTBEAT=1 to run without
|
||||||
|
# monitoring (testing only).
|
||||||
|
HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||||
|
|
||||||
|
# Refuse to dump when the filesystem has less than this much free space.
|
||||||
|
MIN_FREE_MB=2048
|
||||||
|
|
||||||
|
# Retention. Dumps and their globals/counts/checksum siblings disappear as a
|
||||||
|
# set; only the encrypted archives in offsite/ live for the longer window.
|
||||||
|
LOCAL_PLAINTEXT_DAYS=3
|
||||||
|
LOCAL_ENCRYPTED_DAYS=14
|
||||||
|
PREDEPLOY_KEEP=5
|
||||||
|
|
||||||
|
# Postgres coordinates. The container trusts local Unix-socket connections, so
|
||||||
|
# no password belongs here.
|
||||||
|
DB_CONTAINER=chesstrainer-db
|
||||||
|
PG_USER=chesstrainer
|
||||||
|
PG_DB=chesstrainer_prod
|
||||||
|
BACKUP_DIR=/var/backups/chesstrainer
|
||||||
|
|
||||||
|
# Roles the globals dump must be able to recreate.
|
||||||
|
EXPECTED_ROLES="chesstrainer chesstrainer_ro"
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Report a failed Inner Square Chess database backup
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/usr/bin/logger --tag chesstrainer-backup --priority daemon.err --stderr backup.unit-failed: chesstrainer-backup.service failed, see journalctl -u chesstrainer-backup
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Inner Square Chess database backup
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
After=network-online.target docker.service
|
||||||
|
Wants=network-online.target
|
||||||
|
OnFailure=chesstrainer-backup-failure.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=root
|
||||||
|
Group=root
|
||||||
|
ExecStart=/usr/local/sbin/chesstrainer-backup
|
||||||
|
Nice=10
|
||||||
|
IOSchedulingClass=idle
|
||||||
|
TimeoutStartSec=10min
|
||||||
|
SyslogIdentifier=chesstrainer-backup
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Daily Inner Square Chess database backup
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-* 03:15:00 UTC
|
||||||
|
RandomizedDelaySec=5m
|
||||||
|
AccuracySec=1m
|
||||||
|
Persistent=true
|
||||||
|
Unit=chesstrainer-backup.service
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -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"
|
||||||
Executable
+190
@@ -0,0 +1,190 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Restore the newest (or a named) archive into a throwaway Postgres container
|
||||||
|
# and prove that the dump, the roles and the row counts all came back.
|
||||||
|
#
|
||||||
|
# backup-drill # newest archive in DEST
|
||||||
|
# backup-drill 20261111T031500Z.tar.age
|
||||||
|
#
|
||||||
|
# Runs on the workstation. The production database is never contacted: the
|
||||||
|
# container is created and destroyed by this script. Results are appended to
|
||||||
|
# $DRILL_LOG (default $DEST/drills.log).
|
||||||
|
#
|
||||||
|
# Configuration: same file as backup-pull,
|
||||||
|
# ~/.config/chesstrainer/backup-pull.env.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
CONFIG="${PULL_ENV_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/backup-pull.env}"
|
||||||
|
if [[ -r "$CONFIG" ]]; then
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$CONFIG"
|
||||||
|
fi
|
||||||
|
|
||||||
|
DEST="${DEST:-$HOME/chesstrainer-backups}"
|
||||||
|
AGE_KEY="${AGE_KEY:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/age.key}"
|
||||||
|
EXPECTED_ROLES="${EXPECTED_ROLES:-chesstrainer chesstrainer_ro}"
|
||||||
|
DRILL_IMAGE="${DRILL_IMAGE:-postgres:18.6}"
|
||||||
|
DRILL_DB="${DRILL_DB:-chesstrainer_restore}"
|
||||||
|
DRILL_LOG="${DRILL_LOG:-$DEST/drills.log}"
|
||||||
|
DRILL_CONTAINER="${DRILL_CONTAINER:-chesstrainer-drill-$$}"
|
||||||
|
|
||||||
|
START_SECONDS=$SECONDS
|
||||||
|
FAILURE=""
|
||||||
|
TMPDIR_DRILL=""
|
||||||
|
|
||||||
|
log_event() {
|
||||||
|
local event="$1"
|
||||||
|
local extra="${2:-}"
|
||||||
|
|
||||||
|
printf '{"timestamp":"%s","event":"%s"%s}\n' \
|
||||||
|
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
|
||||||
|
}
|
||||||
|
|
||||||
|
record() {
|
||||||
|
local line="$1"
|
||||||
|
|
||||||
|
printf '%s\n' "$line"
|
||||||
|
printf '%s\n' "$line" >>"$DRILL_LOG"
|
||||||
|
}
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
FAILURE="$*"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
local status=$?
|
||||||
|
|
||||||
|
docker rm -f "$DRILL_CONTAINER" >/dev/null 2>&1 || true
|
||||||
|
|
||||||
|
if [[ -n "$TMPDIR_DRILL" ]]; then
|
||||||
|
rm -rf "$TMPDIR_DRILL"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ((status != 0)); then
|
||||||
|
if [[ -d "$DEST" ]]; then
|
||||||
|
record "$(log_event drill.failed ",\"reason\":\"${FAILURE:-exit $status}\"")"
|
||||||
|
else
|
||||||
|
log_event drill.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
|
||||||
|
trap cleanup EXIT
|
||||||
|
trap 'exit 143' TERM INT
|
||||||
|
|
||||||
|
[[ -d "$DEST" ]] || fail "archive directory does not exist: $DEST"
|
||||||
|
[[ -r "$AGE_KEY" ]] || fail "age identity not readable: $AGE_KEY"
|
||||||
|
|
||||||
|
for cmd in docker age tar sha256sum; do
|
||||||
|
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $# -gt 0 ]]; then
|
||||||
|
case "$1" in
|
||||||
|
/*) archive="$1" ;;
|
||||||
|
*) archive="$DEST/$1" ;;
|
||||||
|
esac
|
||||||
|
else
|
||||||
|
archive="$(find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%p\n' | sort | tail -n 1)"
|
||||||
|
[[ -n "$archive" ]] || fail "no archives in $DEST"
|
||||||
|
fi
|
||||||
|
|
||||||
|
[[ -f "$archive" ]] || fail "archive not found: $archive"
|
||||||
|
|
||||||
|
name="${archive##*/}"
|
||||||
|
[[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z(-[a-z0-9]+)?\.tar\.age$ ]] ||
|
||||||
|
fail "unexpected archive name: $name"
|
||||||
|
|
||||||
|
prefix="${name%%.*}"
|
||||||
|
TMPDIR_DRILL="$(mktemp -d "${TMPDIR:-/tmp}/chesstrainer-drill.XXXXXX")"
|
||||||
|
|
||||||
|
echo "backup-drill: decrypting $name" >&2
|
||||||
|
age --decrypt --identity "$AGE_KEY" --output "$TMPDIR_DRILL/$prefix.tar" "$archive" ||
|
||||||
|
fail "could not decrypt $name"
|
||||||
|
|
||||||
|
tar -xf "$TMPDIR_DRILL/$prefix.tar" -C "$TMPDIR_DRILL" ||
|
||||||
|
fail "archive does not contain a readable tar file"
|
||||||
|
|
||||||
|
(
|
||||||
|
cd "$TMPDIR_DRILL"
|
||||||
|
sha256sum --check --strict --quiet "$prefix.sha256"
|
||||||
|
) || fail "checksum verification failed for $name"
|
||||||
|
|
||||||
|
echo "backup-drill: starting $DRILL_IMAGE" >&2
|
||||||
|
docker image inspect "$DRILL_IMAGE" >/dev/null 2>&1 ||
|
||||||
|
docker pull "$DRILL_IMAGE" >/dev/null ||
|
||||||
|
fail "could not pull $DRILL_IMAGE"
|
||||||
|
|
||||||
|
docker run --rm --detach \
|
||||||
|
--name "$DRILL_CONTAINER" \
|
||||||
|
--env POSTGRES_USER=chesstrainer \
|
||||||
|
--env POSTGRES_PASSWORD=drill \
|
||||||
|
--env POSTGRES_HOST_AUTH_METHOD=trust \
|
||||||
|
"$DRILL_IMAGE" >/dev/null || fail "could not start the drill container"
|
||||||
|
|
||||||
|
ready=0
|
||||||
|
for _ in $(seq 1 60); do
|
||||||
|
if docker exec "$DRILL_CONTAINER" pg_isready -U chesstrainer -d postgres >/dev/null 2>&1; then
|
||||||
|
ready=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
((ready == 1)) || fail "postgres did not become ready"
|
||||||
|
|
||||||
|
# Recreating the cluster roles is half of disaster recovery. The scratch
|
||||||
|
# cluster uses the same superuser name as production (`chesstrainer`), because
|
||||||
|
# the globals dump ends with grants issued "GRANTED BY chesstrainer". The dump
|
||||||
|
# always repeats the cluster's own superuser role, so "already exists" is
|
||||||
|
# expected; anything else is a real failure.
|
||||||
|
echo "backup-drill: applying globals" >&2
|
||||||
|
docker exec -i "$DRILL_CONTAINER" psql -U chesstrainer -d postgres \
|
||||||
|
-q -v ON_ERROR_STOP=0 -f - \
|
||||||
|
<"$TMPDIR_DRILL/$prefix.globals.sql" >/dev/null 2>"$TMPDIR_DRILL/globals.err" ||
|
||||||
|
fail "applying the globals dump failed"
|
||||||
|
|
||||||
|
globals_errors="$(grep -v 'already exists' "$TMPDIR_DRILL/globals.err" | sed '/^$/d' || true)"
|
||||||
|
if [[ -n "$globals_errors" ]]; then
|
||||||
|
fail "globals restore reported errors: $(printf '%s' "$globals_errors" | head -n 1)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
for role in $EXPECTED_ROLES; do
|
||||||
|
found="$(docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d postgres -Atc \
|
||||||
|
"select 1 from pg_roles where rolname = '$role'")"
|
||||||
|
[[ "$found" == "1" ]] || fail "globals did not recreate role $role"
|
||||||
|
done
|
||||||
|
|
||||||
|
owner="${EXPECTED_ROLES%% *}"
|
||||||
|
|
||||||
|
docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d postgres \
|
||||||
|
-q -v ON_ERROR_STOP=1 -c "create database $DRILL_DB owner $owner" ||
|
||||||
|
fail "could not create $DRILL_DB"
|
||||||
|
|
||||||
|
echo "backup-drill: restoring into $DRILL_DB" >&2
|
||||||
|
docker exec -i "$DRILL_CONTAINER" pg_restore -U chesstrainer -d "$DRILL_DB" \
|
||||||
|
--single-transaction --exit-on-error <"$TMPDIR_DRILL/$prefix.dump" ||
|
||||||
|
fail "pg_restore failed"
|
||||||
|
|
||||||
|
restored_counts=""
|
||||||
|
for table in users endgames attempts; do
|
||||||
|
expected="$(awk -F= -v key="$table" '$1 == key { print $2 }' "$TMPDIR_DRILL/$prefix.counts")"
|
||||||
|
[[ "$expected" =~ ^[0-9]+$ ]] || fail "counts file has no value for $table"
|
||||||
|
|
||||||
|
actual="$(docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d "$DRILL_DB" -Atc \
|
||||||
|
"select count(*) from $table")"
|
||||||
|
[[ "$actual" =~ ^[0-9]+$ ]] || fail "could not count $table"
|
||||||
|
|
||||||
|
if ((actual < expected)); then
|
||||||
|
fail "restored $table=$actual is below the recorded $expected"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "backup-drill: $table restored=$actual recorded=$expected drift=$((actual - expected))" >&2
|
||||||
|
restored_counts+="${restored_counts:+,}$table=$actual"
|
||||||
|
done
|
||||||
|
|
||||||
|
record "$(log_event drill.completed ",\"archive\":\"$name\",\"result\":\"pass\",\"counts\":\"$restored_counts\",\"duration_s\":$((SECONDS - START_SECONDS))")"
|
||||||
Executable
+248
@@ -0,0 +1,248 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Pull the encrypted database archives from the VPS, verify them end to end,
|
||||||
|
# and apply the 7 daily / 4 weekly / 6 monthly retention policy.
|
||||||
|
#
|
||||||
|
# Runs on the workstation, never on the server. Install as
|
||||||
|
# ~/.local/bin/chesstrainer-backup-pull and enable
|
||||||
|
# chesstrainer-backup-pull.timer as a user unit.
|
||||||
|
#
|
||||||
|
# Configuration: ~/.config/chesstrainer/backup-pull.env (0600). See
|
||||||
|
# deploy/README.md §Backups.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
CONFIG="${PULL_ENV_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/backup-pull.env}"
|
||||||
|
if [[ -r "$CONFIG" ]]; then
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$CONFIG"
|
||||||
|
fi
|
||||||
|
|
||||||
|
VPS_HOST="${VPS_HOST:-}"
|
||||||
|
REMOTE_DIR="${REMOTE_DIR:-/var/backups/chesstrainer/offsite}"
|
||||||
|
DEST="${DEST:-$HOME/chesstrainer-backups}"
|
||||||
|
AGE_KEY="${AGE_KEY:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/age.key}"
|
||||||
|
MAX_STALENESS_HOURS="${MAX_STALENESS_HOURS:-48}"
|
||||||
|
KEEP_DAILY_DAYS="${KEEP_DAILY_DAYS:-7}"
|
||||||
|
KEEP_WEEKLY_WEEKS="${KEEP_WEEKLY_WEEKS:-4}"
|
||||||
|
KEEP_MONTHLY_MONTHS="${KEEP_MONTHLY_MONTHS:-6}"
|
||||||
|
PULL_HEALTHCHECK_URL="${PULL_HEALTHCHECK_URL:-}"
|
||||||
|
SSH_OPTIONS="${SSH_OPTIONS:--o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15}"
|
||||||
|
RSYNC_ATTEMPTS="${RSYNC_ATTEMPTS:-3}"
|
||||||
|
|
||||||
|
START_SECONDS=$SECONDS
|
||||||
|
FAILURE=""
|
||||||
|
VERIFIED=0
|
||||||
|
|
||||||
|
log_event() {
|
||||||
|
local event="$1"
|
||||||
|
local extra="${2:-}"
|
||||||
|
|
||||||
|
printf '{"timestamp":"%s","event":"%s"%s}\n' \
|
||||||
|
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
|
||||||
|
}
|
||||||
|
|
||||||
|
heartbeat() {
|
||||||
|
local outcome="$1"
|
||||||
|
|
||||||
|
[[ -n "$PULL_HEALTHCHECK_URL" ]] || return 0
|
||||||
|
|
||||||
|
local url="${PULL_HEALTHCHECK_URL%/}"
|
||||||
|
[[ "$outcome" == "fail" ]] && url="$url/fail"
|
||||||
|
|
||||||
|
if ! curl --fail --silent --show-error \
|
||||||
|
--max-time 10 --retry 2 --retry-delay 2 \
|
||||||
|
--output /dev/null "$url"; then
|
||||||
|
echo "backup-pull: heartbeat ping failed (run result is unaffected)" >&2
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
FAILURE="$*"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
local status=$?
|
||||||
|
|
||||||
|
if [[ -d "$DEST" ]]; then
|
||||||
|
find "$DEST" -maxdepth 1 -name '.verify.*' -type d -exec rm -rf {} + 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ((status != 0)); then
|
||||||
|
log_event pull.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||||
|
heartbeat fail
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
|
||||||
|
trap cleanup EXIT
|
||||||
|
trap 'exit 143' TERM INT
|
||||||
|
|
||||||
|
[[ -n "$VPS_HOST" ]] || fail "VPS_HOST is not set"
|
||||||
|
[[ -r "$AGE_KEY" ]] || fail "age identity not readable: $AGE_KEY"
|
||||||
|
[[ "$MAX_STALENESS_HOURS" =~ ^[0-9]+$ ]] || fail "MAX_STALENESS_HOURS must be an integer"
|
||||||
|
[[ "$KEEP_DAILY_DAYS" =~ ^[0-9]+$ ]] || fail "KEEP_DAILY_DAYS must be an integer"
|
||||||
|
[[ "$KEEP_WEEKLY_WEEKS" =~ ^[0-9]+$ ]] || fail "KEEP_WEEKLY_WEEKS must be an integer"
|
||||||
|
[[ "$KEEP_MONTHLY_MONTHS" =~ ^[0-9]+$ ]] || fail "KEEP_MONTHLY_MONTHS must be an integer"
|
||||||
|
[[ "$RSYNC_ATTEMPTS" =~ ^[0-9]+$ ]] || fail "RSYNC_ATTEMPTS must be an integer"
|
||||||
|
|
||||||
|
for cmd in rsync ssh age tar sha256sum curl flock; do
|
||||||
|
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||||
|
done
|
||||||
|
|
||||||
|
# Never create DEST on the root filesystem when the backup disk is unmounted.
|
||||||
|
[[ -d "$(dirname "$DEST")" ]] ||
|
||||||
|
fail "parent directory of $DEST does not exist (is the backup disk mounted?)"
|
||||||
|
|
||||||
|
install -d -m 0700 "$DEST"
|
||||||
|
install -d -m 0700 "$DEST/.verified"
|
||||||
|
|
||||||
|
exec 9>"$DEST/.pull.lock"
|
||||||
|
if ! flock -n 9; then
|
||||||
|
# A manual run overlapping the timer is not an error; the other run reports.
|
||||||
|
log_event pull.skipped ',"reason":"another pull is running"'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
archive_epoch() {
|
||||||
|
local name="$1"
|
||||||
|
local ts="${name:0:16}"
|
||||||
|
|
||||||
|
[[ "$ts" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] || return 1
|
||||||
|
|
||||||
|
date -u -d "${ts:0:4}-${ts:4:2}-${ts:6:2} ${ts:9:2}:${ts:11:2}:${ts:13:2}Z" +%s
|
||||||
|
}
|
||||||
|
|
||||||
|
verify_archive() {
|
||||||
|
local archive="$1"
|
||||||
|
local name="${archive##*/}"
|
||||||
|
local marker="$DEST/.verified/$name"
|
||||||
|
local sum tmp
|
||||||
|
|
||||||
|
sum="$(sha256sum "$archive" | awk '{ print $1 }')"
|
||||||
|
|
||||||
|
if [[ -f "$marker" && "$(cat "$marker")" == "$sum" ]]; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
tmp="$(mktemp -d "$DEST/.verify.XXXXXX")"
|
||||||
|
|
||||||
|
if ! age --decrypt --identity "$AGE_KEY" --output "$tmp/$name.tar" "$archive"; then
|
||||||
|
rm -rf "$tmp"
|
||||||
|
echo "backup-pull: $name failed to decrypt" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! tar -xf "$tmp/$name.tar" -C "$tmp"; then
|
||||||
|
rm -rf "$tmp"
|
||||||
|
echo "backup-pull: $name did not contain a readable tar archive" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! (cd "$tmp" && sha256sum --check --strict --quiet ./*.sha256); then
|
||||||
|
rm -rf "$tmp"
|
||||||
|
echo "backup-pull: $name failed its checksum verification" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
rm -rf "$tmp"
|
||||||
|
|
||||||
|
printf '%s\n' "$sum" >"$marker.tmp"
|
||||||
|
mv "$marker.tmp" "$marker"
|
||||||
|
|
||||||
|
VERIFIED=$((VERIFIED + 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Copy
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
attempt=1
|
||||||
|
while true; do
|
||||||
|
if rsync --archive --partial --compress --timeout=120 \
|
||||||
|
--include='*.tar.age' --exclude='*' \
|
||||||
|
--rsh "ssh $SSH_OPTIONS" \
|
||||||
|
"$VPS_HOST:$REMOTE_DIR/" "$DEST/"; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ((attempt >= RSYNC_ATTEMPTS)); then
|
||||||
|
fail "rsync from $VPS_HOST failed after $attempt attempts"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "backup-pull: rsync attempt $attempt failed, retrying" >&2
|
||||||
|
attempt=$((attempt + 1))
|
||||||
|
sleep 20
|
||||||
|
done
|
||||||
|
|
||||||
|
mapfile -t archives < <(
|
||||||
|
find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%f\n' | sort
|
||||||
|
)
|
||||||
|
|
||||||
|
((${#archives[@]} > 0)) || fail "no archives in $DEST after the pull"
|
||||||
|
|
||||||
|
for name in "${archives[@]}"; do
|
||||||
|
[[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z(-[a-z0-9]+)?\.tar\.age$ ]] ||
|
||||||
|
fail "unexpected file in $DEST: $name"
|
||||||
|
done
|
||||||
|
|
||||||
|
newest="${archives[${#archives[@]} - 1]}"
|
||||||
|
newest_epoch="$(archive_epoch "$newest")" || fail "cannot parse a timestamp from $newest"
|
||||||
|
age_seconds=$(($(date -u +%s) - newest_epoch))
|
||||||
|
|
||||||
|
if ((age_seconds > MAX_STALENESS_HOURS * 3600)); then
|
||||||
|
fail "newest archive $newest is $((age_seconds / 3600))h old (limit ${MAX_STALENESS_HOURS}h): VPS backups may have stopped"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Verify every archive once; unchanged ciphertext is only re-hashed.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
for name in "${archives[@]}"; do
|
||||||
|
verify_archive "$DEST/$name" || fail "$name failed verification"
|
||||||
|
done
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Retention: 7 daily, then one per ISO week for 4 weeks, then one per calendar
|
||||||
|
# month for 6 months. Archives outside all three windows are deleted.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
now="$(date -u +%s)"
|
||||||
|
pruned=0
|
||||||
|
declare -A kept_week=()
|
||||||
|
declare -A kept_month=()
|
||||||
|
|
||||||
|
mapfile -t newest_first < <(
|
||||||
|
find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%f\n' | sort -r
|
||||||
|
)
|
||||||
|
|
||||||
|
for name in "${newest_first[@]}"; do
|
||||||
|
epoch="$(archive_epoch "$name")" || continue
|
||||||
|
age_days=$(((now - epoch) / 86400))
|
||||||
|
|
||||||
|
if ((age_days < KEEP_DAILY_DAYS)); then
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
week="$(date -u -d "@$epoch" +%G-W%V)"
|
||||||
|
if ((age_days < KEEP_WEEKLY_WEEKS * 7)) && [[ -z "${kept_week[$week]:-}" ]]; then
|
||||||
|
kept_week[$week]=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
month="$(date -u -d "@$epoch" +%Y-%m)"
|
||||||
|
if ((age_days < KEEP_MONTHLY_MONTHS * 31)) && [[ -z "${kept_month[$month]:-}" ]]; then
|
||||||
|
kept_month[$month]=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "backup-pull: pruning $name" >&2
|
||||||
|
rm -f -- "$DEST/$name" "$DEST/.verified/$name"
|
||||||
|
pruned=$((pruned + 1))
|
||||||
|
done
|
||||||
|
|
||||||
|
log_event pull.completed ",\"newest\":\"$newest\",\"archives\":$(( ${#archives[@]} - pruned )),\"verified\":$VERIFIED,\"pruned\":$pruned,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||||
|
heartbeat ok
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# ~/.config/chesstrainer/backup-pull.env -- mode 0600.
|
||||||
|
#
|
||||||
|
# Sourced by ~/.local/bin/chesstrainer-backup-pull. Values below are the
|
||||||
|
# defaults; VPS_HOST and AGE_KEY must be right. Quote anything containing
|
||||||
|
# spaces.
|
||||||
|
|
||||||
|
VPS_HOST=owen@159.69.21.225
|
||||||
|
REMOTE_DIR=/var/backups/chesstrainer/offsite
|
||||||
|
DEST="/mnt/Mint Data/chesstrainer-backups"
|
||||||
|
|
||||||
|
# Private half of the age key. Back this file up somewhere safe: without it
|
||||||
|
# every archive is unreadable.
|
||||||
|
AGE_KEY="$HOME/.config/chesstrainer/age.key"
|
||||||
|
|
||||||
|
# Fail the pull when the newest archive from the VPS is older than this, which
|
||||||
|
# means the VPS backup timer has stopped.
|
||||||
|
MAX_STALENESS_HOURS=48
|
||||||
|
|
||||||
|
# Keep every archive from the last 7 days, then one per ISO week for 4 weeks,
|
||||||
|
# then one per calendar month for 6 months.
|
||||||
|
KEEP_DAILY_DAYS=7
|
||||||
|
KEEP_WEEKLY_WEEKS=4
|
||||||
|
KEEP_MONTHLY_MONTHS=6
|
||||||
|
|
||||||
|
# Restore drill. It runs in a throwaway container matching the production
|
||||||
|
# Postgres major and appends results to DRILL_LOG.
|
||||||
|
# DRILL_IMAGE=postgres:18.6
|
||||||
|
# DRILL_DB=chesstrainer_restore
|
||||||
|
# DRILL_LOG="$DEST/drills.log"
|
||||||
|
EXPECTED_ROLES="chesstrainer chesstrainer_ro"
|
||||||
|
|
||||||
|
# Optional second heartbeat check with a long period (for example 72h), so you
|
||||||
|
# hear about it when the workstation stops pulling. Leave empty to disable.
|
||||||
|
# PULL_HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||||
|
|
||||||
|
# Extra ssh options, space separated.
|
||||||
|
# SSH_OPTIONS="-o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15"
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Report a failed Inner Square Chess backup unit
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/usr/bin/logger --tag chesstrainer-backup --priority user.err --stderr backup.unit-failed: %i failed, see journalctl --user -u %i
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Monthly restore drill for Inner Square Chess backups
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
OnFailure=chesstrainer-backup-alert@%N.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=%h/.local/bin/chesstrainer-backup-drill
|
||||||
|
WorkingDirectory=%h
|
||||||
|
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||||
|
Nice=10
|
||||||
|
TimeoutStartSec=20min
|
||||||
|
SyslogIdentifier=chesstrainer-backup-drill
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Monthly restore drill for Inner Square Chess backups
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-01 09:00:00
|
||||||
|
RandomizedDelaySec=30m
|
||||||
|
AccuracySec=5m
|
||||||
|
Persistent=true
|
||||||
|
Unit=chesstrainer-backup-drill.service
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Pull encrypted Inner Square Chess backups from the VPS
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
OnFailure=chesstrainer-backup-alert@%N.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=%h/.local/bin/chesstrainer-backup-pull
|
||||||
|
WorkingDirectory=%h
|
||||||
|
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||||
|
Nice=10
|
||||||
|
TimeoutStartSec=15min
|
||||||
|
SyslogIdentifier=chesstrainer-backup-pull
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Daily pull of encrypted Inner Square Chess backups
|
||||||
|
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-* 12:00:00
|
||||||
|
OnBootSec=10m
|
||||||
|
RandomizedDelaySec=10m
|
||||||
|
AccuracySec=1m
|
||||||
|
Persistent=true
|
||||||
|
Unit=chesstrainer-backup-pull.service
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -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,32 +21,78 @@ 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)
|
||||||
user,
|
|
||||||
&url(~p"/users/confirm/#{&1}")
|
|
||||||
)
|
|
||||||
|
|
||||||
# In order to prevent user enumeration attacks, report the same error
|
|
||||||
# as invalid credentials.
|
|
||||||
invalid_credentials(conn, login, failure_path)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defp maybe_resend_confirmation(user, login) do
|
||||||
|
if LoginThrottle.claim_confirmation_resend(login) do
|
||||||
|
case Accounts.deliver_user_confirmation_instructions(
|
||||||
|
user,
|
||||||
|
&url(~p"/users/confirm/#{&1}")
|
||||||
|
) do
|
||||||
|
{:ok, _email} -> :ok
|
||||||
|
{:error, _reason} -> Logger.warning("auth.confirmation.resend_failed")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
|
||||||
|
defp authentication_failed(conn, address, login, reason, failure_path) do
|
||||||
|
LoginThrottle.record_failure(address, login)
|
||||||
|
log_auth_event("auth.login.failed", address, reason: reason)
|
||||||
|
|
||||||
|
# In order to prevent user enumeration attacks, report the same error as
|
||||||
|
# invalid credentials.
|
||||||
|
invalid_credentials(conn, login, failure_path)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp log_auth_event(message, address, metadata) do
|
||||||
|
Logger.warning(message, Keyword.put(metadata, :ip, LoginThrottle.fingerprint(address)))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp throttle_message(retry_in_ms) do
|
||||||
|
minutes = max(div(retry_in_ms + 59_999, 60_000), 1)
|
||||||
|
unit = if minutes == 1, do: "minute", else: "minutes"
|
||||||
|
|
||||||
|
"Too many attempts. Try again in #{minutes} #{unit}."
|
||||||
|
end
|
||||||
|
|
||||||
defp invalid_credentials(conn, login, path) do
|
defp invalid_credentials(conn, login, path) do
|
||||||
conn
|
conn
|
||||||
|> put_flash(:error, "Invalid email, username or password")
|
|> put_flash(:error, "Invalid email, username or password")
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||||
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Policy
|
||||||
|
alias Chesstrainer.Themes
|
||||||
|
alias Chesstrainer.Themes.Theme
|
||||||
|
|
||||||
|
@category_options [
|
||||||
|
{"Endgame", "endgame"},
|
||||||
|
{"Opening", "opening"},
|
||||||
|
{"Tactic", "tactic"}
|
||||||
|
]
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def render(assigns) do
|
||||||
|
~H"""
|
||||||
|
<Layouts.app flash={@flash}>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
|
<.header>
|
||||||
|
{@page_title}
|
||||||
|
<:subtitle>
|
||||||
|
Themes group endgames for filtering. Names must be unique within a category,
|
||||||
|
ignoring case.
|
||||||
|
</:subtitle>
|
||||||
|
</.header>
|
||||||
|
|
||||||
|
<.form for={@form} id="theme-form" phx-change="validate" phx-submit="save">
|
||||||
|
<.input field={@form[:name]} type="text" label="Name" autocomplete="off" required />
|
||||||
|
<.input
|
||||||
|
field={@form[:category]}
|
||||||
|
type="select"
|
||||||
|
label="Category"
|
||||||
|
options={@category_options}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
|
||||||
|
<.button navigate={~p"/admin/themes"}>Cancel</.button>
|
||||||
|
</footer>
|
||||||
|
</.form>
|
||||||
|
</Layouts.app>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def mount(params, _session, socket) do
|
||||||
|
{:ok, apply_action(socket, socket.assigns.live_action, params)}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp apply_action(socket, :new, _params) do
|
||||||
|
theme = %Theme{}
|
||||||
|
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, "New theme")
|
||||||
|
|> assign(:theme, theme)
|
||||||
|
|> assign(:category_options, @category_options)
|
||||||
|
|> assign(:form, to_form(Themes.change_theme(theme)))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp apply_action(socket, :edit, %{"id" => id}) do
|
||||||
|
theme = Themes.get_theme!(id)
|
||||||
|
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, "Edit theme")
|
||||||
|
|> assign(:theme, theme)
|
||||||
|
|> assign(:category_options, @category_options)
|
||||||
|
|> assign(:form, to_form(Themes.change_theme(theme)))
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_event("validate", %{"theme" => theme_params}, socket) do
|
||||||
|
changeset =
|
||||||
|
socket.assigns.theme
|
||||||
|
|> Themes.change_theme(theme_params)
|
||||||
|
|> Map.put(:action, :validate)
|
||||||
|
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("save", %{"theme" => theme_params}, socket) do
|
||||||
|
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
|
||||||
|
save_theme(socket, socket.assigns.live_action, theme_params)
|
||||||
|
else
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp save_theme(socket, :new, theme_params) do
|
||||||
|
case Themes.create_theme(theme_params) do
|
||||||
|
{:ok, _theme} ->
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> put_flash(:info, "Theme created successfully.")
|
||||||
|
|> push_navigate(to: ~p"/admin/themes")}
|
||||||
|
|
||||||
|
{:error, %Ecto.Changeset{} = changeset} ->
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp save_theme(socket, :edit, theme_params) do
|
||||||
|
case Themes.update_theme(socket.assigns.theme, theme_params) do
|
||||||
|
{:ok, _theme} ->
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> put_flash(:info, "Theme updated successfully.")
|
||||||
|
|> push_navigate(to: ~p"/admin/themes")}
|
||||||
|
|
||||||
|
{:error, %Ecto.Changeset{} = changeset} ->
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
|
||||||
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Policy
|
||||||
|
alias Chesstrainer.Themes
|
||||||
|
|
||||||
|
@category_options [
|
||||||
|
{"All categories", ""},
|
||||||
|
{"Endgame", "endgame"},
|
||||||
|
{"Opening", "opening"},
|
||||||
|
{"Tactic", "tactic"}
|
||||||
|
]
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def render(assigns) do
|
||||||
|
~H"""
|
||||||
|
<Layouts.app flash={@flash} wide>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
|
<.header>
|
||||||
|
Themes
|
||||||
|
<:subtitle>
|
||||||
|
Themes group endgames for filtering and puzzle selection. Deleting a theme detaches
|
||||||
|
it from every endgame and leaves the endgames intact.
|
||||||
|
</:subtitle>
|
||||||
|
<:actions>
|
||||||
|
<.button variant="primary" navigate={~p"/admin/themes/new"}>
|
||||||
|
<.icon name="hero-plus" /> New theme
|
||||||
|
</.button>
|
||||||
|
</:actions>
|
||||||
|
</.header>
|
||||||
|
|
||||||
|
<.form
|
||||||
|
for={@filter_form}
|
||||||
|
id="theme-admin-filter-form"
|
||||||
|
phx-change="filter"
|
||||||
|
class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end"
|
||||||
|
>
|
||||||
|
<div class="flex-1 [&>div]:mb-0">
|
||||||
|
<.input
|
||||||
|
field={@filter_form[:search]}
|
||||||
|
type="text"
|
||||||
|
label="Search by name"
|
||||||
|
autocomplete="off"
|
||||||
|
phx-debounce="200"
|
||||||
|
placeholder="Theme name…"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="[&>div]:mb-0 sm:w-56">
|
||||||
|
<.input
|
||||||
|
field={@filter_form[:category]}
|
||||||
|
type="select"
|
||||||
|
label="Category"
|
||||||
|
options={@category_options}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</.form>
|
||||||
|
|
||||||
|
<p :if={@themes == []} class="text-base-content/70">
|
||||||
|
<%= if @has_filters do %>
|
||||||
|
No themes match these filters.
|
||||||
|
<% else %>
|
||||||
|
No themes yet. Themes power endgame filtering and puzzle selection, so start by
|
||||||
|
creating one and attaching it to an endgame.
|
||||||
|
<% end %>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table :if={@themes != []} class={table_class()}>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Category</th>
|
||||||
|
<th>Used by</th>
|
||||||
|
<th><span class="sr-only">Actions</span></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="themes">
|
||||||
|
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
|
||||||
|
<td>{theme.name}</td>
|
||||||
|
<td>{theme.category}</td>
|
||||||
|
<td>
|
||||||
|
<span id={"theme-usage-#{theme.id}"}>{usage_label(usage_count)}</span>
|
||||||
|
</td>
|
||||||
|
<td class="w-0 font-semibold">
|
||||||
|
<div class="flex gap-4">
|
||||||
|
<.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit</.link>
|
||||||
|
<.link
|
||||||
|
phx-click="delete"
|
||||||
|
phx-value-id={theme.id}
|
||||||
|
data-confirm={
|
||||||
|
"Delete #{theme.name}? Used by #{usage_label(usage_count)}. " <>
|
||||||
|
"The endgames will be kept and simply detached."
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</.link>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</Layouts.app>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def mount(_params, _session, socket) do
|
||||||
|
{:ok,
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, "Themes")
|
||||||
|
|> assign(:search, "")
|
||||||
|
|> assign(:category, "")
|
||||||
|
|> assign(:has_filters, false)
|
||||||
|
|> assign(:category_options, @category_options)
|
||||||
|
|> assign(:filter_form, to_form(%{"search" => "", "category" => ""}))
|
||||||
|
|> load_themes()}
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_event("filter", params, socket) do
|
||||||
|
search = Map.get(params, "search", socket.assigns.search)
|
||||||
|
category = Map.get(params, "category", socket.assigns.category)
|
||||||
|
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> assign(:search, search)
|
||||||
|
|> assign(:category, category)
|
||||||
|
|> assign(:has_filters, String.trim(search) != "" or category != "")
|
||||||
|
|> load_themes()}
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("delete", %{"id" => id}, socket) do
|
||||||
|
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
|
||||||
|
theme = Themes.get_theme!(id)
|
||||||
|
{:ok, _theme} = Themes.delete_theme(theme)
|
||||||
|
|
||||||
|
socket =
|
||||||
|
socket
|
||||||
|
|> put_flash(:info, "Theme deleted. Attached endgames were kept.")
|
||||||
|
|> load_themes()
|
||||||
|
|
||||||
|
{:noreply, socket}
|
||||||
|
else
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp load_themes(socket) do
|
||||||
|
themes =
|
||||||
|
Themes.list_themes_for_admin(
|
||||||
|
search: socket.assigns.search,
|
||||||
|
category: socket.assigns.category
|
||||||
|
)
|
||||||
|
|
||||||
|
assign(socket, :themes, themes)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp usage_label(1), do: "1 endgame"
|
||||||
|
defp usage_label(count), do: "#{count} endgames"
|
||||||
|
end
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
defmodule ChesstrainerWeb.Admin.UserLive.Index do
|
||||||
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
|
|
||||||
|
@per_page 25
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def render(assigns) do
|
||||||
|
~H"""
|
||||||
|
<Layouts.app flash={@flash} wide>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
|
<.header>
|
||||||
|
Users
|
||||||
|
<:subtitle>
|
||||||
|
Search accounts, review their roles and plans, and open a user to edit them.
|
||||||
|
Admins only see members and moderators.
|
||||||
|
</:subtitle>
|
||||||
|
<:actions>
|
||||||
|
<.button variant="primary" navigate={~p"/admin/users/new"}>
|
||||||
|
<.icon name="hero-plus" /> Invite user
|
||||||
|
</.button>
|
||||||
|
</:actions>
|
||||||
|
</.header>
|
||||||
|
|
||||||
|
<.form for={@filter_form} id="admin-user-search-form" phx-change="search" class="mb-6">
|
||||||
|
<.input
|
||||||
|
field={@filter_form[:search]}
|
||||||
|
type="search"
|
||||||
|
label="Search by email or username"
|
||||||
|
autocomplete="off"
|
||||||
|
phx-debounce="200"
|
||||||
|
placeholder="email or username…"
|
||||||
|
/>
|
||||||
|
</.form>
|
||||||
|
|
||||||
|
<p :if={@users == []} class="text-base-content/70">
|
||||||
|
<%= if @search == "" do %>
|
||||||
|
No users are visible to you yet.
|
||||||
|
<% else %>
|
||||||
|
No users match “{@search}”.
|
||||||
|
<% end %>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table :if={@users != []} class={table_class()}>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Username</th>
|
||||||
|
<th>Email</th>
|
||||||
|
<th>Role</th>
|
||||||
|
<th>Plan</th>
|
||||||
|
<th>Confirmed</th>
|
||||||
|
<th>Created</th>
|
||||||
|
<th><span class="sr-only">Actions</span></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="admin-users">
|
||||||
|
<tr :for={user <- @users} id={"user-" <> user.id}>
|
||||||
|
<td>{user.username}</td>
|
||||||
|
<td>{user.email}</td>
|
||||||
|
<td>{user.role}</td>
|
||||||
|
<td>{user.plan}</td>
|
||||||
|
<td>{confirmed_label(user)}</td>
|
||||||
|
<td>{format_date(user.inserted_at)}</td>
|
||||||
|
<td class="w-0 font-semibold">
|
||||||
|
<.link navigate={~p"/admin/users/#{user.id}"}>View</.link>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="mt-4 flex flex-wrap items-center justify-between gap-3 text-sm text-base-content/70">
|
||||||
|
<p>
|
||||||
|
Page {@page} of {@total_pages} · {@count} {if @count == 1, do: "user", else: "users"}
|
||||||
|
</p>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<.button
|
||||||
|
:if={@page > 1}
|
||||||
|
variant="secondary"
|
||||||
|
phx-click="previous_page"
|
||||||
|
id="previous-page"
|
||||||
|
>
|
||||||
|
Previous
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
:if={@page < @total_pages}
|
||||||
|
variant="secondary"
|
||||||
|
phx-click="next_page"
|
||||||
|
id="next-page"
|
||||||
|
>
|
||||||
|
Next
|
||||||
|
</.button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Layouts.app>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def mount(_params, _session, socket) do
|
||||||
|
socket =
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, "Users")
|
||||||
|
|> assign(:search, "")
|
||||||
|
|> assign(:page, 1)
|
||||||
|
|> assign(:users, [])
|
||||||
|
|> assign(:count, 0)
|
||||||
|
|> assign(:total_pages, 1)
|
||||||
|
|> assign(:filter_form, to_form(%{"search" => ""}))
|
||||||
|
|
||||||
|
case load_users(socket) do
|
||||||
|
{:ok, socket} -> {:ok, socket}
|
||||||
|
{:error, :unauthorized} -> {:ok, redirect_unauthorized(socket)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_event("search", %{"search" => search}, socket) do
|
||||||
|
case load_users(assign(socket, search: search, page: 1)) do
|
||||||
|
{:ok, socket} -> {:noreply, socket}
|
||||||
|
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("previous_page", _params, socket) do
|
||||||
|
case load_users(assign(socket, :page, max(socket.assigns.page - 1, 1))) do
|
||||||
|
{:ok, socket} -> {:noreply, socket}
|
||||||
|
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("next_page", _params, socket) do
|
||||||
|
case load_users(assign(socket, :page, socket.assigns.page + 1)) do
|
||||||
|
{:ok, socket} -> {:noreply, socket}
|
||||||
|
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp load_users(socket) do
|
||||||
|
scope = socket.assigns.current_scope
|
||||||
|
search = socket.assigns.search
|
||||||
|
|
||||||
|
case Accounts.count_users_for_admin(scope, search: search) do
|
||||||
|
{:ok, count} ->
|
||||||
|
total_pages = max(div(count + @per_page - 1, @per_page), 1)
|
||||||
|
page = min(socket.assigns.page, total_pages)
|
||||||
|
|
||||||
|
case Accounts.list_users_for_admin(scope, search: search, page: page) do
|
||||||
|
{:ok, users} ->
|
||||||
|
{:ok,
|
||||||
|
assign(socket, users: users, count: count, total_pages: total_pages, page: page)}
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:error, :unauthorized}
|
||||||
|
end
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:error, :unauthorized}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp redirect_unauthorized(socket) do
|
||||||
|
socket
|
||||||
|
|> put_flash(:error, "You are not authorized to manage users.")
|
||||||
|
|> push_navigate(to: ~p"/")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp confirmed_label(%{confirmed_at: nil}), do: "No"
|
||||||
|
defp confirmed_label(_user), do: "Yes"
|
||||||
|
|
||||||
|
defp format_date(nil), do: ""
|
||||||
|
|
||||||
|
defp format_date(%DateTime{} = datetime) do
|
||||||
|
Calendar.strftime(datetime, "%Y-%m-%d")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
defmodule ChesstrainerWeb.Admin.UserLive.New do
|
||||||
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
|
alias Chesstrainer.Accounts.Policy
|
||||||
|
alias Chesstrainer.Accounts.Role
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
|
|
||||||
|
@plan_options [{"Free", "free"}, {"Premium", "premium"}]
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def render(assigns) do
|
||||||
|
~H"""
|
||||||
|
<Layouts.app flash={@flash}>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
|
<.header>
|
||||||
|
Invite user
|
||||||
|
<:subtitle>
|
||||||
|
We create the account and email a link so the recipient can choose a password.
|
||||||
|
The invite is confirmed immediately, so no separate confirmation step is needed.
|
||||||
|
</:subtitle>
|
||||||
|
</.header>
|
||||||
|
|
||||||
|
<.form for={@form} id="invite-user-form" phx-change="validate" phx-submit="save">
|
||||||
|
<.input
|
||||||
|
field={@form[:email]}
|
||||||
|
type="email"
|
||||||
|
label="Email"
|
||||||
|
autocomplete="off"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<.input
|
||||||
|
field={@form[:username]}
|
||||||
|
type="text"
|
||||||
|
label="Username"
|
||||||
|
autocomplete="off"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<.input
|
||||||
|
field={@form[:role]}
|
||||||
|
type="select"
|
||||||
|
label="Role"
|
||||||
|
options={@role_options}
|
||||||
|
/>
|
||||||
|
<.input
|
||||||
|
field={@form[:plan]}
|
||||||
|
type="select"
|
||||||
|
label="Plan"
|
||||||
|
options={@plan_options}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<.button phx-disable-with="Sending..." variant="primary">Send invitation</.button>
|
||||||
|
<.button navigate={~p"/admin/users"}>Cancel</.button>
|
||||||
|
</footer>
|
||||||
|
</.form>
|
||||||
|
</Layouts.app>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def mount(_params, _session, socket) do
|
||||||
|
{:ok,
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, "Invite user")
|
||||||
|
|> assign(:role_options, role_options(socket.assigns.current_scope))
|
||||||
|
|> assign(:plan_options, @plan_options)
|
||||||
|
|> assign(
|
||||||
|
:form,
|
||||||
|
to_form(%{"email" => "", "username" => "", "role" => "member", "plan" => "free"},
|
||||||
|
as: :user
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_event("validate", %{"user" => user_params}, socket) do
|
||||||
|
changeset =
|
||||||
|
%User{}
|
||||||
|
|> User.invite_changeset(user_params)
|
||||||
|
|> User.admin_changeset(user_params)
|
||||||
|
|> Map.put(:action, :validate)
|
||||||
|
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("save", %{"user" => user_params}, socket) do
|
||||||
|
case Accounts.invite_user_as_admin(
|
||||||
|
socket.assigns.current_scope,
|
||||||
|
user_params,
|
||||||
|
&url(~p"/users/reset-password/#{&1}")
|
||||||
|
) do
|
||||||
|
{:ok, user} ->
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> put_flash(:info, "Invitation sent to #{user.email}.")
|
||||||
|
|> push_navigate(to: ~p"/admin/users")}
|
||||||
|
|
||||||
|
{:error, %Ecto.Changeset{} = changeset} ->
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to assign that role.")}
|
||||||
|
|
||||||
|
{:error, _reason} ->
|
||||||
|
{:noreply,
|
||||||
|
put_flash(socket, :error, "The invitation could not be sent. Please try again.")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp role_options(scope) do
|
||||||
|
for role <- Role.values(),
|
||||||
|
Policy.can_assign_role?(scope, role),
|
||||||
|
do: {role_label(role), role}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp role_label(:super_admin), do: "Super admin"
|
||||||
|
defp role_label(role), do: role |> Atom.to_string() |> String.capitalize()
|
||||||
|
end
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
defmodule ChesstrainerWeb.Admin.UserLive.Show do
|
||||||
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
|
alias Chesstrainer.Accounts.Policy
|
||||||
|
alias Chesstrainer.Accounts.Role
|
||||||
|
|
||||||
|
@plan_options [{"Free", "free"}, {"Premium", "premium"}]
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def render(assigns) do
|
||||||
|
~H"""
|
||||||
|
<Layouts.app flash={@flash} wide>
|
||||||
|
<Layouts.admin_nav current_scope={@current_scope} />
|
||||||
|
|
||||||
|
<div id="admin-user-page">
|
||||||
|
<.header>
|
||||||
|
{@user.username}
|
||||||
|
<:subtitle>Account details and administrator controls.</:subtitle>
|
||||||
|
<:actions>
|
||||||
|
<.button navigate={~p"/admin/users"}>
|
||||||
|
<.icon name="hero-arrow-left" /> All users
|
||||||
|
</.button>
|
||||||
|
</:actions>
|
||||||
|
</.header>
|
||||||
|
|
||||||
|
<.list>
|
||||||
|
<:item title="Email">{@user.email}</:item>
|
||||||
|
<:item title="Username">{@user.username}</:item>
|
||||||
|
<:item title="Role">{@user.role}</:item>
|
||||||
|
<:item title="Plan">{@user.plan}</:item>
|
||||||
|
<:item title="Confirmed">{confirmed_label(@user)}</:item>
|
||||||
|
<:item title="Rating">{round(@user.rating)}</:item>
|
||||||
|
<:item title="Created">{format_datetime(@user.inserted_at)}</:item>
|
||||||
|
<:item title="Last updated">{format_datetime(@user.updated_at)}</:item>
|
||||||
|
</.list>
|
||||||
|
|
||||||
|
<section class="mt-8">
|
||||||
|
<h2 class="text-lg font-semibold">Role and plan</h2>
|
||||||
|
|
||||||
|
<.form
|
||||||
|
:if={@can_manage}
|
||||||
|
for={@form}
|
||||||
|
id="admin-user-form"
|
||||||
|
phx-change="validate"
|
||||||
|
phx-submit="save"
|
||||||
|
class="mt-4"
|
||||||
|
>
|
||||||
|
<.input
|
||||||
|
field={@form[:role]}
|
||||||
|
type="select"
|
||||||
|
label="Role"
|
||||||
|
options={@role_options}
|
||||||
|
/>
|
||||||
|
<.input
|
||||||
|
field={@form[:plan]}
|
||||||
|
type="select"
|
||||||
|
label="Plan"
|
||||||
|
options={@plan_options}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<.button phx-disable-with="Saving..." variant="primary">Save changes</.button>
|
||||||
|
</footer>
|
||||||
|
</.form>
|
||||||
|
|
||||||
|
<p :if={!@can_manage} class="mt-4 text-sm text-base-content/70">
|
||||||
|
You can view this account but not change its role or plan.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section :if={@can_manage} class="mt-8 border-t border-base-200 pt-6">
|
||||||
|
<h2 class="text-lg font-semibold">Account emails</h2>
|
||||||
|
<p class="mt-1 text-sm text-base-content/70">
|
||||||
|
These actions send email through the configured mailer. In development the messages
|
||||||
|
appear in the Swoosh mailbox at <code>/dev/mailbox</code>.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="mt-4 flex flex-wrap gap-2">
|
||||||
|
<.button
|
||||||
|
:if={is_nil(@user.confirmed_at)}
|
||||||
|
variant="secondary"
|
||||||
|
phx-click="resend_confirmation"
|
||||||
|
id="resend-confirmation"
|
||||||
|
>
|
||||||
|
Resend confirmation email
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
variant="secondary"
|
||||||
|
phx-click="send_password_reset"
|
||||||
|
id="send-password-reset"
|
||||||
|
>
|
||||||
|
Send password reset email
|
||||||
|
</.button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</Layouts.app>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def mount(%{"id" => id}, _session, socket) do
|
||||||
|
case Accounts.get_user_for_admin(socket.assigns.current_scope, id) do
|
||||||
|
{:ok, user} ->
|
||||||
|
{:ok, assign_user(socket, user)}
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:ok,
|
||||||
|
socket
|
||||||
|
|> put_flash(:error, "You are not authorized to view that user.")
|
||||||
|
|> push_navigate(to: ~p"/admin/users")}
|
||||||
|
|
||||||
|
{:error, :not_found} ->
|
||||||
|
{:ok,
|
||||||
|
socket
|
||||||
|
|> put_flash(:error, "User not found.")
|
||||||
|
|> push_navigate(to: ~p"/admin/users")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_event("validate", %{"user" => user_params}, socket) do
|
||||||
|
if socket.assigns.can_manage do
|
||||||
|
changeset =
|
||||||
|
socket.assigns.user
|
||||||
|
|> Accounts.change_user_as_admin(user_params)
|
||||||
|
|> Map.put(:action, :validate)
|
||||||
|
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
|
||||||
|
else
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("save", %{"user" => user_params}, socket) do
|
||||||
|
case Accounts.update_user_as_admin(
|
||||||
|
socket.assigns.current_scope,
|
||||||
|
socket.assigns.user,
|
||||||
|
user_params
|
||||||
|
) do
|
||||||
|
{:ok, user} ->
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> assign_user(user)
|
||||||
|
|> put_flash(:info, "User updated successfully.")}
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")}
|
||||||
|
|
||||||
|
{:error, :own_role} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "You cannot change your own role.")}
|
||||||
|
|
||||||
|
{:error, :last_super_admin} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "You cannot demote the last super admin.")}
|
||||||
|
|
||||||
|
{:error, %Ecto.Changeset{} = changeset} ->
|
||||||
|
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("resend_confirmation", _params, socket) do
|
||||||
|
case Accounts.resend_user_confirmation_instructions_as_admin(
|
||||||
|
socket.assigns.current_scope,
|
||||||
|
socket.assigns.user,
|
||||||
|
&url(~p"/users/confirm/#{&1}")
|
||||||
|
) do
|
||||||
|
{:ok, _email} ->
|
||||||
|
{:noreply, put_flash(socket, :info, "Confirmation email sent.")}
|
||||||
|
|
||||||
|
{:error, :already_confirmed} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "That account is already confirmed.")}
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to email this user.")}
|
||||||
|
|
||||||
|
{:error, _reason} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "The confirmation email could not be sent.")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("send_password_reset", _params, socket) do
|
||||||
|
case Accounts.send_user_reset_password_instructions_as_admin(
|
||||||
|
socket.assigns.current_scope,
|
||||||
|
socket.assigns.user,
|
||||||
|
&url(~p"/users/reset-password/#{&1}")
|
||||||
|
) do
|
||||||
|
{:ok, _email} ->
|
||||||
|
{:noreply, put_flash(socket, :info, "Password reset email sent.")}
|
||||||
|
|
||||||
|
{:error, :unauthorized} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "You are not authorized to email this user.")}
|
||||||
|
|
||||||
|
{:error, _reason} ->
|
||||||
|
{:noreply, put_flash(socket, :error, "The password reset email could not be sent.")}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp assign_user(socket, user) do
|
||||||
|
can_manage = Policy.can_manage_user?(socket.assigns.current_scope, user)
|
||||||
|
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, user.username)
|
||||||
|
|> assign(:user, user)
|
||||||
|
|> assign(:can_manage, can_manage)
|
||||||
|
|> assign(:plan_options, @plan_options)
|
||||||
|
|> assign(:role_options, role_options(socket.assigns.current_scope))
|
||||||
|
|> assign(:form, to_form(Accounts.change_user_as_admin(user)))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp role_options(scope) do
|
||||||
|
for role <- Role.values(),
|
||||||
|
Policy.can_assign_role?(scope, role),
|
||||||
|
do: {role_label(role), role}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp role_label(:super_admin), do: "Super admin"
|
||||||
|
defp role_label(role), do: role |> Atom.to_string() |> String.capitalize()
|
||||||
|
|
||||||
|
defp confirmed_label(%{confirmed_at: nil}), do: "No"
|
||||||
|
defp confirmed_label(_user), do: "Yes"
|
||||||
|
|
||||||
|
defp format_datetime(nil), do: "—"
|
||||||
|
|
||||||
|
defp format_datetime(%DateTime{} = datetime) do
|
||||||
|
Calendar.strftime(datetime, "%Y-%m-%d %H:%M UTC")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -13,6 +13,8 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
def render(assigns) do
|
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