Commit 79bdfe8f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add Soundmarks: location-tied anthems with business/super admin roles

New feature, distinct from the existing GeoDrop (any user dropping a
song for others to find): a Soundmark is a curated anthem tied to a
place. One with no owner is a super-admin-curated landmark; one with
a business_owner_id is that business's location, and only its owner
(or a super admin) can change its anthem.

- User.role ("user" | "business_admin" | "super_admin") plus
  get_current_business_admin / get_current_super_admin dependencies.
  Super admin passes both checks - same privileges, elevated.
- New soundmarks router: nearby detection (haversine against each
  soundmark's own trigger radius, not a caller-supplied search
  radius), cross-user anthem streaming (deliberately not scoped to
  the caller owning the underlying song, unlike /library/stream),
  business-owner song assignment, super-admin CRUD, a "public
  library" search across every user's songs (no such cross-user
  endpoint existed before - everything else is locked to the
  caller), and user role management (promote/demote, with owning a
  soundmark auto-promoting a plain user to business_admin so
  ownership isn't otherwise inaccessible to them).
- GET /auth/me so the webapp can read the caller's role.

25 new tests covering role gating, ownership enforcement, cross-user
song picking/streaming, and radius-based nearby matching. Promoted
dev-test-user to super_admin for webapp testing.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent a97f9454
Pipeline #1051 passed with stage
in 4 minutes and 50 seconds
"""add user roles and soundmarks table
Revision ID: 28cc64af2c16
Revises: e9d581074a3f
Create Date: 2026-08-11 05:30:25.568806
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '28cc64af2c16'
down_revision: Union[str, Sequence[str], None] = 'e9d581074a3f'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('soundmarks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('latitude', sa.Float(), nullable=True),
sa.Column('longitude', sa.Float(), nullable=True),
sa.Column('radius_meters', sa.Float(), nullable=False),
sa.Column('business_owner_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['business_owner_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_soundmarks_business_owner_id'), 'soundmarks', ['business_owner_id'], unique=False)
op.create_index(op.f('ix_soundmarks_id'), 'soundmarks', ['id'], unique=False)
op.create_index(op.f('ix_soundmarks_name'), 'soundmarks', ['name'], unique=False)
# server_default backfills existing rows - without it, adding a NOT NULL column to a
# table that already has rows fails.
op.add_column('users', sa.Column('role', sa.String(), nullable=False, server_default='user'))
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'role')
op.drop_index(op.f('ix_soundmarks_name'), table_name='soundmarks')
op.drop_index(op.f('ix_soundmarks_id'), table_name='soundmarks')
op.drop_index(op.f('ix_soundmarks_business_owner_id'), table_name='soundmarks')
op.drop_table('soundmarks')
# ### end Alembic commands ###
......@@ -10,7 +10,7 @@ from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, channels, discovery, library, music, remix, social
from src.api.routers import auth, channels, discovery, library, music, remix, social, soundmarks
from src.core.config import CORS_ORIGINS, DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal
from src.services.storage import DOWNLOADS_DIR
......@@ -91,6 +91,7 @@ app.include_router(music.router)
app.include_router(social.router)
app.include_router(remix.router)
app.include_router(channels.router)
app.include_router(soundmarks.router)
@app.get("/", include_in_schema=False)
......
......@@ -141,6 +141,20 @@ async def auth_logout(req: RefreshReq, db: Session = Depends(get_db)):
return {"status": "success"}
@router.get("/me")
async def auth_me(current_user: User = Depends(get_current_user)):
"""Lets the client know who's logged in and what they're allowed to see - the webapp uses
`role` to decide whether to show the business/super admin panels."""
return {
"status": "success",
"user": {
"id": current_user.id,
"username": current_user.username,
"role": current_user.role,
},
}
@router.get("/chats")
async def get_chats(current_user: User = Depends(get_current_user)):
if not current_user.telegram_session_string:
......
This diff is collapsed.
......@@ -31,6 +31,10 @@ class User(Base):
# Pyrogram session string for this user's linked Telegram account. Set on /auth/login,
# used server-side only (by telegram_sync calls) - never serialized back to a client.
telegram_session_string = Column(String, nullable=True)
# "user" | "business_admin" | "super_admin" - kept as a plain string rather than a DB enum
# so adding a role later doesn't need a migration to alter the enum type (sqlite's enum
# support is weak anyway). Validated at the API boundary in soundmarks.py, not here.
role = Column(String, default="user", nullable=False)
class RefreshToken(Base):
__tablename__ = "refresh_tokens"
......@@ -122,6 +126,27 @@ class GeoDrop(Base):
longitude = Column(Float)
dropped_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Soundmark(Base):
"""A curated 'anthem' tied to a real-world place - distinct from GeoDrop (any user
dropping a song for others to stumble on). A Soundmark with business_owner_id NULL is a
super-admin-curated landmark (e.g. locally significant to the area); one with an owner is
that business's location, and its anthem can only be changed by that owner or a super
admin. song_id is nullable so a soundmark can exist (name/location set by a super admin)
before anyone has picked its anthem yet."""
__tablename__ = "soundmarks"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
latitude = Column(Float)
longitude = Column(Float)
# How close (in meters) someone needs to be for this soundmark to be considered "active" -
# this is what /soundmarks/nearby matches against, not a caller-supplied search radius.
radius_meters = Column(Float, default=200.0, nullable=False)
business_owner_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class LiveRoom(Base):
__tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True)
......
......@@ -63,3 +63,21 @@ def get_current_user(
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
return user
def is_super_admin(user: User) -> bool:
return user.role == "super_admin"
def get_current_business_admin(current_user: User = Depends(get_current_user)) -> User:
"""Business admins manage their own soundmarks; super admins pass this check too since
they can do everything a business admin can, plus more (see get_current_super_admin)."""
if current_user.role not in ("business_admin", "super_admin"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Business admin access required")
return current_user
def get_current_super_admin(current_user: User = Depends(get_current_user)) -> User:
if not is_super_admin(current_user):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin access required")
return current_user
......@@ -47,12 +47,13 @@ _user_ids = itertools.count(10_000)
def make_user(db_session):
"""Creates a real User row (as if they'd completed Telegram login) without going through
the actual Telegram auth flow - test_auth.py covers that flow itself with mocks."""
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string"):
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string", role: str = "user"):
uid = next(_user_ids)
user = User(
id=uid,
phone_number=phone_number or f"+1555{uid}",
telegram_session_string=telegram_session_string,
role=role,
)
db_session.add(user)
db_session.commit()
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment