From 9cac2cd335c44027dcd5579a21dbba0e1ca609b8 Mon Sep 17 00:00:00 2001 From: npeter83 Date: Tue, 16 Jun 2026 09:17:14 +0200 Subject: [PATCH] feat(demo): demo-account schema + reusable rate limiter Add the shared demo-account plumbing: users.is_demo marks the single shared demo user, demo_whitelist holds the admin-curated emails that may enter it without Google sign-in, and a small in-process RateLimiter (generic groundwork) for throttling the demo-login endpoint per IP. --- backend/alembic/versions/0014_demo_account.py | 59 +++++++++++++++++++ backend/app/models.py | 22 +++++++ backend/app/ratelimit.py | 43 ++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 backend/alembic/versions/0014_demo_account.py create mode 100644 backend/app/ratelimit.py diff --git a/backend/alembic/versions/0014_demo_account.py b/backend/alembic/versions/0014_demo_account.py new file mode 100644 index 0000000..3d9a8f3 --- /dev/null +++ b/backend/alembic/versions/0014_demo_account.py @@ -0,0 +1,59 @@ +"""demo account: users.is_demo + demo_whitelist + +Revision ID: 0014_demo_account +Revises: 0013_playlist_fingerprint +Create Date: 2026-06-16 + +Adds the shared demo-account plumbing: + - users.is_demo — marks the single shared demo user (no OAuth token / YouTube scope). + - demo_whitelist — admin-curated emails that may enter the demo account from the login + page without Google sign-in. Multiple emails are just keys to the same shared door. +The demo user row itself is created lazily on first demo login (works across all three DBs +without a data migration), so this only adds the schema. +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "0014_demo_account" +down_revision: Union[str, None] = "0013_playlist_fingerprint" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column( + "users", + sa.Column( + "is_demo", + sa.Boolean(), + nullable=False, + server_default=sa.false(), + ), + ) + op.create_index("ix_users_is_demo", "users", ["is_demo"]) + + op.create_table( + "demo_whitelist", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("email", sa.String(length=320), nullable=False), + sa.Column("note", sa.Text(), nullable=True), + sa.Column("added_by", sa.String(length=320), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.func.now(), + nullable=False, + ), + ) + op.create_index( + "ix_demo_whitelist_email", "demo_whitelist", ["email"], unique=True + ) + + +def downgrade() -> None: + op.drop_index("ix_demo_whitelist_email", table_name="demo_whitelist") + op.drop_table("demo_whitelist") + op.drop_index("ix_users_is_demo", table_name="users") + op.drop_column("users", "is_demo") diff --git a/backend/app/models.py b/backend/app/models.py index cf4d044..55f694c 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -28,6 +28,12 @@ class User(Base): display_name: Mapped[str | None] = mapped_column(String(255)) avatar_url: Mapped[str | None] = mapped_column(String(1024)) role: Mapped[str] = mapped_column(String(16), default="user", server_default="user") + # The single shared "demo" account: signed into without Google OAuth (via a whitelisted + # email on the login page), has no OAuth token / YouTube scope, and its per-user state is + # shared by everyone who enters this way. Exactly one such row is expected. + is_demo: Mapped[bool] = mapped_column( + Boolean, default=False, server_default="false", index=True + ) # Free-form UI preferences (theme, color scheme, font scale, default filters…). preferences: Mapped[dict | None] = mapped_column(JSON) created_at: Mapped[datetime] = mapped_column( @@ -81,6 +87,22 @@ class Invite(Base): decided_by: Mapped[str | None] = mapped_column(String(320)) # admin email +class DemoWhitelist(Base): + """Emails that may enter the shared demo account from the login page (no Google OAuth). + A hidden, admin-curated list of "keys to the same door" — every entry logs into the one + shared demo user. Distinct from Invite (which gates real Google sign-in).""" + + __tablename__ = "demo_whitelist" + + id: Mapped[int] = mapped_column(primary_key=True) + email: Mapped[str] = mapped_column(String(320), unique=True, index=True) + note: Mapped[str | None] = mapped_column(Text) + added_by: Mapped[str | None] = mapped_column(String(320)) # admin email + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + + class Channel(Base): """A YouTube channel. Shared across all users (one channel's videos are the same for everyone), so its expensive metadata is fetched and stored only once.""" diff --git a/backend/app/ratelimit.py b/backend/app/ratelimit.py new file mode 100644 index 0000000..7df0b5f --- /dev/null +++ b/backend/app/ratelimit.py @@ -0,0 +1,43 @@ +"""A tiny in-process sliding-window rate limiter. + +Generic groundwork: keyed by an arbitrary string (e.g. a client IP), so it can throttle any +endpoint. Single-worker uvicorn → in-memory state is sufficient; it resets on restart, which +is fine for abuse throttling (not for anything that must survive a deploy). Not shared across +processes — if we ever run multiple workers, swap the backing store for Redis behind the same +``allow()`` interface. +""" +import threading +import time + + +class RateLimiter: + def __init__(self, max_events: int, window_seconds: float): + self.max_events = max_events + self.window = window_seconds + self._hits: dict[str, list[float]] = {} + self._lock = threading.Lock() + + def allow(self, key: str) -> bool: + """Record an attempt for ``key`` and return whether it is within the limit. + + True -> under the cap (the attempt is counted). + False -> the cap for the current window is already reached (attempt NOT counted, so a + blocked caller can't keep pushing the window forward).""" + now = time.monotonic() + cutoff = now - self.window + with self._lock: + hits = [t for t in self._hits.get(key, []) if t > cutoff] + if len(hits) >= self.max_events: + self._hits[key] = hits + return False + hits.append(now) + self._hits[key] = hits + # Opportunistic cleanup so abandoned keys don't accumulate unboundedly. + if len(self._hits) > 4096: + for k in list(self._hits): + fresh = [t for t in self._hits[k] if t > cutoff] + if fresh: + self._hits[k] = fresh + else: + del self._hits[k] + return True