diff --git a/..env.swp b/..env.swp new file mode 100644 index 0000000..eac252e Binary files /dev/null and b/..env.swp differ diff --git a/.env.example b/.env.example index a10ed9f..aa80a4d 100644 --- a/.env.example +++ b/.env.example @@ -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=admin@example.com -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 diff --git a/backend/Dockerfile b/backend/Dockerfile index dbe50a6..02ae584 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -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"] diff --git a/backend/app/config.py b/backend/app/config.py index 113dbf2..b0698ba 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -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" diff --git a/backend/app/database.py b/backend/app/database.py index ab666ac..cfabb31 100644 --- a/backend/app/database.py +++ b/backend/app/database.py @@ -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) diff --git a/backend/app/dependencies.py b/backend/app/dependencies.py index 0492ae8..b57319c 100644 --- a/backend/app/dependencies.py +++ b/backend/app/dependencies.py @@ -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") diff --git a/backend/app/main.py b/backend/app/main.py index 9d484dd..e6f63d4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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") diff --git a/backend/app/models/admin_settings.py b/backend/app/models/admin_settings.py new file mode 100644 index 0000000..0eab8ac --- /dev/null +++ b/backend/app/models/admin_settings.py @@ -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 diff --git a/backend/app/routers/admin.py b/backend/app/routers/admin.py index 905d833..0b5fea0 100644 --- a/backend/app/routers/admin.py +++ b/backend/app/routers/admin.py @@ -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, - ) - db.add(user) + +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.", + ) + + 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 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 db.refresh(user) + 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) diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 705aa9e..f1d2903 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -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)) diff --git a/backend/app/routers/backups.py b/backend/app/routers/backups.py new file mode 100644 index 0000000..b9a8e2d --- /dev/null +++ b/backend/app/routers/backups.py @@ -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") diff --git a/backend/app/scheduler.py b/backend/app/scheduler.py new file mode 100644 index 0000000..8139352 --- /dev/null +++ b/backend/app/scheduler.py @@ -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) diff --git a/backend/app/schemas/admin.py b/backend/app/schemas/admin.py new file mode 100644 index 0000000..827bf33 --- /dev/null +++ b/backend/app/schemas/admin.py @@ -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 diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.py index 863b316..d713d96 100644 --- a/backend/app/schemas/user.py +++ b/backend/app/schemas/user.py @@ -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} diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/services/backup.py b/backend/app/services/backup.py new file mode 100644 index 0000000..4994c03 --- /dev/null +++ b/backend/app/services/backup.py @@ -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) diff --git a/backend/app/utils/crypto.py b/backend/app/utils/crypto.py new file mode 100644 index 0000000..694d630 --- /dev/null +++ b/backend/app/utils/crypto.py @@ -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() diff --git a/backend/app/utils/notify.py b/backend/app/utils/notify.py index 62c4e22..da08251 100644 --- a/backend/app/utils/notify.py +++ b/backend/app/utils/notify.py @@ -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 diff --git a/backend/app/utils/security.py b/backend/app/utils/security.py index d7e3447..9a2e456 100644 --- a/backend/app/utils/security.py +++ b/backend/app/utils/security.py @@ -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 diff --git a/backend/requirements.txt b/backend/requirements.txt index 9138a91..5db05c7 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index 221e17f..203fb65 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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}" diff --git a/frontend/admin.html b/frontend/admin.html index 90f27f6..93d5d44 100644 --- a/frontend/admin.html +++ b/frontend/admin.html @@ -11,72 +11,44 @@
-

Admin — User Management

- -
- -
-

All Users

