diff --git a/README.md b/README.md index 2781ba8..cc81f88 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,11 @@ Built with FastAPI, vanilla JS, and MySQL — fully containerized with Docker Co - **Bottle fill bar** — visual level indicator based on your configured bottle size - **Community page** — public leaderboard of all bottles; click any card to see a searchable, alphabetical bourbon list - **Settings modal** — update display name, bottle size, timezone, and password from any page via the gear icon -- **Admin panel** — list all users, reset passwords, disable/enable accounts, delete users, and impersonate any user for debugging -- **JWT auth** — Bearer token auth with impersonation support (admin tokens carry an `admin_id` claim) +- **Admin panel** — separate out-of-band admin login (not a user account) with Users, Notifications, Backups and Reset tabs +- **Backups** — scheduled and on-demand full database dumps to an NFS share, with restore (entries only or all data) +- **JWT auth** — Bearer token auth; admin tokens are a separate credential (`admin: true` claim, no user `sub`) - **About page** — public explainer on what an infinity bottle is, why to track it, and how to get started -- **Push notifications** — Ntfy alerts for admin logins, new registrations, and account changes +- **Push notifications** — Ntfy alerts for admin logins, new registrations, account changes, resets and restores — configured in the admin panel ## Stack @@ -30,7 +31,9 @@ Built with FastAPI, vanilla JS, and MySQL — fully containerized with Docker Co | Reverse Proxy | Nginx 1.31.9 (Alpine) | | Auth | JWT via `python-jose` 3.5.0, passwords hashed with `passlib[bcrypt]` 1.7.4 (bcrypt 4.0.1) | | Rate limiting | `slowapi` 0.1.10 | -| Notifications | `ntfy` (optional) | +| Notifications | `ntfy` (optional, configured in the admin panel) | +| Scheduling | `apscheduler` 3.11.3 (backup schedule) | +| Backups | `mariadb-dump` / `mariadb` client (works against the MySQL 8 server) | | Container | Docker Compose | ## Project Structure @@ -39,44 +42,51 @@ Built with FastAPI, vanilla JS, and MySQL — fully containerized with Docker Co bourbonacci/ ├── backend/ │ ├── app/ -│ │ ├── main.py # FastAPI app entry point, lifespan (DB init + admin seed) +│ │ ├── main.py # FastAPI app entry point, lifespan (DB init + backup scheduler) │ │ ├── config.py # Pydantic settings (reads from .env) │ │ ├── database.py # Async engine, session factory, Base, init_db() │ │ ├── dependencies.py # get_db, get_current_user, get_current_admin │ │ ├── limiter.py # slowapi rate limiter instance +│ │ ├── scheduler.py # APScheduler job for scheduled backups │ │ ├── models/ │ │ │ ├── user.py # User ORM model -│ │ │ └── entry.py # Entry ORM model (add/remove types) +│ │ │ ├── entry.py # Entry ORM model (add/remove types) +│ │ │ └── admin_settings.py # Single-row admin config (ntfy, backup schedule, admin lockout) │ │ ├── routers/ │ │ │ ├── auth.py # POST /api/auth/register, /api/auth/login │ │ │ ├── users.py # GET/PUT /api/users/me, PUT /api/users/me/password │ │ │ ├── entries.py # CRUD /api/entries, GET /api/entries/stats │ │ │ ├── public.py # GET /api/public/stats (unauthenticated) -│ │ │ └── admin.py # Admin user management + impersonation +│ │ │ ├── admin.py # Admin login, user management, ntfy settings, reset +│ │ │ └── backups.py # Backup schedule, run now, list, restore, delete │ │ ├── schemas/ │ │ │ ├── user.py # Pydantic schemas for user/auth -│ │ │ └── entry.py # Pydantic schemas for entries/stats +│ │ │ ├── entry.py # Pydantic schemas for entries/stats +│ │ │ └── admin.py # Pydantic schemas for admin panel + backups +│ │ ├── services/ +│ │ │ └── backup.py # mariadb-dump / restore, retention pruning │ │ └── utils/ -│ │ ├── security.py # JWT creation/decode, password hashing -│ │ └── notify.py # Ntfy push notification helper +│ │ ├── security.py # JWT creation/decode (user + admin tokens), password hashing +│ │ ├── crypto.py # Fernet encryption (from SECRET_KEY) for the stored ntfy token +│ │ └── notify.py # Ntfy push notification helper (reads admin settings) │ ├── Dockerfile │ └── requirements.txt ├── frontend/ │ ├── index.html # Landing page + public community bottles │ ├── about.html # What is an infinity bottle? + Bourbonacci explainer -│ ├── login.html +│ ├── login.html # User login; falls back to admin login │ ├── register.html │ ├── dashboard.html # My Bottle — stats, fill bar, entry log │ ├── log.html # Log add or remove entries │ ├── profile.html # Profile settings (display name, timezone, password) -│ ├── admin.html # Admin user management panel +│ ├── admin.html # Admin panel (Users / Notifications / Backups / Reset) │ ├── css/style.css # Bourbon-themed dark UI │ └── js/ -│ ├── api.js # Fetch wrapper, token injection, escHtml, admin API +│ ├── api.js # Fetch wrapper, token injection, escHtml │ ├── auth.js # Auth state, nav rendering, settings modal -│ └── admin.js # Admin page logic (user table, modals, impersonation) +│ └── admin.js # Admin panel logic (own admin token + API client) ├── nginx/ -│ └── default.conf # Serves frontend, proxies /api/ to backend:8000 +│ └── default.conf # Serves frontend (no-cache), proxies /api/ to backend:8000 ├── docker-compose.yml └── .env.example ``` @@ -87,23 +97,33 @@ bourbonacci/ |---|---|---| | `/index.html` | No | Landing page with community bottle cards; click to browse bourbons | | `/about.html` | No | What is an infinity bottle? Why Bourbonacci? How to get started | -| `/login.html` | No | Login form — redirects to `/index.html` on success | +| `/login.html` | No | Login form — redirects to `/index.html` on success; admin credentials redirect to `/admin.html` | | `/register.html` | No | Registration form | | `/dashboard.html` | Yes | My Bottle — stats, fill bar, full entry log with delete | | `/log.html` | Yes | Log an add or remove entry (date defaults to today in your saved timezone) | | `/profile.html` | Yes | Edit display name, timezone, bottle size, password | -| `/admin.html` | Admin | User management — reset PW, disable, impersonate, delete | +| `/admin.html` | Admin | Admin panel — Users, Notifications, Backups, Reset | ## Navigation The top-right nav area shows (when logged in): - **Display name** — non-clickable label -- **Admin** button — only visible to admin accounts, links to `/admin.html` - **⚙ Settings** button — opens a modal to update display name, bottle size, timezone, and password - **Logout** button -When impersonating a user, the nav shows **"Viewing as [name]"** and a **Return to Admin** button. +## Admin Panel + +The admin is an out-of-band login defined by `ADMIN_USERNAME` / `ADMIN_PASSWORD` in `.env` — not a row in `users`. Sign in from the normal login page: if the user login is rejected, the page tries the admin login and, on success, opens `/admin.html` with a separate admin token (`bb_admin_token`). After 5 failed admin attempts the admin login locks for 15 minutes (with an ntfy alert). + +| Tab | What it does | +|---|---| +| Users | Search users, reset password (generates a one-time temp password), disable/enable, delete (type the email to confirm) | +| Notifications | Ntfy server URL, topic and access token (token stored encrypted), send a test notification | +| Backups | Schedule (daily/weekly, hour in UTC, retention count, optional subfolder), backup now, list files, restore (`restore entries` or `restore all` typed to confirm), delete | +| Reset | Reset all entries for every user (type `reset entries`); a safety backup runs first and the reset is aborted if it fails | + +Backups are gzipped SQL dumps named `bourbonacci__.sql.gz`, written to `/backups` in the backend container — the NFS volume defined in `docker-compose.yml` (`BACKUP_NFS_HOST` / `BACKUP_NFS_PATH`). The share must be writable by uid 1000 (the backend's `appuser`). A full restore replaces every table, including admin settings, with the backup's contents. ## API Endpoints @@ -136,16 +156,28 @@ When impersonating a user, the nav shows **"Viewing as [name]"** and a **Return ### Admin | Method | Path | Auth | Description | |---|---|---|---| -| GET | `/api/admin/users` | Admin | List all users | -| POST | `/api/admin/users` | Admin | Create a user | -| POST | `/api/admin/users/{id}/reset-password` | Admin | Force-reset a user's password | +| POST | `/api/admin/login` | No (5/min) | Admin login with `ADMIN_USERNAME` / `ADMIN_PASSWORD`, returns admin JWT | +| GET | `/api/admin/users` | Admin | List all users with entry counts | +| POST | `/api/admin/users/{id}/reset-password` | Admin | Generate and return a temporary password | | POST | `/api/admin/users/{id}/disable` | Admin | Disable a user account | | POST | `/api/admin/users/{id}/enable` | Admin | Re-enable a user account | | DELETE | `/api/admin/users/{id}` | Admin | Hard-delete a user and all their data | -| POST | `/api/admin/users/{id}/impersonate` | Admin | Get a token scoped as that user | -| POST | `/api/admin/unimpersonate` | Admin | Exchange impersonation token back for admin token | +| GET | `/api/admin/ntfy-settings` | Admin | Get ntfy server/topic (token reported only as `has_token`) | +| PUT | `/api/admin/ntfy-settings` | Admin | Update ntfy server/topic/token | +| POST | `/api/admin/ntfy-settings/test` | Admin | Send a test notification | +| POST | `/api/admin/reset/entries` | Admin | Safety backup, then delete every entry for every user | -Authenticated routes expect `Authorization: Bearer ` header. +### Backups +| Method | Path | Auth | Description | +|---|---|---|---| +| GET | `/api/admin/backups/settings` | Admin | Get schedule + last backup status | +| PUT | `/api/admin/backups/settings` | Admin | Update schedule, retention, subfolder | +| GET | `/api/admin/backups` | Admin | List backup files | +| POST | `/api/admin/backups/run` | Admin | Run a backup now | +| POST | `/api/admin/backups/{filename}/restore` | Admin | Restore (`{"scope": "entries"}` or `{"scope": "all"}`) | +| DELETE | `/api/admin/backups/{filename}` | Admin | Delete a backup file | + +Authenticated routes expect `Authorization: Bearer ` header. Admin routes require an admin token; user tokens are rejected there and vice versa. ### Entry Schema @@ -200,7 +232,7 @@ docker compose up -d The app will be available at `http://localhost:8057` by default (configure the port mapping in `docker-compose.yml`). -The backend waits for MySQL to pass its healthcheck before starting. Tables are created automatically on first boot via SQLAlchemy's `create_all`. The admin account defined in `.env` is seeded on first boot — subsequent restarts will not overwrite a manually changed password. +The backend waits for MySQL to pass its healthcheck before starting. Tables are created automatically on first boot via SQLAlchemy's `create_all`. Sign in with `ADMIN_USERNAME` / `ADMIN_PASSWORD` to reach the admin panel, then set up notifications and the backup schedule there. ### Stop @@ -221,28 +253,35 @@ docker compose down -v | `DATABASE_URL` | Yes | SQLAlchemy async DSN (`mysql+aiomysql://user:pass@db:3306/dbname`) | | `SECRET_KEY` | Yes | JWT signing secret — keep long and random | | `ACCESS_TOKEN_EXPIRE_MINUTES` | No | JWT TTL in minutes (default: `480`) | -| `ADMIN_USERNAME` | Yes | Admin account email, seeded on first boot | -| `ADMIN_PASSWORD` | Yes | Admin account password, seeded on first boot | +| `ADMIN_USERNAME` | No | Out-of-band admin login username — must not match any user's email. Leave blank (with the password) to disable the admin panel. | +| `ADMIN_PASSWORD` | No | Out-of-band admin login password | | `ALLOWED_ORIGINS` | No | Comma-separated CORS origins (default: `http://localhost`) | -| `NTFY_URL` | No | Full Ntfy topic URL (e.g. `https://ntfy.example.com/my-topic`). Leave blank to disable notifications. | -| `NTFY_TOKEN` | No | Ntfy access token for protected topics | +| `BACKUP_NFS_HOST` | No | NFS server for the backups volume (default: `172.16.21.51`) | +| `BACKUP_NFS_PATH` | No | NFS export for the backups volume (default: `/mnt/pool1/bourbonacci-backups`) | ## Ntfy Notifications -When `NTFY_URL` is set, the following events trigger push notifications: +Configured in the admin panel (Notifications tab). Once a server URL and topic are saved, the following events trigger push notifications: | Event | Priority | |---|---| | New user registration | Default | | Admin login | High | +| Admin login locked out | High | +| Password reset issued | Default | | User account disabled | Default | | User account deleted | Default | +| All entries reset | High | +| Backup restored | High | ## Security - Passwords hashed with bcrypt - JWTs signed with HS256, configurable TTL -- Rate limiting on auth and password change endpoints +- Rate limiting on auth, admin login and password change endpoints +- Admin login lockout after 5 failed attempts (15 minutes) +- Stored ntfy token encrypted with a key derived from `SECRET_KEY` +- Backup files written `0600`; backup filenames and subfolders validated against path traversal - Disabled accounts blocked at login and on every authenticated request - All security headers set in Nginx (HSTS, CSP, X-Frame-Options, etc.) - Gzip compression enabled for text responses @@ -261,7 +300,7 @@ When `NTFY_URL` is set, the following events trigger push notifications: | `display_name` | varchar(100) nullable | | | `timezone` | varchar(50) | default `UTC` | | `bottle_size` | float nullable | user-configured bottle capacity in shots | -| `is_admin` | bool | default false | +| `is_admin` | bool | default false — legacy, unused (admin is out-of-band) | | `is_disabled` | bool | default false | | `created_at` | datetime | server default | @@ -277,3 +316,17 @@ When `NTFY_URL` is set, the following events trigger push notifications: | `amount_shots` | float | default 1.0 | | `notes` | text nullable | | | `created_at` | datetime | server default | + +**admin_settings** (single row, `id = 1`) +| Column | Type | Notes | +|---|---|---| +| `id` | int PK | always 1 | +| `ntfy_server_url` / `ntfy_topic` | varchar(255) nullable | | +| `ntfy_token` | varchar(500) nullable | Fernet-encrypted | +| `backup_enabled` | bool | default false | +| `backup_frequency` | varchar(10) | `daily` or `weekly` | +| `backup_hour` / `backup_weekday` | int | UTC hour 0–23; weekday 0 = Monday | +| `backup_retention` | int | backups kept, default 14 | +| `backup_location` | varchar(255) nullable | optional subfolder under `/backups` | +| `last_backup_at` / `last_backup_status` / `last_backup_error` | | last run result (UTC) | +| `admin_failed_attempts` / `admin_locked_until` | | admin login lockout state (UTC) |