Commit d9a22bf3 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Stop sending user_id/owner_id to channels endpoints (backend fix)

Matches the backend fix removing the user_id/owner_id impersonation
hole - createChannel/followChannel/unfollowChannel no longer take an
id param since the backend derives it from the auth token now. UI
display (hiding the follow button on your own channel) still uses
getCurrentUserId() locally, just no longer sends it to the server.

Also adds the first test coverage for the Channels page - there was
none before this.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 68164f7a
Pipeline #1072 canceled with stage
import { apiFetch } from './client'
// Unlike every other router, /channels takes user_id explicitly in request bodies instead of
// deriving it from the auth token server-side - see getCurrentUserId() in jwt.ts, used by the
// pages calling these to fill it in automatically.
export interface Channel {
id: number
owner_id: number
......@@ -17,10 +13,10 @@ export function listChannels() {
return apiFetch<Channel[]>('/channels')
}
export function createChannel(ownerId: number, name: string, description?: string) {
export function createChannel(name: string, description?: string) {
return apiFetch<Channel>('/channels', {
method: 'POST',
json: { owner_id: ownerId, name, description: description ?? null },
json: { name, description: description ?? null },
})
}
......@@ -28,12 +24,12 @@ export function getChannel(channelId: number) {
return apiFetch<{ channel: Channel; follower_count: number }>(`/channels/${channelId}`)
}
export function followChannel(channelId: number, userId: number) {
return apiFetch(`/channels/${channelId}/follow`, { method: 'POST', json: { user_id: userId } })
export function followChannel(channelId: number) {
return apiFetch(`/channels/${channelId}/follow`, { method: 'POST' })
}
export function unfollowChannel(channelId: number, userId: number) {
return apiFetch(`/channels/${channelId}/unfollow`, { method: 'POST', json: { user_id: userId } })
export function unfollowChannel(channelId: number) {
return apiFetch(`/channels/${channelId}/unfollow`, { method: 'POST' })
}
export interface VibeSet {
......@@ -48,10 +44,10 @@ export function listVibeSets(channelId: number) {
return apiFetch<VibeSet[]>(`/channels/${channelId}/vibe-sets`)
}
export function createVibeSet(channelId: number, userId: number, title: string, songIds: number[]) {
export function createVibeSet(channelId: number, title: string, songIds: number[]) {
return apiFetch<VibeSet>(`/channels/${channelId}/vibe-sets`, {
method: 'POST',
json: { user_id: userId, title, song_ids: songIds },
json: { title, song_ids: songIds },
})
}
......@@ -68,9 +64,9 @@ export function listStories(channelId: number) {
return apiFetch<AudioStory[]>(`/channels/${channelId}/stories`)
}
export function createStory(channelId: number, userId: number, songId: number, caption?: string) {
export function createStory(channelId: number, songId: number, caption?: string) {
return apiFetch<AudioStory>(`/channels/${channelId}/stories`, {
method: 'POST',
json: { user_id: userId, song_id: songId, caption: caption ?? null },
json: { song_id: songId, caption: caption ?? null },
})
}
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Channels } from './Channels'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { setTokens } from '../api/client'
import * as channelsApi from '../api/channels'
/** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies,
* that's the server's job), matching api/jwt.test.ts's own helper. */
function fakeJwt(payload: object): string {
const base64url = (obj: object) =>
btoa(JSON.stringify(obj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
return `${base64url({ alg: 'HS256', typ: 'JWT' })}.${base64url(payload)}.fake-signature`
}
const MY_CHANNEL: channelsApi.Channel = {
id: 1,
owner_id: 1,
name: 'My Channel',
description: null,
avatar_url: null,
created_at: '2026-01-01T00:00:00Z',
}
const OTHER_CHANNEL: channelsApi.Channel = {
id: 2,
owner_id: 5,
name: "Someone Else's Channel",
description: null,
avatar_url: null,
created_at: '2026-01-01T00:00:00Z',
}
function renderChannels() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Channels />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Channels', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows an empty state when there are no channels', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([])
renderChannels()
expect(await screen.findByText(/No channels yet/)).toBeInTheDocument()
})
it('lists channels with their follower count and owner', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([OTHER_CHANNEL])
vi.spyOn(channelsApi, 'getChannel').mockResolvedValue({ channel: OTHER_CHANNEL, follower_count: 3 })
renderChannels()
expect(await screen.findByText("Someone Else's Channel")).toBeInTheDocument()
expect(screen.getByText(/3 followers · owner #5/)).toBeInTheDocument()
})
it('creates a channel via the form without needing to pass an owner id', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([])
const create = vi.spyOn(channelsApi, 'createChannel').mockResolvedValue(MY_CHANNEL)
renderChannels()
await screen.findByText(/No channels yet/)
await userEvent.type(screen.getByPlaceholderText('New channel name'), 'My Channel')
await userEvent.click(screen.getByRole('button', { name: 'Create' }))
await waitFor(() => expect(create).toHaveBeenCalledWith('My Channel'))
})
it('does not show a follow button on your own channel', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([MY_CHANNEL])
vi.spyOn(channelsApi, 'getChannel').mockResolvedValue({ channel: MY_CHANNEL, follower_count: 0 })
renderChannels()
await screen.findByText('My Channel')
expect(screen.queryByRole('button', { name: /Follow/ })).not.toBeInTheDocument()
})
it('follows and unfollows someone else\'s channel without passing a user id', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([OTHER_CHANNEL])
vi.spyOn(channelsApi, 'getChannel').mockResolvedValue({ channel: OTHER_CHANNEL, follower_count: 3 })
const follow = vi.spyOn(channelsApi, 'followChannel').mockResolvedValue({})
const unfollow = vi.spyOn(channelsApi, 'unfollowChannel').mockResolvedValue({ status: 'ok' })
renderChannels()
await screen.findByText("Someone Else's Channel")
await userEvent.click(screen.getByRole('button', { name: 'Follow' }))
expect(follow).toHaveBeenCalledWith(OTHER_CHANNEL.id)
expect(await screen.findByText(/4 followers/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Unfollow' })).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Unfollow' }))
expect(unfollow).toHaveBeenCalledWith(OTHER_CHANNEL.id)
expect(await screen.findByText(/3 followers/)).toBeInTheDocument()
})
})
......@@ -36,20 +36,19 @@ export function Channels() {
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newName.trim() || userId === null) return
await createChannel(userId, newName.trim())
if (!newName.trim()) return
await createChannel(newName.trim())
setNewName('')
refresh()
}
async function toggleFollow(channelId: number) {
if (userId === null) return
if (followedIds.has(channelId)) {
await unfollowChannel(channelId, userId)
await unfollowChannel(channelId)
setFollowedIds((s) => new Set([...s].filter((id) => id !== channelId)))
setFollowerCounts((c) => ({ ...c, [channelId]: Math.max(0, c[channelId] - 1) }))
} else {
await followChannel(channelId, userId)
await followChannel(channelId)
setFollowedIds((s) => new Set(s).add(channelId))
setFollowerCounts((c) => ({ ...c, [channelId]: (c[channelId] ?? 0) + 1 }))
}
......
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