- +
+
Users
+
Notifications
+
Backups
+
Reset
-
- - - - - - - - - - - - - - -
Display NameEmailRoleStatusJoinedActions
Loading…
-
+
- - - - +
- - + diff --git a/frontend/css/style.css b/frontend/css/style.css index 21e8a0f..0c32d18 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -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); } diff --git a/frontend/js/admin.js b/frontend/js/admin.js index 64561b8..fa6af82 100644 --- a/frontend/js/admin.js +++ b/frontend/js/admin.js @@ -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; - } - currentAdminId = user.id; - await loadUsers(); -}); - -async function loadUsers() { - try { - const users = await API.admin.listUsers(); - renderUsers(users); - } catch (err) { - showMsg(err.message, 'error'); - } -} - -function renderUsers(users) { - const tbody = document.getElementById('users-body'); - - if (!users.length) { - tbody.innerHTML = 'No users found.'; - return; + function signOut() { + localStorage.removeItem(TOKEN_KEY); + window.location.href = '/login.html'; } - tbody.innerHTML = users.map(u => { - const isSelf = u.id === currentAdminId; - const name = escHtml(u.display_name || u.email); - const roleLabel = u.is_admin - ? 'Admin' - : 'User'; - const statusLabel = u.is_disabled - ? 'Disabled' - : 'Active'; - const joined = new Date(u.created_at).toLocaleDateString(); + 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 toggleBtn = u.is_disabled - ? `` - : ``; + const res = await fetch('/api/admin' + path, { + method, + headers, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); - const impersonateBtn = !isSelf - ? `` - : ''; + if (res.status === 401 || res.status === 403) { + signOut(); + throw new Error('Signed out'); + } + if (res.status === 204) return null; - const deleteBtn = !isSelf - ? `` - : ''; - - return ` - ${name} - ${escHtml(u.email)} - ${roleLabel} - ${statusLabel} - ${joined} - - - ${toggleBtn} - ${impersonateBtn} - ${deleteBtn} - - `; - }).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(); -} - -function hideResetModal() { - document.getElementById('reset-modal').style.display = 'none'; - resetTargetId = null; -} - -async function submitReset() { - const password = document.getElementById('reset-password').value; - const msgEl = document.getElementById('reset-msg'); - - if (password.length < 8) { - msgEl.innerHTML = '
Password must be at least 8 characters.
'; - return; + 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; } - try { - await API.admin.resetPassword(resetTargetId, { new_password: password }); - msgEl.innerHTML = '
Password reset successfully.
'; - setTimeout(hideResetModal, 1200); - } catch (err) { - msgEl.innerHTML = `
${escHtml(err.message)}
`; - } -} + 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'), + }; -async function toggleUser(id, disable) { - try { - if (disable) await API.admin.disable(id); - else await API.admin.enable(id); + // ── 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 `
${escHtml(text)}
`; + } + + 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 ` +
+ + +
`; + } + + 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 { + await fn(); + input.value = ''; + } finally { + input.disabled = false; + btn.textContent = label; + armConfirm(id); + } + } + + // ── 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 = '

Loading…

'; + ({ 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 = ` +
+
+ + +
+
+ + + + + +
Display NameEmailEntriesStatusJoinedActions
Loading…
+
`; await loadUsers(); - } catch (err) { - showMsg(err.message, 'error'); } -} -async function impersonateUser(id) { - 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'; - } catch (err) { - showMsg(err.message, 'error'); + async function loadUsers() { + try { + users = await api.listUsers(); + renderUserRows(); + } catch (err) { + const body = document.getElementById('users-body'); + if (body) body.innerHTML = 'Failed to load users.'; + setMsg('users-msg', err.message, 'error'); + } } -} -function showDeleteModal(id, name) { - deleteTargetId = id; - document.getElementById('delete-username').textContent = name; - document.getElementById('delete-modal').style.display = 'flex'; -} + 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)); -function hideDeleteModal() { - document.getElementById('delete-modal').style.display = 'none'; - deleteTargetId = null; -} + if (!filtered.length) { + tbody.innerHTML = `${users.length ? 'No matching users.' : 'No users found.'}`; + return; + } -async function submitDelete() { - try { - await API.admin.delete(deleteTargetId); - hideDeleteModal(); - showMsg('User deleted.', 'success'); - await loadUsers(); - } catch (err) { - hideDeleteModal(); - showMsg(err.message, 'error'); + tbody.innerHTML = filtered.map(u => { + const status = u.is_disabled + ? 'Disabled' + : 'Active'; + const toggle = u.is_disabled + ? `` + : ``; + const temp = tempPasswords[u.id] + ? `
${escHtml(tempPasswords[u.id])} + shown once — relay this to ${escHtml(u.email)}
` + : ''; + return ` + ${escHtml(u.display_name || u.email)} + ${escHtml(u.email)} + ${u.entry_count} + ${status} + ${new Date(u.created_at).toLocaleDateString()} + + + ${toggle} + + + ${temp}`; + }).join(''); } -} -function showMsg(text, type) { - const el = document.getElementById('msg'); - if (!el) return; - const cls = type === 'success' ? 'alert-success' : 'alert-error'; - el.innerHTML = `
${escHtml(text)}
`; - if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000); -} + 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'); + } + } -document.addEventListener('click', (e) => { - if (e.target.id === 'reset-modal') hideResetModal(); - if (e.target.id === 'delete-modal') hideDeleteModal(); -}); + async function toggleUser(id, disable) { + try { + await (disable ? api.disableUser(id) : api.enableUser(id)); + await loadUsers(); + } catch (err) { + setMsg('users-msg', err.message, 'error'); + } + } + + 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(); + } + + 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; + } + document.getElementById('tab-content').innerHTML = ` +
+

Admin push notifications

+

Sent via ntfy for new registrations, admin logins and lockouts, user changes, resets and restores. Token auth only.

+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
`; + } + + async function saveNtfy() { + const btn = document.getElementById('ntfy-save'); + setMsg('ntfy-msg', ''); + btn.disabled = true; + btn.textContent = 'Saving…'; + try { + 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) { + setMsg('ntfy-msg', err.message, 'error'); + } finally { + btn.disabled = false; + btn.textContent = 'Save'; + } + } + + async function testNtfy() { + const btn = document.getElementById('ntfy-test'); + setMsg('ntfy-msg', ''); + btn.disabled = true; + btn.textContent = 'Sending…'; + try { + await api.testNtfy(); + setMsg('ntfy-msg', 'Test notification sent — check your device!', 'success'); + } catch (err) { + setMsg('ntfy-msg', err.message, 'error'); + } finally { + btn.disabled = false; + btn.textContent = 'Send test'; + } + } + + // ── Backups ──────────────────────────────────────────────────────────────── + + let backupFiles = []; + + async function renderBackupsTab() { + let cfg; + try { + cfg = await api.getBackupCfg(); + } catch (err) { + document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error'); + return; + } + const hourOpts = Array.from({ length: 24 }, (_, h) => + ``).join(''); + const dayOpts = WEEKDAYS.map((w, i) => + ``).join(''); + + document.getElementById('tab-content').innerHTML = ` +
+

Backup schedule

+

Runs a full database dump into /backups, the NFS share set via BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env. All times are UTC.

+ +
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+
+ +

+
+ +
+

Backup now

+

Run an immediate backup outside the schedule.

+ +
+
+ +

Backup files

+

Loading…

`; + + renderLastBackup(cfg); + await loadBackupFiles(); + } + + function renderLastBackup(cfg) { + const el = document.getElementById('bk-last'); + if (!el) return; + 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' + ? 'success' + : `failed: ${escHtml(cfg.last_backup_error || '')}`); + } + + 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 = '

No backups yet.

'; + return; + } + el.innerHTML = backupFiles.map((f, i) => ` +
+
+
+ ${escHtml(f.filename)} +
${fmtBytes(f.size_bytes)} · ${escHtml(fmtDateTime(f.created_at))}
+
+ +
+
+
+ + ${confirmWidget(`rs-e-${i}`, 'restore entries', 'Restore entries only')} +
+
+ + ${confirmWidget(`rs-a-${i}`, 'restore all', 'Restore all data')} +
+
+
+
`).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 = ` +
+ Destructive actions
+ 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. +
+ +
+

Reset all entries

+

Permanently delete every bottle entry (adds and removes) for every user — each bottle starts empty again.

+ + ${confirmWidget('reset-entries', 'reset entries', 'Reset all entries')} +
+
`; + + 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, + }; +})(); diff --git a/frontend/js/api.js b/frontend/js/api.js index d620222..f93beea 100644 --- a/frontend/js/api.js +++ b/frontend/js/api.js @@ -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', {}), - }, }; })(); diff --git a/frontend/js/auth.js b/frontend/js/auth.js index 6d1fdb7..b8b9a28 100644 --- a/frontend/js/auth.js +++ b/frontend/js/auth.js @@ -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 = ` My Bottle Log Entry `; - if (isImpersonating) { - navUserEl.innerHTML = ` - Viewing as ${escHtml(user?.display_name || user?.email || 'User')} - - `; - } else { - navUserEl.innerHTML = ` - ${escHtml(user?.display_name || user?.email || 'Account')} - ${user?.is_admin ? 'Admin' : ''} - - - `; - _injectSettingsModal(user); - } + navUserEl.innerHTML = ` + ${escHtml(user?.display_name || user?.email || 'Account')} + + + `; + _injectSettingsModal(user); } else { navLinksEl.innerHTML = ''; navUserEl.innerHTML = `Login`; @@ -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, }; })(); diff --git a/frontend/login.html b/frontend/login.html index cf88a2c..3f6c530 100644 --- a/frontend/login.html +++ b/frontend/login.html @@ -28,7 +28,7 @@
- +
@@ -60,19 +60,50 @@ document.addEventListener('DOMContentLoaded', () => { btn.disabled = true; btn.textContent = 'Signing in…'; + const email = document.getElementById('email').value.trim(); + const password = document.getElementById('password').value; + 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); + // 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); - // Pre-fetch user info so nav renders immediately - const user = await API.users.me(); - Auth.saveUser(user); + 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; + } - window.location.href = '/index.html'; + // 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 = `
${err.message}
`; + alert.innerHTML = `
${escHtml(err.message)}
`; btn.disabled = false; btn.textContent = 'Sign In'; } diff --git a/nginx/default.conf b/nginx/default.conf index 3a7e986..e260ae2 100644 --- a/nginx/default.conf +++ b/nginx/default.conf @@ -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) {