Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c695dfc93b | ||
|
|
6272322f31 |
No files matched your search
+9
-6
@@ -9,13 +9,16 @@ DATABASE_URL=mysql+aiomysql://bourbonacci:changeme_db@db:3306/bourbonacci
|
||||
SECRET_KEY=changeme_generate_a_long_random_string_here
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=480
|
||||
|
||||
# Admin account (seeded on every container start)
|
||||
ADMIN_USERNAME=[email protected]
|
||||
ADMIN_PASSWORD=changeme_admin
|
||||
# Out-of-band admin login (used from the normal sign-in form). Not a real user
|
||||
# account -- must not match any user's email. Leave both blank to disable the
|
||||
# admin panel entirely. Ntfy notifications are configured in the admin panel.
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=set-a-strong-admin-password
|
||||
|
||||
# CORS: comma-separated list of allowed origins
|
||||
ALLOWED_ORIGINS=https://yourdomain.com
|
||||
|
||||
# Ntfy push notifications (optional — leave blank to disable)
|
||||
NTFY_URL=https://ntfy.example.com/your-topic
|
||||
NTFY_TOKEN=
|
||||
# NFS share docker-compose mounts into the backend container at /backups
|
||||
# (admin panel > Backups), so backups live off-host. Must be writable by uid 1000.
|
||||
BACKUP_NFS_HOST=172.16.21.51
|
||||
BACKUP_NFS_PATH=/mnt/pool1/bourbonacci-backups
|
||||
@@ -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_<UTC timestamp>_<random>.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 <token>` 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 <token>` 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) |
|
||||
+9
-1
@@ -2,12 +2,20 @@ FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# mariadb-client provides mariadb-dump / mariadb, used by app/services/backup.py
|
||||
# for the admin panel's backups and restores (works against the MySQL 8 server).
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends mariadb-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY app/ ./app/
|
||||
|
||||
RUN useradd -r -s /bin/false appuser
|
||||
# uid 1000 so the NFS backup share (writable by uid 1000) mounted at /backups works.
|
||||
RUN useradd -r -u 1000 -s /bin/false appuser \
|
||||
&& mkdir -p /backups \
|
||||
&& chown appuser:appuser /backups
|
||||
USER appuser
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -1,4 +1,3 @@
|
||||
from typing import Optional
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
@@ -7,11 +6,10 @@ class Settings(BaseSettings):
|
||||
secret_key: str
|
||||
access_token_expire_minutes: int = 480
|
||||
algorithm: str = "HS256"
|
||||
admin_username: str
|
||||
admin_password: str
|
||||
# Out-of-band admin login (not a DB user). Both must be set to enable it.
|
||||
admin_username: str = ""
|
||||
admin_password: str = ""
|
||||
allowed_origins: str = "http://localhost"
|
||||
ntfy_url: Optional[str] = None
|
||||
ntfy_token: Optional[str] = None
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
|
||||
@@ -14,7 +14,7 @@ class Base(DeclarativeBase):
|
||||
|
||||
async def init_db() -> None:
|
||||
# Import models so their tables are registered on Base.metadata before create_all
|
||||
from app.models import user, entry # noqa: F401
|
||||
from app.models import user, entry, admin_settings # noqa: F401
|
||||
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database import AsyncSessionLocal
|
||||
from app.utils.security import decode_token
|
||||
from app.utils.security import decode_token, is_admin_token
|
||||
|
||||
bearer_scheme = HTTPBearer()
|
||||
|
||||
@@ -37,7 +37,7 @@ async def get_current_user(
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_admin(current_user=Depends(get_current_user)):
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
||||
return current_user
|
||||
async def get_current_admin(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)) -> None:
|
||||
# Out-of-band admin: authenticated by an admin-only JWT, not a DB user.
|
||||
if not is_admin_token(credentials.credentials):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Admin access required")
|
||||
+6
-23
@@ -3,14 +3,14 @@ from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy import select
|
||||
from slowapi import _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
|
||||
from app.config import settings
|
||||
from app.database import init_db, AsyncSessionLocal
|
||||
from app import scheduler
|
||||
from app.database import init_db
|
||||
from app.limiter import limiter
|
||||
from app.routers import auth, users, entries, public, admin
|
||||
from app.routers import auth, users, entries, public, admin, backups
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -19,31 +19,13 @@ logging.basicConfig(
|
||||
logger = logging.getLogger("bourbonacci")
|
||||
|
||||
|
||||
async def _seed_admin() -> None:
|
||||
from app.models.user import User
|
||||
from app.utils.security import hash_password
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
result = await db.execute(select(User).where(User.email == settings.admin_username))
|
||||
user = result.scalar_one_or_none()
|
||||
if user is None:
|
||||
db.add(User(
|
||||
email=settings.admin_username,
|
||||
password_hash=hash_password(settings.admin_password),
|
||||
display_name="Admin",
|
||||
is_admin=True,
|
||||
))
|
||||
elif not user.is_admin:
|
||||
user.is_admin = True
|
||||
await db.commit()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await init_db()
|
||||
await _seed_admin()
|
||||
await scheduler.start()
|
||||
logger.info("Bourbonacci started")
|
||||
yield
|
||||
scheduler.shutdown()
|
||||
logger.info("Bourbonacci shutting down")
|
||||
|
||||
|
||||
@@ -64,6 +46,7 @@ app.include_router(users.router)
|
||||
app.include_router(entries.router)
|
||||
app.include_router(public.router)
|
||||
app.include_router(admin.router)
|
||||
app.include_router(backups.router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Integer, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class AdminSettings(Base):
|
||||
"""Single-row table (id=1) holding admin-only config that's edited live from the admin panel."""
|
||||
|
||||
__tablename__ = "admin_settings"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
ntfy_server_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
ntfy_topic: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
ntfy_token: Mapped[Optional[str]] = mapped_column(String(500))
|
||||
|
||||
# Scheduled backups (see routers/backups.py, services/backup.py).
|
||||
backup_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
backup_frequency: Mapped[str] = mapped_column(String(10), nullable=False, default="daily")
|
||||
backup_hour: Mapped[int] = mapped_column(Integer, nullable=False, default=3) # 0-23, UTC
|
||||
backup_weekday: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # 0=Mon, used if weekly
|
||||
backup_retention: Mapped[int] = mapped_column(Integer, nullable=False, default=14)
|
||||
# Optional subfolder under the mounted /backups directory.
|
||||
backup_location: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
last_backup_at: Mapped[Optional[datetime]] = mapped_column(DateTime) # UTC
|
||||
last_backup_status: Mapped[Optional[str]] = mapped_column(String(20)) # "success" | "error"
|
||||
last_backup_error: Mapped[Optional[str]] = mapped_column(String(2000))
|
||||
|
||||
# Brute-force protection for the out-of-band admin login.
|
||||
admin_failed_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
admin_locked_until: Mapped[Optional[datetime]] = mapped_column(DateTime) # UTC
|
||||
+206
-114
@@ -1,149 +1,241 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from app.dependencies import get_db, get_current_admin, bearer_scheme
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.dependencies import get_current_admin, get_db
|
||||
from app.limiter import limiter
|
||||
from app.models.admin_settings import AdminSettings
|
||||
from app.models.entry import Entry
|
||||
from app.models.user import User
|
||||
from app.schemas.user import AdminUserCreate, AdminPasswordReset, AdminUserResponse, Token
|
||||
from app.utils.security import hash_password, create_token
|
||||
from app.schemas.admin import (
|
||||
AdminLogin,
|
||||
AdminNtfySettingsOut,
|
||||
AdminNtfySettingsUpdate,
|
||||
AdminTokenOut,
|
||||
AdminUserOut,
|
||||
ResetPasswordOut,
|
||||
ResetResultOut,
|
||||
)
|
||||
from app.services.backup import BackupError, run_backup
|
||||
from app.utils.crypto import encrypt
|
||||
from app.utils.notify import notify
|
||||
from app.utils.security import create_admin_token, hash_password
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[AdminUserResponse])
|
||||
async def list_users(
|
||||
_: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
result = await db.execute(select(User).order_by(User.created_at))
|
||||
return result.scalars().all()
|
||||
MAX_FAILED_ADMIN_ATTEMPTS = 5
|
||||
ADMIN_LOCKOUT_MINUTES = 15
|
||||
|
||||
|
||||
@router.post("/users", response_model=AdminUserResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(
|
||||
body: AdminUserCreate,
|
||||
_: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
result = await db.execute(select(User).where(User.email == body.email))
|
||||
if result.scalar_one_or_none():
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
|
||||
def _utcnow() -> datetime:
|
||||
# MySQL DATETIME columns are naive; store UTC.
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
user = User(
|
||||
email=body.email,
|
||||
password_hash=hash_password(body.password),
|
||||
display_name=body.display_name or body.email.split("@")[0],
|
||||
is_admin=False,
|
||||
|
||||
async def _get_admin_settings(db: AsyncSession) -> AdminSettings:
|
||||
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
|
||||
if not row:
|
||||
row = AdminSettings(id=1)
|
||||
db.add(row)
|
||||
await db.flush()
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/login", response_model=AdminTokenOut)
|
||||
@limiter.limit("5/minute")
|
||||
async def admin_login(request: Request, body: AdminLogin, db: AsyncSession = Depends(get_db)):
|
||||
if not settings.admin_username or not settings.admin_password:
|
||||
raise HTTPException(status_code=503, detail="Admin login is not configured")
|
||||
|
||||
row = await _get_admin_settings(db)
|
||||
|
||||
if row.admin_locked_until and row.admin_locked_until > _utcnow():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Admin login temporarily locked after repeated failed attempts. Try again later.",
|
||||
)
|
||||
db.add(user)
|
||||
|
||||
ok_user = secrets.compare_digest(body.username.encode(), settings.admin_username.encode())
|
||||
ok_pass = secrets.compare_digest(body.password.encode(), settings.admin_password.encode())
|
||||
if not (ok_user and ok_pass):
|
||||
row.admin_failed_attempts += 1
|
||||
if row.admin_failed_attempts >= MAX_FAILED_ADMIN_ATTEMPTS:
|
||||
row.admin_locked_until = _utcnow() + timedelta(minutes=ADMIN_LOCKOUT_MINUTES)
|
||||
row.admin_failed_attempts = 0
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
await notify(
|
||||
"Admin login locked",
|
||||
f"Admin login was locked out after {MAX_FAILED_ADMIN_ATTEMPTS} failed attempts.",
|
||||
priority="high",
|
||||
tags=["warning", "rotating_light"],
|
||||
)
|
||||
else:
|
||||
await db.commit()
|
||||
raise HTTPException(status_code=401, detail="Invalid admin credentials")
|
||||
|
||||
row.admin_failed_attempts = 0
|
||||
row.admin_locked_until = None
|
||||
await db.commit()
|
||||
await notify("Admin login", "Successful admin login.", priority="high", tags=["closed_lock_with_key"])
|
||||
|
||||
return AdminTokenOut(access_token=create_admin_token())
|
||||
|
||||
|
||||
# ── Users ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/users", response_model=list[AdminUserOut], dependencies=[Depends(get_current_admin)])
|
||||
async def list_users(db: AsyncSession = Depends(get_db)):
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(User, func.count(Entry.id))
|
||||
.outerjoin(Entry, Entry.user_id == User.id)
|
||||
.group_by(User.id)
|
||||
.order_by(func.lower(User.email))
|
||||
)
|
||||
).all()
|
||||
return [
|
||||
AdminUserOut(
|
||||
id=u.id,
|
||||
email=u.email,
|
||||
display_name=u.display_name,
|
||||
created_at=u.created_at,
|
||||
is_disabled=u.is_disabled,
|
||||
entry_count=count,
|
||||
)
|
||||
for u, count in rows
|
||||
]
|
||||
|
||||
|
||||
async def _get_user(user_id: int, db: AsyncSession) -> User:
|
||||
user = (await db.execute(select(User).where(User.id == user_id))).scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/reset-password", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def reset_password(
|
||||
user_id: int,
|
||||
body: AdminPasswordReset,
|
||||
_: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
|
||||
user.password_hash = hash_password(body.new_password)
|
||||
@router.post(
|
||||
"/users/{user_id}/reset-password",
|
||||
response_model=ResetPasswordOut,
|
||||
dependencies=[Depends(get_current_admin)],
|
||||
)
|
||||
async def reset_password(user_id: int, db: AsyncSession = Depends(get_db)):
|
||||
user = await _get_user(user_id, db)
|
||||
temp_password = secrets.token_urlsafe(9)
|
||||
user.password_hash = hash_password(temp_password)
|
||||
await db.commit()
|
||||
await notify("Password reset issued", f"A temp password was issued for {user.email}.")
|
||||
return ResetPasswordOut(temp_password=temp_password)
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/disable", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def disable_user(
|
||||
user_id: int,
|
||||
current_admin: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
if user_id == current_admin.id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot disable your own account")
|
||||
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
|
||||
@router.post(
|
||||
"/users/{user_id}/disable",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(get_current_admin)],
|
||||
)
|
||||
async def disable_user(user_id: int, db: AsyncSession = Depends(get_db)):
|
||||
user = await _get_user(user_id, db)
|
||||
user.is_disabled = True
|
||||
await db.commit()
|
||||
await notify("User Disabled", f"Account disabled: {user.email} (by admin {current_admin.email})", priority="default")
|
||||
await notify("User disabled", f"Account disabled: {user.email}")
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/enable", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def enable_user(
|
||||
user_id: int,
|
||||
_: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
|
||||
@router.post(
|
||||
"/users/{user_id}/enable",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(get_current_admin)],
|
||||
)
|
||||
async def enable_user(user_id: int, db: AsyncSession = Depends(get_db)):
|
||||
user = await _get_user(user_id, db)
|
||||
user.is_disabled = False
|
||||
await db.commit()
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
current_admin: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
if user_id == current_admin.id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot delete your own account")
|
||||
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
|
||||
@router.delete(
|
||||
"/users/{user_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(get_current_admin)],
|
||||
)
|
||||
async def delete_user(user_id: int, db: AsyncSession = Depends(get_db)):
|
||||
user = await _get_user(user_id, db)
|
||||
email = user.email
|
||||
await db.delete(user)
|
||||
await db.commit()
|
||||
await notify("User Deleted", f"Account deleted: {user.email} (by admin {current_admin.email})", priority="default")
|
||||
await notify("Account deleted", f"{email} was deleted.", tags=["warning"])
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/impersonate", response_model=Token)
|
||||
async def impersonate_user(
|
||||
user_id: int,
|
||||
current_admin: User = Depends(get_current_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
if user_id == current_admin.id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot impersonate yourself")
|
||||
# ── Notifications ────────────────────────────────────────────────────────────
|
||||
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
|
||||
return Token(access_token=create_token(user.id, admin_id=current_admin.id))
|
||||
def _ntfy_settings_out(row: AdminSettings) -> AdminNtfySettingsOut:
|
||||
return AdminNtfySettingsOut(
|
||||
ntfy_server_url=row.ntfy_server_url,
|
||||
ntfy_topic=row.ntfy_topic,
|
||||
has_token=bool(row.ntfy_token),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/unimpersonate", response_model=Token)
|
||||
async def unimpersonate(
|
||||
credentials=Depends(bearer_scheme),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
from app.utils.security import decode_token_full
|
||||
@router.get("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
|
||||
async def get_ntfy_settings(db: AsyncSession = Depends(get_db)):
|
||||
row = await _get_admin_settings(db)
|
||||
await db.commit()
|
||||
return _ntfy_settings_out(row)
|
||||
|
||||
token = credentials.credentials
|
||||
payload = decode_token_full(token)
|
||||
admin_id = payload.get("admin_id") if payload else None
|
||||
if not admin_id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Not an impersonation token")
|
||||
|
||||
result = await db.execute(select(User).where(User.id == admin_id))
|
||||
admin = result.scalar_one_or_none()
|
||||
if not admin or not admin.is_admin or admin.is_disabled:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin not found")
|
||||
@router.put("/ntfy-settings", response_model=AdminNtfySettingsOut, dependencies=[Depends(get_current_admin)])
|
||||
async def update_ntfy_settings(body: AdminNtfySettingsUpdate, db: AsyncSession = Depends(get_db)):
|
||||
row = await _get_admin_settings(db)
|
||||
if body.ntfy_server_url is not None:
|
||||
row.ntfy_server_url = body.ntfy_server_url.strip() or None
|
||||
if body.ntfy_topic is not None:
|
||||
row.ntfy_topic = body.ntfy_topic.strip() or None
|
||||
if body.ntfy_token is not None:
|
||||
row.ntfy_token = encrypt(body.ntfy_token) if body.ntfy_token else None
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
return _ntfy_settings_out(row)
|
||||
|
||||
return Token(access_token=create_token(admin.id))
|
||||
|
||||
@router.post(
|
||||
"/ntfy-settings/test",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(get_current_admin)],
|
||||
)
|
||||
async def test_ntfy_settings():
|
||||
ok = await notify(
|
||||
"Test notification",
|
||||
"This is a test notification from the Bourbonacci admin panel.",
|
||||
tags=["white_check_mark"],
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=502, detail="Failed to send test notification. Check your ntfy settings.")
|
||||
|
||||
|
||||
# ── Reset ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async def _safety_backup(db: AsyncSession) -> str:
|
||||
"""Run a fresh backup before a destructive reset. Refuses to proceed
|
||||
(raises 502) if the backup itself fails, so a broken backup path can
|
||||
never leave a reset with no safety net."""
|
||||
try:
|
||||
backup = await run_backup(db)
|
||||
except BackupError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Safety backup failed, reset aborted: {exc}")
|
||||
return backup.filename
|
||||
|
||||
|
||||
@router.post("/reset/entries", response_model=ResetResultOut, dependencies=[Depends(get_current_admin)])
|
||||
async def reset_entries(db: AsyncSession = Depends(get_db)):
|
||||
"""Delete every entry for every user. User accounts and settings are untouched."""
|
||||
backup_filename = await _safety_backup(db)
|
||||
result = await db.execute(delete(Entry))
|
||||
await db.commit()
|
||||
await notify(
|
||||
"Entries reset",
|
||||
f"All entries were deleted ({result.rowcount or 0} rows). Safety backup: {backup_filename}",
|
||||
priority="high",
|
||||
tags=["rotating_light"],
|
||||
)
|
||||
return ResetResultOut(entries_deleted=result.rowcount or 0, backup_filename=backup_filename)
|
||||
@@ -37,7 +37,7 @@ async def register(request: Request, body: UserCreate, db: AsyncSession = Depend
|
||||
await db.refresh(user)
|
||||
|
||||
logger.info("New user registered: %s", body.email)
|
||||
await notify("New Registration", f"User registered: {body.email}", priority="default")
|
||||
await notify("New registration", f"User registered: {body.email}", tags=["bust_in_silhouette"])
|
||||
return Token(access_token=create_token(user.id))
|
||||
|
||||
|
||||
@@ -56,6 +56,4 @@ async def login(request: Request, body: LoginRequest, db: AsyncSession = Depends
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
|
||||
|
||||
logger.info("Login: %s (id=%s)", body.email, user.id)
|
||||
if user.is_admin:
|
||||
await notify("Admin Login", f"Admin login: {body.email}", priority="high")
|
||||
return Token(access_token=create_token(user.id))
|
||||
@@ -0,0 +1,104 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app import scheduler
|
||||
from app.dependencies import get_current_admin, get_db
|
||||
from app.models.admin_settings import AdminSettings
|
||||
from app.schemas.admin import (
|
||||
BackupFileOut,
|
||||
BackupSettingsOut,
|
||||
BackupSettingsUpdate,
|
||||
RestoreRequest,
|
||||
RestoreResult,
|
||||
)
|
||||
from app.services.backup import (
|
||||
BackupError,
|
||||
delete_backup,
|
||||
list_backups,
|
||||
normalize_backup_location,
|
||||
restore_backup,
|
||||
run_backup,
|
||||
)
|
||||
from app.utils.notify import notify
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/admin/backups", tags=["backups"], dependencies=[Depends(get_current_admin)]
|
||||
)
|
||||
|
||||
|
||||
async def _get_settings_row(db: AsyncSession) -> AdminSettings:
|
||||
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
|
||||
if not row:
|
||||
row = AdminSettings(id=1)
|
||||
db.add(row)
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/settings", response_model=BackupSettingsOut)
|
||||
async def get_backup_settings(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_settings_row(db)
|
||||
|
||||
|
||||
@router.put("/settings", response_model=BackupSettingsOut)
|
||||
async def update_backup_settings(body: BackupSettingsUpdate, db: AsyncSession = Depends(get_db)):
|
||||
try:
|
||||
location = normalize_backup_location(body.backup_location)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
row = await _get_settings_row(db)
|
||||
row.backup_enabled = body.backup_enabled
|
||||
row.backup_frequency = body.backup_frequency
|
||||
row.backup_hour = body.backup_hour
|
||||
row.backup_weekday = body.backup_weekday
|
||||
row.backup_retention = body.backup_retention
|
||||
row.backup_location = location
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
|
||||
scheduler.reschedule(row.backup_enabled, row.backup_frequency, row.backup_hour, row.backup_weekday)
|
||||
return row
|
||||
|
||||
|
||||
@router.get("", response_model=list[BackupFileOut])
|
||||
async def list_backup_files(db: AsyncSession = Depends(get_db)):
|
||||
row = await _get_settings_row(db)
|
||||
return list_backups(row.backup_location)
|
||||
|
||||
|
||||
@router.post("/run", response_model=BackupFileOut, status_code=status.HTTP_201_CREATED)
|
||||
async def run_backup_now(db: AsyncSession = Depends(get_db)):
|
||||
try:
|
||||
return await run_backup(db)
|
||||
except BackupError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Backup failed: {exc}")
|
||||
|
||||
|
||||
@router.post("/{filename}/restore", response_model=RestoreResult)
|
||||
async def restore_backup_file(filename: str, body: RestoreRequest, db: AsyncSession = Depends(get_db)):
|
||||
try:
|
||||
await restore_backup(filename, body.scope, db)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid backup filename")
|
||||
except FileNotFoundError:
|
||||
raise HTTPException(status_code=404, detail="Backup file not found")
|
||||
except BackupError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Restore failed: {exc}")
|
||||
await notify(
|
||||
"Backup restored",
|
||||
f"Restored '{filename}' (scope: {body.scope}).",
|
||||
priority="high",
|
||||
tags=["rotating_light"],
|
||||
)
|
||||
return RestoreResult(scope=body.scope, filename=filename)
|
||||
|
||||
|
||||
@router.delete("/{filename}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_backup_file(filename: str, db: AsyncSession = Depends(get_db)):
|
||||
row = await _get_settings_row(db)
|
||||
try:
|
||||
delete_backup(filename, row.backup_location)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid backup filename")
|
||||
@@ -0,0 +1,48 @@
|
||||
import logging
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database import AsyncSessionLocal
|
||||
from app.models.admin_settings import AdminSettings
|
||||
from app.services.backup import run_backup
|
||||
|
||||
logger = logging.getLogger("bourbonacci.scheduler")
|
||||
|
||||
_JOB_ID = "scheduled_backup"
|
||||
_scheduler = AsyncIOScheduler(timezone="UTC")
|
||||
|
||||
|
||||
async def _run_scheduled_backup() -> None:
|
||||
async with AsyncSessionLocal() as db:
|
||||
try:
|
||||
await run_backup(db)
|
||||
except Exception:
|
||||
logger.exception("Scheduled backup failed")
|
||||
|
||||
|
||||
def reschedule(enabled: bool, frequency: str, hour: int, weekday: int) -> None:
|
||||
if _scheduler.get_job(_JOB_ID):
|
||||
_scheduler.remove_job(_JOB_ID)
|
||||
if not enabled:
|
||||
return
|
||||
trigger = CronTrigger(
|
||||
hour=hour,
|
||||
minute=0,
|
||||
day_of_week=weekday if frequency == "weekly" else "*",
|
||||
timezone="UTC",
|
||||
)
|
||||
_scheduler.add_job(_run_scheduled_backup, trigger, id=_JOB_ID, replace_existing=True)
|
||||
|
||||
|
||||
async def start() -> None:
|
||||
async with AsyncSessionLocal() as db:
|
||||
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
|
||||
if row:
|
||||
reschedule(row.backup_enabled, row.backup_frequency, row.backup_hour, row.backup_weekday)
|
||||
_scheduler.start()
|
||||
|
||||
|
||||
def shutdown() -> None:
|
||||
_scheduler.shutdown(wait=False)
|
||||
@@ -0,0 +1,96 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
def _as_utc(v: Optional[datetime]) -> Optional[datetime]:
|
||||
# MySQL DATETIME columns come back naive; they're stored as UTC.
|
||||
if v is not None and v.tzinfo is None:
|
||||
return v.replace(tzinfo=timezone.utc)
|
||||
return v
|
||||
|
||||
|
||||
class AdminLogin(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class AdminTokenOut(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class AdminUserOut(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
display_name: Optional[str]
|
||||
created_at: datetime
|
||||
is_disabled: bool
|
||||
entry_count: int
|
||||
|
||||
|
||||
class ResetPasswordOut(BaseModel):
|
||||
temp_password: str
|
||||
|
||||
|
||||
class ResetResultOut(BaseModel):
|
||||
entries_deleted: int = 0
|
||||
# Filename of the safety backup taken automatically right before the reset.
|
||||
backup_filename: Optional[str] = None
|
||||
|
||||
|
||||
class AdminNtfySettingsOut(BaseModel):
|
||||
ntfy_server_url: Optional[str]
|
||||
ntfy_topic: Optional[str]
|
||||
has_token: bool
|
||||
|
||||
|
||||
class AdminNtfySettingsUpdate(BaseModel):
|
||||
ntfy_server_url: Optional[str] = None
|
||||
ntfy_topic: Optional[str] = None
|
||||
ntfy_token: Optional[str] = None
|
||||
|
||||
|
||||
BackupScope = Literal["entries", "all"]
|
||||
BackupFrequency = Literal["daily", "weekly"]
|
||||
|
||||
|
||||
class BackupSettingsOut(BaseModel):
|
||||
backup_enabled: bool
|
||||
backup_frequency: BackupFrequency
|
||||
backup_hour: int
|
||||
backup_weekday: int
|
||||
backup_retention: int
|
||||
backup_location: Optional[str] = None
|
||||
last_backup_at: Optional[datetime] = None
|
||||
last_backup_status: Optional[str] = None
|
||||
last_backup_error: Optional[str] = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
_utc = field_validator("last_backup_at")(_as_utc)
|
||||
|
||||
|
||||
class BackupSettingsUpdate(BaseModel):
|
||||
backup_enabled: bool
|
||||
backup_frequency: BackupFrequency = "daily"
|
||||
backup_hour: int = Field(default=3, ge=0, le=23)
|
||||
backup_weekday: int = Field(default=0, ge=0, le=6)
|
||||
backup_retention: int = Field(default=14, ge=1, le=365)
|
||||
backup_location: Optional[str] = Field(default=None, max_length=255)
|
||||
|
||||
|
||||
class BackupFileOut(BaseModel):
|
||||
filename: str
|
||||
size_bytes: int
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class RestoreRequest(BaseModel):
|
||||
scope: BackupScope
|
||||
|
||||
|
||||
class RestoreResult(BaseModel):
|
||||
scope: BackupScope
|
||||
filename: str
|
||||
@@ -26,7 +26,6 @@ class UserResponse(BaseModel):
|
||||
display_name: Optional[str]
|
||||
timezone: str
|
||||
bottle_size: Optional[float]
|
||||
is_admin: bool
|
||||
created_at: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
@@ -40,25 +39,3 @@ class Token(BaseModel):
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class AdminUserCreate(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
display_name: Optional[str] = None
|
||||
|
||||
|
||||
class AdminPasswordReset(BaseModel):
|
||||
new_password: str
|
||||
|
||||
|
||||
class AdminUserResponse(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
display_name: Optional[str]
|
||||
timezone: str
|
||||
is_admin: bool
|
||||
is_disabled: bool
|
||||
created_at: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
Whitespace-only changes.
@@ -0,0 +1,229 @@
|
||||
import asyncio
|
||||
import gzip
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.engine import make_url
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database import engine
|
||||
from app.models.admin_settings import AdminSettings
|
||||
from app.schemas.admin import BackupFileOut
|
||||
|
||||
logger = logging.getLogger("bourbonacci.backup")
|
||||
|
||||
BACKUP_ROOT = Path("/backups")
|
||||
_FILENAME_PREFIX = "bourbonacci_"
|
||||
_FILENAME_SUFFIX = ".sql.gz"
|
||||
_TABLE_MARKER = re.compile(rb"^-- Table structure for table `([^`]+)`", re.MULTILINE)
|
||||
# First statement of the trailer mysqldump/mariadb-dump writes after the last table.
|
||||
_TRAILER_MARKER = re.compile(rb"^/\*!40103 SET TIME_ZONE=@OLD_TIME_ZONE \*/;", re.MULTILINE)
|
||||
|
||||
|
||||
class BackupError(Exception):
|
||||
"""A mariadb-dump/mariadb subprocess exited non-zero."""
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
# MySQL DATETIME columns are naive; store UTC.
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def _conn_args() -> tuple[list[str], dict[str, str]]:
|
||||
"""Connection flags for the MariaDB CLI tools, derived from DATABASE_URL.
|
||||
The password goes in MYSQL_PWD so it never shows up in the process list."""
|
||||
url = make_url(settings.database_url)
|
||||
args = [
|
||||
"-h", url.host or "localhost",
|
||||
"-P", str(url.port or 3306),
|
||||
"-u", url.username or "",
|
||||
# MySQL 8.4 serves TLS with an auto-generated self-signed cert.
|
||||
"--skip-ssl-verify-server-cert",
|
||||
]
|
||||
env = {**os.environ, "MYSQL_PWD": url.password or ""}
|
||||
return args, env
|
||||
|
||||
|
||||
def _db_name() -> str:
|
||||
return make_url(settings.database_url).database or ""
|
||||
|
||||
|
||||
async def _get_settings(db: AsyncSession) -> AdminSettings:
|
||||
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
|
||||
if not row:
|
||||
row = AdminSettings(id=1)
|
||||
db.add(row)
|
||||
await db.flush()
|
||||
return row
|
||||
|
||||
|
||||
_LOCATION_RE = re.compile(r"^[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$")
|
||||
|
||||
|
||||
def normalize_backup_location(location: str | None) -> str | None:
|
||||
"""Validate the admin's optional backup subfolder: plain folder names
|
||||
(letters, digits, - and _) nested with "/", so it can't point outside
|
||||
BACKUP_ROOT. Raises ValueError otherwise."""
|
||||
location = (location or "").strip().strip("/")
|
||||
if not location:
|
||||
return None
|
||||
if not _LOCATION_RE.match(location):
|
||||
raise ValueError("Subfolder may only contain letters, numbers, - and _, separated by /.")
|
||||
return location
|
||||
|
||||
|
||||
def backup_dir(location: str | None = None) -> Path:
|
||||
d = BACKUP_ROOT / location.strip("/") if location else BACKUP_ROOT
|
||||
# Belt and braces alongside normalize_backup_location: never create or
|
||||
# use a directory outside BACKUP_ROOT, whatever is stored in the row.
|
||||
if not d.resolve().is_relative_to(BACKUP_ROOT.resolve()):
|
||||
raise ValueError("Backup location must be inside the backup directory")
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _resolve_backup_file(filename: str, location: str | None) -> Path:
|
||||
"""Resolve a filename against the backup directory, rejecting anything
|
||||
that escapes it (path traversal via `..`, absolute paths, etc)."""
|
||||
base = backup_dir(location).resolve()
|
||||
candidate = (base / filename).resolve()
|
||||
if not candidate.is_relative_to(base) or candidate.parent != base:
|
||||
raise ValueError("Invalid backup filename")
|
||||
return candidate
|
||||
|
||||
|
||||
def list_backups(location: str | None = None) -> list[BackupFileOut]:
|
||||
d = backup_dir(location)
|
||||
files = [
|
||||
BackupFileOut(
|
||||
filename=f.name,
|
||||
size_bytes=f.stat().st_size,
|
||||
created_at=datetime.fromtimestamp(f.stat().st_mtime, tz=timezone.utc),
|
||||
)
|
||||
for f in d.iterdir()
|
||||
if f.is_file() and f.name.startswith(_FILENAME_PREFIX) and f.name.endswith(_FILENAME_SUFFIX)
|
||||
]
|
||||
files.sort(key=lambda b: b.created_at, reverse=True)
|
||||
return files
|
||||
|
||||
|
||||
def prune_backups(retention: int, location: str | None = None) -> int:
|
||||
files = list_backups(location)
|
||||
to_delete = files[retention:]
|
||||
for f in to_delete:
|
||||
(backup_dir(location) / f.filename).unlink(missing_ok=True)
|
||||
return len(to_delete)
|
||||
|
||||
|
||||
async def _dump_to(path: Path) -> None:
|
||||
conn, env = _conn_args()
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"mariadb-dump", *conn,
|
||||
"--single-transaction", "--no-tablespaces", "--skip-lock-tables",
|
||||
_db_name(),
|
||||
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env,
|
||||
)
|
||||
stderr_task = asyncio.create_task(proc.stderr.read())
|
||||
with gzip.open(path, "wb") as out:
|
||||
while chunk := await proc.stdout.read(65536):
|
||||
out.write(chunk)
|
||||
stderr = await stderr_task
|
||||
await proc.wait()
|
||||
if proc.returncode != 0:
|
||||
raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb-dump exited {proc.returncode}")
|
||||
|
||||
|
||||
async def _load_sql(sql: bytes) -> None:
|
||||
conn, env = _conn_args()
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"mariadb", *conn, _db_name(),
|
||||
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env,
|
||||
)
|
||||
_, stderr = await proc.communicate(input=sql)
|
||||
if proc.returncode != 0:
|
||||
raise BackupError(stderr.decode(errors="replace").strip() or f"mariadb exited {proc.returncode}")
|
||||
|
||||
|
||||
def _extract_table(sql: bytes, table: str) -> bytes:
|
||||
"""Return the dump's header + the given table's DROP/CREATE/INSERT section + trailer,
|
||||
so just that one table can be reloaded from a full-database dump."""
|
||||
markers = list(_TABLE_MARKER.finditer(sql))
|
||||
trailer = _TRAILER_MARKER.search(sql)
|
||||
if not markers or not trailer:
|
||||
raise BackupError("Backup file is not in the expected mysqldump format")
|
||||
header = sql[: markers[0].start()]
|
||||
for i, m in enumerate(markers):
|
||||
if m.group(1).decode() == table:
|
||||
end = markers[i + 1].start() if i + 1 < len(markers) else trailer.start()
|
||||
return header + sql[m.start(): end] + sql[trailer.start():]
|
||||
raise BackupError(f"Backup file has no `{table}` table")
|
||||
|
||||
|
||||
async def run_backup(db: AsyncSession) -> BackupFileOut:
|
||||
row = await _get_settings(db)
|
||||
d = backup_dir(row.backup_location)
|
||||
# A short random suffix guards against two backups landing in the same
|
||||
# second (e.g. rapid "Backup now" clicks), which would otherwise silently
|
||||
# overwrite one another.
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
path = d / f"{_FILENAME_PREFIX}{stamp}_{secrets.token_hex(3)}{_FILENAME_SUFFIX}"
|
||||
|
||||
try:
|
||||
await _dump_to(path)
|
||||
except BackupError as exc:
|
||||
path.unlink(missing_ok=True)
|
||||
row.last_backup_at = _utcnow()
|
||||
row.last_backup_status = "error"
|
||||
row.last_backup_error = str(exc)[:2000]
|
||||
await db.commit()
|
||||
logger.error("Backup failed: %s", exc)
|
||||
raise
|
||||
|
||||
# Full user data in plaintext -- keep it readable only by the app user.
|
||||
path.chmod(0o600)
|
||||
|
||||
prune_backups(row.backup_retention, row.backup_location)
|
||||
|
||||
row.last_backup_at = _utcnow()
|
||||
row.last_backup_status = "success"
|
||||
row.last_backup_error = None
|
||||
await db.commit()
|
||||
|
||||
stat = path.stat()
|
||||
return BackupFileOut(
|
||||
filename=path.name,
|
||||
size_bytes=stat.st_size,
|
||||
created_at=datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc),
|
||||
)
|
||||
|
||||
|
||||
async def restore_backup(filename: str, scope: Literal["entries", "all"], db: AsyncSession) -> None:
|
||||
row = await _get_settings(db)
|
||||
path = _resolve_backup_file(filename, row.backup_location)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(filename)
|
||||
# Reading admin_settings above left this session in an open transaction
|
||||
# holding a metadata lock on that table; a full restore DROPs and
|
||||
# recreates it, which would block on that lock. Close the transaction first.
|
||||
await db.commit()
|
||||
|
||||
sql = await asyncio.to_thread(lambda: gzip.decompress(path.read_bytes()))
|
||||
if scope == "entries":
|
||||
sql = _extract_table(sql, "entries")
|
||||
await _load_sql(sql)
|
||||
|
||||
# Tables were dropped and recreated -- discard pooled connections so none
|
||||
# carries state from before the restore.
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def delete_backup(filename: str, location: str | None) -> None:
|
||||
path = _resolve_backup_file(filename, location)
|
||||
path.unlink(missing_ok=True)
|
||||
@@ -0,0 +1,21 @@
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
# Derived from SECRET_KEY: rotating SECRET_KEY also invalidates any
|
||||
# previously encrypted values (e.g. the stored ntfy token).
|
||||
key = hashlib.sha256(settings.secret_key.encode()).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(key))
|
||||
|
||||
|
||||
def encrypt(value: str) -> str:
|
||||
return _fernet().encrypt(value.encode()).decode()
|
||||
|
||||
|
||||
def decrypt(value: str) -> str:
|
||||
return _fernet().decrypt(value.encode()).decode()
|
||||
+62
-12
@@ -1,19 +1,69 @@
|
||||
import base64
|
||||
import logging
|
||||
import httpx
|
||||
from typing import Optional
|
||||
|
||||
from app.config import settings
|
||||
import httpx
|
||||
from cryptography.fernet import InvalidToken
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database import AsyncSessionLocal
|
||||
from app.utils.crypto import decrypt
|
||||
|
||||
logger = logging.getLogger("bourbonacci.notify")
|
||||
|
||||
|
||||
async def notify(title: str, message: str, priority: str = "default") -> None:
|
||||
if not settings.ntfy_url:
|
||||
return
|
||||
headers = {"Title": f"Bourbonacci Admin - {title}", "Priority": priority}
|
||||
if settings.ntfy_token:
|
||||
headers["Authorization"] = f"Bearer {settings.ntfy_token}"
|
||||
def _header_value(value: str) -> str:
|
||||
# HTTP header values must be ASCII; ntfy decodes RFC 2047 encoded-words,
|
||||
# so send non-ASCII titles/tags that way and leave plain ASCII untouched.
|
||||
if value.isascii():
|
||||
return value
|
||||
return "=?UTF-8?B?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?="
|
||||
|
||||
|
||||
def _normalize_server_url(server_url: str) -> str:
|
||||
server_url = server_url.strip()
|
||||
if not server_url.startswith(("http://", "https://")):
|
||||
server_url = "https://" + server_url
|
||||
return server_url
|
||||
|
||||
|
||||
async def notify(
|
||||
title: str,
|
||||
message: str,
|
||||
priority: str = "default",
|
||||
tags: Optional[list[str]] = None,
|
||||
) -> bool:
|
||||
"""Send an admin push notification using the ntfy settings saved in the
|
||||
admin panel (Notifications tab). Returns False if not configured or the
|
||||
send failed; never raises."""
|
||||
from app.models.admin_settings import AdminSettings
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none()
|
||||
if not row or not row.ntfy_server_url or not row.ntfy_topic:
|
||||
return False
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
await client.post(settings.ntfy_url, content=message, headers=headers)
|
||||
except Exception as exc:
|
||||
logger.warning("Ntfy notification failed: %s", exc)
|
||||
token = decrypt(row.ntfy_token) if row.ntfy_token else None
|
||||
except InvalidToken:
|
||||
logger.error("Could not decrypt stored admin ntfy token")
|
||||
return False
|
||||
|
||||
server_url = _normalize_server_url(row.ntfy_server_url)
|
||||
url = server_url.rstrip("/") + "/" + row.ntfy_topic.strip("/")
|
||||
headers = {"Title": _header_value(f"Bourbonacci Admin - {title}"), "Priority": priority}
|
||||
if tags:
|
||||
headers["Tags"] = _header_value(",".join(tags))
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.post(url, content=message.encode("utf-8"), headers=headers)
|
||||
if resp.status_code >= 300:
|
||||
logger.warning("Ntfy send to %s failed with status %s", server_url, resp.status_code)
|
||||
return False
|
||||
return True
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning("Ntfy send to %s failed: %s", server_url, exc)
|
||||
return False
|
||||
@@ -17,14 +17,18 @@ def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def create_token(user_id: int, admin_id: Optional[int] = None) -> str:
|
||||
def create_token(user_id: int) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
payload: dict = {"sub": str(user_id), "exp": expire}
|
||||
if admin_id is not None:
|
||||
payload["admin_id"] = admin_id
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def create_admin_token() -> str:
|
||||
# No "sub" claim, so decode_token() rejects it as a user token.
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
return jwt.encode({"admin": True, "exp": expire}, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[int]:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
@@ -36,8 +40,9 @@ def decode_token(token: str) -> Optional[int]:
|
||||
return None
|
||||
|
||||
|
||||
def decode_token_full(token: str) -> Optional[dict]:
|
||||
def is_admin_token(token: str) -> bool:
|
||||
try:
|
||||
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
except JWTError:
|
||||
return None
|
||||
return False
|
||||
return payload.get("admin") is True
|
||||
@@ -11,3 +11,5 @@ pytz==2026.6
|
||||
email-validator==2.4.0
|
||||
slowapi==0.1.10
|
||||
httpx==0.28.1
|
||||
cryptography==50.0.2
|
||||
apscheduler==3.11.3
|
||||
+12
-2
@@ -21,8 +21,10 @@ services:
|
||||
- ADMIN_USERNAME=${ADMIN_USERNAME}
|
||||
- ADMIN_PASSWORD=${ADMIN_PASSWORD}
|
||||
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-http://localhost}
|
||||
- NTFY_URL=${NTFY_URL:-}
|
||||
- NTFY_TOKEN=${NTFY_TOKEN:-}
|
||||
volumes:
|
||||
# Scheduled/manual backups (admin panel > Backups): the NFS-backed `backups`
|
||||
# volume below, so they live off-host. The share must be writable by uid 1000.
|
||||
- backups:/backups
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
@@ -56,3 +58,11 @@ services:
|
||||
|
||||
volumes:
|
||||
mysql_data:
|
||||
# Off-host backups on the project's NFS share. Override the server/export
|
||||
# with BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env.
|
||||
backups:
|
||||
driver: local
|
||||
driver_opts:
|
||||
type: nfs
|
||||
o: "addr=${BACKUP_NFS_HOST:-172.16.21.51},nfsvers=4.1,rw,hard,timeo=600,retrans=2"
|
||||
device: ":${BACKUP_NFS_PATH:-/mnt/pool1/bourbonacci-backups}"
|
||||
+22
-50
@@ -11,72 +11,44 @@
|
||||
|
||||
<nav>
|
||||
<div class="nav-left">
|
||||
<a href="/index.html" class="nav-brand">🥃 Bourbonacci</a>
|
||||
<div class="nav-links" id="nav-links"></div>
|
||||
<span class="nav-brand">🥃 Bourbonacci — Admin</span>
|
||||
</div>
|
||||
<div class="nav-user">
|
||||
<button onclick="Admin.signOut()" class="btn btn-sm btn-ghost">Sign out</button>
|
||||
</div>
|
||||
<div id="nav-user"></div>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
<h1 class="page-title">Admin — User Management</h1>
|
||||
|
||||
<div id="msg"></div>
|
||||
|
||||
<div class="section-header">
|
||||
<h2>All Users</h2>
|
||||
<button class="btn btn-ghost btn-sm" onclick="loadUsers()">Refresh</button>
|
||||
<div class="tabs">
|
||||
<div class="tab" data-tab="users" onclick="Admin.showTab('users')">Users</div>
|
||||
<div class="tab" data-tab="notifications" onclick="Admin.showTab('notifications')">Notifications</div>
|
||||
<div class="tab" data-tab="backups" onclick="Admin.showTab('backups')">Backups</div>
|
||||
<div class="tab" data-tab="reset" onclick="Admin.showTab('reset')">Reset</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Display Name</th>
|
||||
<th>Email</th>
|
||||
<th>Role</th>
|
||||
<th>Status</th>
|
||||
<th>Joined</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="users-body">
|
||||
<tr class="empty-row"><td colspan="6">Loading…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="tab-content"></div>
|
||||
|
||||
<!-- Reset password modal -->
|
||||
<div id="reset-modal" class="modal-overlay" style="display:none">
|
||||
<div class="modal-box">
|
||||
<h2>Reset Password</h2>
|
||||
<p style="margin-bottom:1rem;color:var(--cream-dim)">Setting new password for: <strong id="reset-username"></strong></p>
|
||||
<div id="reset-msg"></div>
|
||||
<div class="form-group" style="margin-bottom:1rem">
|
||||
<label>New Password</label>
|
||||
<input type="password" id="reset-password" placeholder="Min 8 characters" />
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;justify-content:flex-end">
|
||||
<button class="btn btn-ghost" onclick="hideResetModal()">Cancel</button>
|
||||
<button class="btn btn-primary" onclick="submitReset()">Set Password</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Delete confirmation modal -->
|
||||
<!-- Delete user confirmation modal -->
|
||||
<div id="delete-modal" class="modal-overlay" style="display:none">
|
||||
<div class="modal-box">
|
||||
<h2>Delete User</h2>
|
||||
<p style="margin-bottom:1.5rem;color:var(--cream-dim)">Delete <strong id="delete-username"></strong>? This will permanently remove their account and all associated data.</p>
|
||||
<p style="margin-bottom:1rem;color:var(--cream-dim)">
|
||||
This permanently deletes <strong id="delete-email"></strong>'s account and every entry they own.
|
||||
This cannot be undone. Type the email address to confirm.
|
||||
</p>
|
||||
<div id="delete-msg"></div>
|
||||
<div class="form-group">
|
||||
<input type="text" id="delete-confirm" autocomplete="off" oninput="Admin.onDeleteConfirmInput()" />
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;justify-content:flex-end">
|
||||
<button class="btn btn-ghost" onclick="hideDeleteModal()">Cancel</button>
|
||||
<button class="btn btn-danger" onclick="submitDelete()">Delete</button>
|
||||
<button class="btn btn-ghost" onclick="Admin.hideDeleteModal()">Cancel</button>
|
||||
<button class="btn btn-danger" id="delete-submit" disabled onclick="Admin.submitDelete()">Delete permanently</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script src="/js/api.js"></script>
|
||||
<script src="/js/auth.js"></script>
|
||||
<script src="/js/admin.js"></script>
|
||||
<script src="/js/admin.js?v=2"></script>
|
||||
</body>
|
||||
</html>
|
||||
+19
-16
@@ -81,20 +81,6 @@ nav {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nav-impersonating {
|
||||
color: var(--amber-light);
|
||||
font-size: 0.85rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-amber {
|
||||
background: var(--amber);
|
||||
color: #0d0800;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.btn-amber:hover { background: var(--amber-light); }
|
||||
|
||||
/* ---- Modal ---- */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
@@ -140,8 +126,6 @@ nav {
|
||||
}
|
||||
|
||||
/* ---- Admin badges ---- */
|
||||
.badge-admin { background: rgba(200,134,10,.2); color: var(--amber-light); border: 1px solid var(--amber-dim); }
|
||||
.badge-user { background: rgba(245,230,200,.1); color: var(--cream-dim); border: 1px solid var(--border); }
|
||||
.badge-active { background: rgba(39,174,96,.15); color: #5dd490; border: 1px solid #1e6b3d; }
|
||||
.badge-disabled { background: rgba(192,57,43,.2); color: #e07060; border: 1px solid var(--danger-dim); }
|
||||
|
||||
@@ -475,6 +459,25 @@ tbody td {
|
||||
.tab.active, .tab:hover { color: var(--amber-light); }
|
||||
.tab.active { border-bottom-color: var(--amber); }
|
||||
|
||||
/* ---- Admin panel ---- */
|
||||
.admin-card { margin-bottom: 1.5rem; }
|
||||
.card + .admin-card { margin-top: 0; }
|
||||
.admin-muted { color: var(--cream-dim); font-size: .85rem; margin-bottom: 1rem; }
|
||||
.admin-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0 1rem; }
|
||||
.admin-check { display: flex; align-items: center; gap: .5rem; color: var(--cream); margin-bottom: 1rem; cursor: pointer; }
|
||||
.admin-check input { width: auto; }
|
||||
.admin-confirm { display: flex; gap: .5rem; align-items: center; }
|
||||
.admin-confirm input { max-width: 220px; padding: .4rem .7rem; font-size: .85rem; }
|
||||
.admin-file { padding: 1rem; margin-bottom: .75rem; }
|
||||
.admin-file .admin-muted { margin-bottom: 0; }
|
||||
.admin-file-head { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
|
||||
.admin-restore { display: flex; gap: 1.5rem; flex-wrap: wrap; margin-top: .75rem; }
|
||||
.admin-restore label, .admin-card label code { font-size: .8rem; }
|
||||
.temp-pw { display: flex; gap: .75rem; align-items: center; background: rgba(200,134,10,.12); border: 1px solid var(--amber-dim); border-radius: var(--radius); padding: .5rem .75rem; font-size: .85rem; color: var(--amber-light); }
|
||||
.temp-pw code { font-size: .95rem; color: var(--cream); }
|
||||
.text-success { color: #5dd490; }
|
||||
.text-danger { color: #e07060; }
|
||||
|
||||
/* ---- Custom scrollbar ---- */
|
||||
::-webkit-scrollbar { width: 8px; }
|
||||
::-webkit-scrollbar-track { background: var(--bg-card); }
|
||||
|
||||
+549
-119
@@ -1,164 +1,594 @@
|
||||
// admin.js — admin user management page
|
||||
// admin.js — out-of-band admin panel (Users / Notifications / Backups / Reset).
|
||||
// Uses its own admin token (bb_admin_token), separate from the normal user token.
|
||||
|
||||
let resetTargetId = null;
|
||||
let deleteTargetId = null;
|
||||
let currentAdminId = null;
|
||||
const Admin = (() => {
|
||||
const TOKEN_KEY = 'bb_admin_token';
|
||||
const TABS = ['users', 'notifications', 'backups', 'reset'];
|
||||
const WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
if (!Auth.requireAuth()) return;
|
||||
await Auth.renderNav();
|
||||
// ── API ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const user = Auth.getUser();
|
||||
if (!user || !user.is_admin) {
|
||||
window.location.href = '/dashboard.html';
|
||||
return;
|
||||
function signOut() {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
window.location.href = '/login.html';
|
||||
}
|
||||
currentAdminId = user.id;
|
||||
await loadUsers();
|
||||
});
|
||||
|
||||
async function loadUsers() {
|
||||
async function request(method, path, body) {
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
const tok = localStorage.getItem(TOKEN_KEY);
|
||||
if (tok) headers['Authorization'] = `Bearer ${tok}`;
|
||||
|
||||
const res = await fetch('/api/admin' + path, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
signOut();
|
||||
throw new Error('Signed out');
|
||||
}
|
||||
if (res.status === 204) return null;
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
const msg = data?.detail || `HTTP ${res.status}`;
|
||||
throw new Error(Array.isArray(msg) ? msg.map(e => e.msg).join(', ') : msg);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
const api = {
|
||||
listUsers: () => request('GET', '/users'),
|
||||
resetPassword: (id) => request('POST', `/users/${id}/reset-password`),
|
||||
disableUser: (id) => request('POST', `/users/${id}/disable`),
|
||||
enableUser: (id) => request('POST', `/users/${id}/enable`),
|
||||
deleteUser: (id) => request('DELETE', `/users/${id}`),
|
||||
getNtfy: () => request('GET', '/ntfy-settings'),
|
||||
updateNtfy: (body) => request('PUT', '/ntfy-settings', body),
|
||||
testNtfy: () => request('POST', '/ntfy-settings/test'),
|
||||
getBackupCfg: () => request('GET', '/backups/settings'),
|
||||
updateBackupCfg:(body) => request('PUT', '/backups/settings', body),
|
||||
listBackups: () => request('GET', '/backups'),
|
||||
runBackup: () => request('POST', '/backups/run'),
|
||||
restoreBackup: (f, scope) => request('POST', `/backups/${encodeURIComponent(f)}/restore`, { scope }),
|
||||
deleteBackup: (f) => request('DELETE', `/backups/${encodeURIComponent(f)}`),
|
||||
resetEntries: () => request('POST', '/reset/entries'),
|
||||
};
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
function fmtDateTime(iso) {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return d.toLocaleString(undefined, {
|
||||
year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function fmtBytes(n) {
|
||||
if (n < 1024) return `${n} B`;
|
||||
const units = ['KB', 'MB', 'GB'];
|
||||
let v = n, i = -1;
|
||||
do { v /= 1024; i += 1; } while (v >= 1024 && i < units.length - 1);
|
||||
return `${v.toFixed(1)} ${units[i]}`;
|
||||
}
|
||||
|
||||
function alertHtml(text, type) {
|
||||
const cls = type === 'success' ? 'alert-success' : 'alert-error';
|
||||
return `<div class="alert ${cls}">${escHtml(text)}</div>`;
|
||||
}
|
||||
|
||||
function setMsg(id, text, type) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.innerHTML = text ? alertHtml(text, type) : '';
|
||||
}
|
||||
|
||||
// "Type X to arm, then click" confirm widget for destructive actions.
|
||||
function confirmWidget(id, word, label) {
|
||||
return `
|
||||
<div class="admin-confirm">
|
||||
<input type="text" id="${id}-input" placeholder="${escHtml(word)}" autocomplete="off"
|
||||
data-word="${escHtml(word)}" oninput="Admin.armConfirm('${id}')" />
|
||||
<button class="btn btn-sm btn-danger" id="${id}-btn" disabled>${escHtml(label)}</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function armConfirm(id) {
|
||||
const input = document.getElementById(`${id}-input`);
|
||||
const btn = document.getElementById(`${id}-btn`);
|
||||
btn.disabled = input.value.trim().toLowerCase() !== input.dataset.word;
|
||||
}
|
||||
|
||||
async function runConfirm(id, fn) {
|
||||
const input = document.getElementById(`${id}-input`);
|
||||
const btn = document.getElementById(`${id}-btn`);
|
||||
if (btn.disabled) return;
|
||||
const label = btn.textContent;
|
||||
btn.disabled = true;
|
||||
input.disabled = true;
|
||||
btn.textContent = 'Working…';
|
||||
try {
|
||||
const users = await API.admin.listUsers();
|
||||
renderUsers(users);
|
||||
} catch (err) {
|
||||
showMsg(err.message, 'error');
|
||||
await fn();
|
||||
input.value = '';
|
||||
} finally {
|
||||
input.disabled = false;
|
||||
btn.textContent = label;
|
||||
armConfirm(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderUsers(users) {
|
||||
// ── Tabs ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function showTab(name) {
|
||||
if (!TABS.includes(name)) name = 'users';
|
||||
history.replaceState(null, '', `#${name}`);
|
||||
document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
|
||||
const content = document.getElementById('tab-content');
|
||||
content.innerHTML = '<p class="admin-muted">Loading…</p>';
|
||||
({ users: renderUsersTab, notifications: renderNotificationsTab,
|
||||
backups: renderBackupsTab, reset: renderResetTab })[name]();
|
||||
}
|
||||
|
||||
// ── Users ──────────────────────────────────────────────────────────────────
|
||||
|
||||
let users = [];
|
||||
let tempPasswords = {};
|
||||
let deleteTarget = null;
|
||||
|
||||
async function renderUsersTab() {
|
||||
document.getElementById('tab-content').innerHTML = `
|
||||
<div id="users-msg"></div>
|
||||
<div class="section-header">
|
||||
<input type="text" id="user-search" placeholder="Search users…" oninput="Admin.renderUserRows()" style="max-width:320px" />
|
||||
<button class="btn btn-ghost btn-sm" onclick="Admin.loadUsers()">Refresh</button>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Display Name</th><th>Email</th><th>Entries</th><th>Status</th><th>Joined</th><th>Actions</th></tr>
|
||||
</thead>
|
||||
<tbody id="users-body"><tr class="empty-row"><td colspan="6">Loading…</td></tr></tbody>
|
||||
</table>
|
||||
</div>`;
|
||||
await loadUsers();
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
try {
|
||||
users = await api.listUsers();
|
||||
renderUserRows();
|
||||
} catch (err) {
|
||||
const body = document.getElementById('users-body');
|
||||
if (body) body.innerHTML = '<tr class="empty-row"><td colspan="6">Failed to load users.</td></tr>';
|
||||
setMsg('users-msg', err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function renderUserRows() {
|
||||
const tbody = document.getElementById('users-body');
|
||||
if (!tbody) return;
|
||||
const q = (document.getElementById('user-search')?.value || '').trim().toLowerCase();
|
||||
const filtered = users.filter(u =>
|
||||
!q || u.email.toLowerCase().includes(q) || (u.display_name || '').toLowerCase().includes(q));
|
||||
|
||||
if (!users.length) {
|
||||
tbody.innerHTML = '<tr class="empty-row"><td colspan="6">No users found.</td></tr>';
|
||||
if (!filtered.length) {
|
||||
tbody.innerHTML = `<tr class="empty-row"><td colspan="6">${users.length ? 'No matching users.' : 'No users found.'}</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = users.map(u => {
|
||||
const isSelf = u.id === currentAdminId;
|
||||
const name = escHtml(u.display_name || u.email);
|
||||
const roleLabel = u.is_admin
|
||||
? '<span class="badge badge-admin">Admin</span>'
|
||||
: '<span class="badge badge-user">User</span>';
|
||||
const statusLabel = u.is_disabled
|
||||
tbody.innerHTML = filtered.map(u => {
|
||||
const status = u.is_disabled
|
||||
? '<span class="badge badge-disabled">Disabled</span>'
|
||||
: '<span class="badge badge-active">Active</span>';
|
||||
const joined = new Date(u.created_at).toLocaleDateString();
|
||||
|
||||
const toggleBtn = u.is_disabled
|
||||
? `<button class="btn btn-sm btn-primary" onclick="toggleUser(${u.id}, false)">Enable</button>`
|
||||
: `<button class="btn btn-sm btn-ghost" onclick="toggleUser(${u.id}, true)"${isSelf ? ' disabled title="Cannot disable yourself"' : ''}>Disable</button>`;
|
||||
|
||||
const impersonateBtn = !isSelf
|
||||
? `<button class="btn btn-sm btn-ghost" onclick="impersonateUser(${u.id})">Login As</button>`
|
||||
const toggle = u.is_disabled
|
||||
? `<button class="btn btn-sm btn-primary" onclick="Admin.toggleUser(${u.id}, false)">Enable</button>`
|
||||
: `<button class="btn btn-sm btn-ghost" onclick="Admin.toggleUser(${u.id}, true)">Disable</button>`;
|
||||
const temp = tempPasswords[u.id]
|
||||
? `<tr><td colspan="6"><div class="temp-pw"><code>${escHtml(tempPasswords[u.id])}</code>
|
||||
<span>shown once — relay this to ${escHtml(u.email)}</span></div></td></tr>`
|
||||
: '';
|
||||
|
||||
const deleteBtn = !isSelf
|
||||
? `<button class="btn btn-sm btn-danger" onclick="showDeleteModal(${u.id}, '${name}')">Delete</button>`
|
||||
: '';
|
||||
|
||||
return `<tr>
|
||||
<td><strong>${name}</strong></td>
|
||||
return `<tr${u.is_disabled ? ' style="opacity:.6"' : ''}>
|
||||
<td><strong>${escHtml(u.display_name || u.email)}</strong></td>
|
||||
<td>${escHtml(u.email)}</td>
|
||||
<td>${roleLabel}</td>
|
||||
<td>${statusLabel}</td>
|
||||
<td>${joined}</td>
|
||||
<td>${u.entry_count}</td>
|
||||
<td>${status}</td>
|
||||
<td>${new Date(u.created_at).toLocaleDateString()}</td>
|
||||
<td style="display:flex;gap:0.35rem;flex-wrap:wrap">
|
||||
<button class="btn btn-sm btn-ghost" onclick="showResetModal(${u.id}, '${name}')">Reset PW</button>
|
||||
${toggleBtn}
|
||||
${impersonateBtn}
|
||||
${deleteBtn}
|
||||
<button class="btn btn-sm btn-ghost" onclick="Admin.resetPassword(${u.id})">Reset PW</button>
|
||||
${toggle}
|
||||
<button class="btn btn-sm btn-danger" onclick="Admin.showDeleteModal(${u.id})">Delete</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
</tr>${temp}`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
|
||||
function showResetModal(id, name) {
|
||||
resetTargetId = id;
|
||||
document.getElementById('reset-username').textContent = name;
|
||||
document.getElementById('reset-password').value = '';
|
||||
document.getElementById('reset-msg').innerHTML = '';
|
||||
document.getElementById('reset-modal').style.display = 'flex';
|
||||
document.getElementById('reset-password').focus();
|
||||
}
|
||||
async function resetPassword(id) {
|
||||
const u = users.find(x => x.id === id);
|
||||
if (!u || !confirm(`Reset password for ${u.email}? A new temporary password will be generated.`)) return;
|
||||
try {
|
||||
const { temp_password } = await api.resetPassword(id);
|
||||
tempPasswords[id] = temp_password;
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
setMsg('users-msg', err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function hideResetModal() {
|
||||
document.getElementById('reset-modal').style.display = 'none';
|
||||
resetTargetId = null;
|
||||
}
|
||||
async function toggleUser(id, disable) {
|
||||
try {
|
||||
await (disable ? api.disableUser(id) : api.enableUser(id));
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
setMsg('users-msg', err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function submitReset() {
|
||||
const password = document.getElementById('reset-password').value;
|
||||
const msgEl = document.getElementById('reset-msg');
|
||||
function showDeleteModal(id) {
|
||||
deleteTarget = users.find(x => x.id === id) || null;
|
||||
if (!deleteTarget) return;
|
||||
document.getElementById('delete-email').textContent = deleteTarget.email;
|
||||
document.getElementById('delete-confirm').value = '';
|
||||
document.getElementById('delete-confirm').placeholder = deleteTarget.email;
|
||||
document.getElementById('delete-submit').disabled = true;
|
||||
document.getElementById('delete-msg').innerHTML = '';
|
||||
document.getElementById('delete-modal').style.display = 'flex';
|
||||
document.getElementById('delete-confirm').focus();
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
msgEl.innerHTML = '<div class="alert alert-error">Password must be at least 8 characters.</div>';
|
||||
function hideDeleteModal() {
|
||||
document.getElementById('delete-modal').style.display = 'none';
|
||||
deleteTarget = null;
|
||||
}
|
||||
|
||||
function onDeleteConfirmInput() {
|
||||
const v = document.getElementById('delete-confirm').value;
|
||||
document.getElementById('delete-submit').disabled = !deleteTarget || v !== deleteTarget.email;
|
||||
}
|
||||
|
||||
async function submitDelete() {
|
||||
if (!deleteTarget || document.getElementById('delete-confirm').value !== deleteTarget.email) return;
|
||||
const btn = document.getElementById('delete-submit');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Deleting…';
|
||||
try {
|
||||
await api.deleteUser(deleteTarget.id);
|
||||
hideDeleteModal();
|
||||
setMsg('users-msg', 'User deleted.', 'success');
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
document.getElementById('delete-msg').innerHTML = alertHtml(err.message, 'error');
|
||||
btn.disabled = false;
|
||||
} finally {
|
||||
btn.textContent = 'Delete permanently';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Notifications ──────────────────────────────────────────────────────────
|
||||
|
||||
async function renderNotificationsTab() {
|
||||
let cfg;
|
||||
try {
|
||||
cfg = await api.getNtfy();
|
||||
} catch (err) {
|
||||
document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await API.admin.resetPassword(resetTargetId, { new_password: password });
|
||||
msgEl.innerHTML = '<div class="alert alert-success">Password reset successfully.</div>';
|
||||
setTimeout(hideResetModal, 1200);
|
||||
} catch (err) {
|
||||
msgEl.innerHTML = `<div class="alert alert-error">${escHtml(err.message)}</div>`;
|
||||
document.getElementById('tab-content').innerHTML = `
|
||||
<div class="card admin-card">
|
||||
<h3 class="card-title">Admin push notifications</h3>
|
||||
<p class="admin-muted">Sent via ntfy for new registrations, admin logins and lockouts, user changes, resets and restores. Token auth only.</p>
|
||||
<div class="form-group">
|
||||
<label for="ntfy-server">Server URL</label>
|
||||
<input type="text" id="ntfy-server" placeholder="https://ntfy.sh" value="${escHtml(cfg.ntfy_server_url || '')}" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="ntfy-topic">Topic</label>
|
||||
<input type="text" id="ntfy-topic" placeholder="my-secret-admin-topic" value="${escHtml(cfg.ntfy_topic || '')}" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="ntfy-token">Access token <span id="ntfy-token-hint">${cfg.has_token ? '(configured — leave blank to keep)' : ''}</span></label>
|
||||
<input type="password" id="ntfy-token" autocomplete="new-password" placeholder="${cfg.has_token ? '••••••••' : 'tk_…'}" />
|
||||
</div>
|
||||
<div id="ntfy-msg"></div>
|
||||
<div style="display:flex;gap:0.5rem">
|
||||
<button class="btn btn-primary" id="ntfy-save" onclick="Admin.saveNtfy()">Save</button>
|
||||
<button class="btn btn-ghost" id="ntfy-test" onclick="Admin.testNtfy()">Send test</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleUser(id, disable) {
|
||||
async function saveNtfy() {
|
||||
const btn = document.getElementById('ntfy-save');
|
||||
setMsg('ntfy-msg', '');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Saving…';
|
||||
try {
|
||||
if (disable) await API.admin.disable(id);
|
||||
else await API.admin.enable(id);
|
||||
await loadUsers();
|
||||
const body = {
|
||||
ntfy_server_url: document.getElementById('ntfy-server').value.trim(),
|
||||
ntfy_topic: document.getElementById('ntfy-topic').value.trim(),
|
||||
};
|
||||
const token = document.getElementById('ntfy-token').value;
|
||||
if (token) body.ntfy_token = token;
|
||||
const updated = await api.updateNtfy(body);
|
||||
const tokenInput = document.getElementById('ntfy-token');
|
||||
tokenInput.value = '';
|
||||
tokenInput.placeholder = updated.has_token ? '••••••••' : 'tk_…';
|
||||
document.getElementById('ntfy-token-hint').textContent = updated.has_token ? '(configured — leave blank to keep)' : '';
|
||||
setMsg('ntfy-msg', 'Saved.', 'success');
|
||||
} catch (err) {
|
||||
showMsg(err.message, 'error');
|
||||
setMsg('ntfy-msg', err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Save';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function impersonateUser(id) {
|
||||
async function testNtfy() {
|
||||
const btn = document.getElementById('ntfy-test');
|
||||
setMsg('ntfy-msg', '');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Sending…';
|
||||
try {
|
||||
const data = await API.admin.impersonate(id);
|
||||
Auth.saveToken(data.access_token);
|
||||
const user = await API.users.me();
|
||||
Auth.saveUser(user);
|
||||
window.location.href = '/dashboard.html';
|
||||
await api.testNtfy();
|
||||
setMsg('ntfy-msg', 'Test notification sent — check your device!', 'success');
|
||||
} catch (err) {
|
||||
showMsg(err.message, 'error');
|
||||
setMsg('ntfy-msg', err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Send test';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showDeleteModal(id, name) {
|
||||
deleteTargetId = id;
|
||||
document.getElementById('delete-username').textContent = name;
|
||||
document.getElementById('delete-modal').style.display = 'flex';
|
||||
}
|
||||
// ── Backups ────────────────────────────────────────────────────────────────
|
||||
|
||||
function hideDeleteModal() {
|
||||
document.getElementById('delete-modal').style.display = 'none';
|
||||
deleteTargetId = null;
|
||||
}
|
||||
let backupFiles = [];
|
||||
|
||||
async function submitDelete() {
|
||||
async function renderBackupsTab() {
|
||||
let cfg;
|
||||
try {
|
||||
await API.admin.delete(deleteTargetId);
|
||||
hideDeleteModal();
|
||||
showMsg('User deleted.', 'success');
|
||||
await loadUsers();
|
||||
cfg = await api.getBackupCfg();
|
||||
} catch (err) {
|
||||
hideDeleteModal();
|
||||
showMsg(err.message, 'error');
|
||||
document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const hourOpts = Array.from({ length: 24 }, (_, h) =>
|
||||
`<option value="${h}"${h === cfg.backup_hour ? ' selected' : ''}>${String(h).padStart(2, '0')}:00</option>`).join('');
|
||||
const dayOpts = WEEKDAYS.map((w, i) =>
|
||||
`<option value="${i}"${i === cfg.backup_weekday ? ' selected' : ''}>${w}</option>`).join('');
|
||||
|
||||
function showMsg(text, type) {
|
||||
const el = document.getElementById('msg');
|
||||
document.getElementById('tab-content').innerHTML = `
|
||||
<div class="card admin-card">
|
||||
<h3 class="card-title">Backup schedule</h3>
|
||||
<p class="admin-muted">Runs a full database dump into /backups, the NFS share set via BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env. All times are UTC.</p>
|
||||
<label class="admin-check">
|
||||
<input type="checkbox" id="bk-enabled"${cfg.backup_enabled ? ' checked' : ''} /> Enable scheduled backups
|
||||
</label>
|
||||
<div class="admin-grid">
|
||||
<div class="form-group">
|
||||
<label for="bk-frequency">Frequency</label>
|
||||
<select id="bk-frequency" onchange="Admin.onFrequencyChange()">
|
||||
<option value="daily"${cfg.backup_frequency === 'daily' ? ' selected' : ''}>Daily</option>
|
||||
<option value="weekly"${cfg.backup_frequency === 'weekly' ? ' selected' : ''}>Weekly</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="bk-hour">Hour (UTC)</label>
|
||||
<select id="bk-hour">${hourOpts}</select>
|
||||
</div>
|
||||
<div class="form-group" id="bk-weekday-group"${cfg.backup_frequency === 'weekly' ? '' : ' style="display:none"'}>
|
||||
<label for="bk-weekday">Day of week</label>
|
||||
<select id="bk-weekday">${dayOpts}</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="bk-retention">Keep last N backups</label>
|
||||
<input type="number" id="bk-retention" min="1" max="365" value="${cfg.backup_retention}" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="bk-location">Subfolder (optional)</label>
|
||||
<input type="text" id="bk-location" placeholder="e.g. nightly" value="${escHtml(cfg.backup_location || '')}" />
|
||||
</div>
|
||||
</div>
|
||||
<div id="bk-save-msg"></div>
|
||||
<button class="btn btn-primary btn-sm" id="bk-save" onclick="Admin.saveBackupCfg()">Save schedule</button>
|
||||
<p class="admin-muted" id="bk-last" style="margin-top:1rem"></p>
|
||||
</div>
|
||||
|
||||
<div class="card admin-card">
|
||||
<h3 class="card-title">Backup now</h3>
|
||||
<p class="admin-muted">Run an immediate backup outside the schedule.</p>
|
||||
<button class="btn btn-primary btn-sm" id="bk-run" onclick="Admin.runBackup()">Backup now</button>
|
||||
<div id="bk-run-msg" style="margin-top:.75rem"></div>
|
||||
</div>
|
||||
|
||||
<div class="section-header" style="margin-top:1.5rem"><h2>Backup files</h2></div>
|
||||
<div id="bk-files"><p class="admin-muted">Loading…</p></div>`;
|
||||
|
||||
renderLastBackup(cfg);
|
||||
await loadBackupFiles();
|
||||
}
|
||||
|
||||
function renderLastBackup(cfg) {
|
||||
const el = document.getElementById('bk-last');
|
||||
if (!el) return;
|
||||
const cls = type === 'success' ? 'alert-success' : 'alert-error';
|
||||
el.innerHTML = `<div class="alert ${cls}" style="margin-bottom:1rem">${escHtml(text)}</div>`;
|
||||
if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000);
|
||||
}
|
||||
if (!cfg.last_backup_at) { el.textContent = 'No backups have run yet.'; return; }
|
||||
el.innerHTML = `Last backup: ${escHtml(fmtDateTime(cfg.last_backup_at))} — ` + (cfg.last_backup_status === 'success'
|
||||
? '<span class="text-success">success</span>'
|
||||
: `<span class="text-danger">failed: ${escHtml(cfg.last_backup_error || '')}</span>`);
|
||||
}
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.id === 'reset-modal') hideResetModal();
|
||||
function onFrequencyChange() {
|
||||
const weekly = document.getElementById('bk-frequency').value === 'weekly';
|
||||
document.getElementById('bk-weekday-group').style.display = weekly ? '' : 'none';
|
||||
}
|
||||
|
||||
async function saveBackupCfg() {
|
||||
const btn = document.getElementById('bk-save');
|
||||
setMsg('bk-save-msg', '');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Saving…';
|
||||
try {
|
||||
const updated = await api.updateBackupCfg({
|
||||
backup_enabled: document.getElementById('bk-enabled').checked,
|
||||
backup_frequency: document.getElementById('bk-frequency').value,
|
||||
backup_hour: Number(document.getElementById('bk-hour').value),
|
||||
backup_weekday: Number(document.getElementById('bk-weekday').value),
|
||||
backup_retention: Number(document.getElementById('bk-retention').value),
|
||||
backup_location: document.getElementById('bk-location').value,
|
||||
});
|
||||
document.getElementById('bk-location').value = updated.backup_location || '';
|
||||
setMsg('bk-save-msg', 'Saved.', 'success');
|
||||
renderLastBackup(updated);
|
||||
await loadBackupFiles();
|
||||
} catch (err) {
|
||||
setMsg('bk-save-msg', err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Save schedule';
|
||||
}
|
||||
}
|
||||
|
||||
async function runBackup() {
|
||||
const btn = document.getElementById('bk-run');
|
||||
setMsg('bk-run-msg', '');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Backing up…';
|
||||
try {
|
||||
const r = await api.runBackup();
|
||||
setMsg('bk-run-msg', `Created ${r.filename} (${fmtBytes(r.size_bytes)}).`, 'success');
|
||||
renderLastBackup(await api.getBackupCfg());
|
||||
await loadBackupFiles();
|
||||
} catch (err) {
|
||||
setMsg('bk-run-msg', err.message, 'error');
|
||||
api.getBackupCfg().then(renderLastBackup).catch(() => {});
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Backup now';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBackupFiles() {
|
||||
const el = document.getElementById('bk-files');
|
||||
if (!el) return;
|
||||
try {
|
||||
backupFiles = await api.listBackups();
|
||||
} catch (err) {
|
||||
el.innerHTML = alertHtml('Failed to load backup files: ' + err.message, 'error');
|
||||
return;
|
||||
}
|
||||
if (!backupFiles.length) {
|
||||
el.innerHTML = '<p class="admin-muted"><em>No backups yet.</em></p>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = backupFiles.map((f, i) => `
|
||||
<div class="card admin-card admin-file">
|
||||
<div class="admin-file-head">
|
||||
<div>
|
||||
<code>${escHtml(f.filename)}</code>
|
||||
<div class="admin-muted">${fmtBytes(f.size_bytes)} · ${escHtml(fmtDateTime(f.created_at))}</div>
|
||||
</div>
|
||||
<button class="btn btn-sm btn-ghost" id="bk-del-${i}" onclick="Admin.deleteBackup(${i})">Delete</button>
|
||||
</div>
|
||||
<div class="admin-restore">
|
||||
<div>
|
||||
<label>Type <code>restore entries</code></label>
|
||||
${confirmWidget(`rs-e-${i}`, 'restore entries', 'Restore entries only')}
|
||||
</div>
|
||||
<div>
|
||||
<label>Type <code>restore all</code></label>
|
||||
${confirmWidget(`rs-a-${i}`, 'restore all', 'Restore all data')}
|
||||
</div>
|
||||
</div>
|
||||
<div id="bk-row-msg-${i}"></div>
|
||||
</div>`).join('');
|
||||
|
||||
backupFiles.forEach((f, i) => {
|
||||
document.getElementById(`rs-e-${i}-btn`).onclick = () => restore(i, 'entries');
|
||||
document.getElementById(`rs-a-${i}-btn`).onclick = () => restore(i, 'all');
|
||||
});
|
||||
}
|
||||
|
||||
async function restore(i, scope) {
|
||||
const f = backupFiles[i];
|
||||
const id = scope === 'all' ? `rs-a-${i}` : `rs-e-${i}`;
|
||||
setMsg(`bk-row-msg-${i}`, '');
|
||||
await runConfirm(id, async () => {
|
||||
try {
|
||||
await api.restoreBackup(f.filename, scope);
|
||||
setMsg(`bk-row-msg-${i}`, `Restored ${scope === 'all' ? 'all data' : 'entries'}.`, 'success');
|
||||
} catch (err) {
|
||||
setMsg(`bk-row-msg-${i}`, err.message, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteBackup(i) {
|
||||
const f = backupFiles[i];
|
||||
if (!confirm(`Delete backup file "${f.filename}"? This cannot be undone.`)) return;
|
||||
const btn = document.getElementById(`bk-del-${i}`);
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Deleting…';
|
||||
try {
|
||||
await api.deleteBackup(f.filename);
|
||||
await loadBackupFiles();
|
||||
} catch (err) {
|
||||
setMsg(`bk-row-msg-${i}`, 'Delete failed: ' + err.message, 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Delete';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Reset ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function renderResetTab() {
|
||||
document.getElementById('tab-content').innerHTML = `
|
||||
<div class="alert alert-error">
|
||||
<strong>Destructive actions</strong><br />
|
||||
These run across every user's data and cannot be undone. User accounts, passwords, profile
|
||||
settings and admin settings are always kept. Each one automatically runs a fresh backup first
|
||||
and refuses to proceed if that backup fails.
|
||||
</div>
|
||||
|
||||
<div class="card admin-card">
|
||||
<h3 class="card-title">Reset all entries</h3>
|
||||
<p class="admin-muted">Permanently delete every bottle entry (adds and removes) for every user — each bottle starts empty again.</p>
|
||||
<label>Type <code>reset entries</code> to confirm</label>
|
||||
${confirmWidget('reset-entries', 'reset entries', 'Reset all entries')}
|
||||
<div id="reset-entries-msg" style="margin-top:.75rem"></div>
|
||||
</div>`;
|
||||
|
||||
document.getElementById('reset-entries-btn').onclick = () => {
|
||||
setMsg('reset-entries-msg', '');
|
||||
runConfirm('reset-entries', async () => {
|
||||
try {
|
||||
const r = await api.resetEntries();
|
||||
setMsg('reset-entries-msg',
|
||||
`Deleted ${r.entries_deleted} entr${r.entries_deleted === 1 ? 'y' : 'ies'}. Safety backup: ${r.backup_filename}.`,
|
||||
'success');
|
||||
} catch (err) {
|
||||
setMsg('reset-entries-msg', err.message, 'error');
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// ── Init ───────────────────────────────────────────────────────────────────
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (!localStorage.getItem(TOKEN_KEY)) { window.location.href = '/login.html'; return; }
|
||||
showTab(location.hash.slice(1));
|
||||
});
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.id === 'delete-modal') hideDeleteModal();
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
signOut, showTab, armConfirm,
|
||||
loadUsers, renderUserRows, resetPassword, toggleUser,
|
||||
showDeleteModal, hideDeleteModal, onDeleteConfirmInput, submitDelete,
|
||||
saveNtfy, testNtfy,
|
||||
onFrequencyChange, saveBackupCfg, runBackup, deleteBackup,
|
||||
};
|
||||
})();
|
||||
@@ -66,15 +66,5 @@ const API = (() => {
|
||||
public: {
|
||||
stats: () => request('GET', '/public/stats'),
|
||||
},
|
||||
admin: {
|
||||
listUsers: () => request('GET', '/admin/users'),
|
||||
createUser: (body) => request('POST', '/admin/users', body),
|
||||
resetPassword: (id, body) => request('POST', `/admin/users/${id}/reset-password`, body),
|
||||
disable: (id) => request('POST', `/admin/users/${id}/disable`, {}),
|
||||
enable: (id) => request('POST', `/admin/users/${id}/enable`, {}),
|
||||
delete: (id) => request('DELETE', `/admin/users/${id}`),
|
||||
impersonate: (id) => request('POST', `/admin/users/${id}/impersonate`, {}),
|
||||
unimpersonate: () => request('POST', '/admin/unimpersonate', {}),
|
||||
},
|
||||
};
|
||||
})();
|
||||
@@ -55,28 +55,17 @@ const Auth = (() => {
|
||||
try { user = await API.users.me(); saveUser(user); } catch (_) {}
|
||||
}
|
||||
|
||||
const payload = _decodePayload();
|
||||
const isImpersonating = !!(payload && payload.admin_id);
|
||||
|
||||
navLinksEl.innerHTML = `
|
||||
<a href="/dashboard.html" class="btn btn-ghost btn-sm${activePage === 'dashboard' ? ' active' : ''}">My Bottle</a>
|
||||
<a href="/log.html" class="btn btn-ghost btn-sm${activePage === 'log' ? ' active' : ''}">Log Entry</a>
|
||||
`;
|
||||
|
||||
if (isImpersonating) {
|
||||
navUserEl.innerHTML = `
|
||||
<span class="nav-impersonating">Viewing as <strong>${escHtml(user?.display_name || user?.email || 'User')}</strong></span>
|
||||
<button onclick="Auth.returnToAdmin()" class="btn btn-sm btn-amber">↩ Return to Admin</button>
|
||||
`;
|
||||
} else {
|
||||
navUserEl.innerHTML = `
|
||||
<span class="nav-username">${escHtml(user?.display_name || user?.email || 'Account')}</span>
|
||||
${user?.is_admin ? '<a href="/admin.html" class="btn btn-sm btn-ghost">Admin</a>' : ''}
|
||||
<button onclick="Auth.showSettingsModal()" class="btn btn-sm btn-ghost" title="Settings">⚙</button>
|
||||
<button onclick="Auth.logout()" class="btn btn-sm btn-ghost">Logout</button>
|
||||
`;
|
||||
_injectSettingsModal(user);
|
||||
}
|
||||
} else {
|
||||
navLinksEl.innerHTML = '';
|
||||
navUserEl.innerHTML = `<a href="/login.html" class="btn btn-primary btn-sm">Login</a>`;
|
||||
@@ -229,22 +218,9 @@ const Auth = (() => {
|
||||
if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000);
|
||||
}
|
||||
|
||||
async function returnToAdmin() {
|
||||
try {
|
||||
const data = await API.post('/admin/unimpersonate', {});
|
||||
saveToken(data.access_token);
|
||||
const user = await API.users.me();
|
||||
saveUser(user);
|
||||
window.location.href = '/admin.html';
|
||||
} catch (_) {
|
||||
logout();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getToken, saveToken, getUser, saveUser,
|
||||
logout, isLoggedIn, requireAuth, redirectIfLoggedIn, renderNav,
|
||||
showSettingsModal, hideSettingsModal, detectTimezone, saveProfile, submitPasswordChange,
|
||||
returnToAdmin,
|
||||
};
|
||||
})();
|
||||
+37
-6
@@ -28,7 +28,7 @@
|
||||
<form id="login-form">
|
||||
<div class="form-group">
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" autocomplete="email" required placeholder="[email protected]" />
|
||||
<input type="text" id="email" autocomplete="username" required placeholder="[email protected]" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
@@ -60,19 +60,50 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Signing in…';
|
||||
|
||||
try {
|
||||
const email = document.getElementById('email').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
const data = await API.auth.login(email, password);
|
||||
Auth.saveToken(data.access_token);
|
||||
|
||||
try {
|
||||
// Raw fetch (not API.auth.login) so a 401 doesn't trigger the global sign-out redirect.
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
const data = await res.json().catch(() => null);
|
||||
|
||||
if (res.ok) {
|
||||
Auth.saveToken(data.access_token);
|
||||
// Pre-fetch user info so nav renders immediately
|
||||
const user = await API.users.me();
|
||||
Auth.saveUser(user);
|
||||
|
||||
window.location.href = '/index.html';
|
||||
return;
|
||||
}
|
||||
|
||||
// A rejected normal login might be the out-of-band admin account.
|
||||
if (res.status === 401 || res.status === 422) {
|
||||
const adminRes = await fetch('/api/admin/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: email, password }),
|
||||
});
|
||||
if (adminRes.ok) {
|
||||
const adminData = await adminRes.json();
|
||||
localStorage.setItem('bb_admin_token', adminData.access_token);
|
||||
window.location.href = '/admin.html?v=2';
|
||||
return;
|
||||
}
|
||||
if (adminRes.status === 429) {
|
||||
const adminErr = await adminRes.json().catch(() => null);
|
||||
throw new Error(adminErr?.detail || 'Too many attempts. Try again later.');
|
||||
}
|
||||
throw new Error('Invalid credentials');
|
||||
}
|
||||
|
||||
throw new Error(data?.detail || `HTTP ${res.status}`);
|
||||
} catch (err) {
|
||||
alert.innerHTML = `<div class="alert alert-error">${err.message}</div>`;
|
||||
alert.innerHTML = `<div class="alert alert-error">${escHtml(err.message)}</div>`;
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Sign In';
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ server {
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
# Revalidate on every load so updated pages/JS reach browsers immediately.
|
||||
add_header Cache-Control "no-cache" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self';" always;
|
||||
|
||||
if ($request_method = TRACE) {
|
||||
|
||||
Reference in new issue
Block a user