Commit da534d8e authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Switch login to username/password; Telegram becomes account-linking, not auth

Login.tsx is now a plain username/password form (with a register toggle)
instead of the two-step Telegram phone/code flow - completeLogin() and the
redirect-to-original-destination logic are unchanged, only how tokens get
obtained. api/auth.ts's requestCode/login are renamed to
requestTelegramCode/linkTelegram and point at the backend's new
/auth/telegram/* paths, reflecting that Telegram is for linking an account
(for chat-scanning music-tagging) rather than signing in. Roadmap updated to
match.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 50bce471
Pipeline #1081 failed with stage
import { apiFetch } from './client' import { apiFetch } from './client'
export interface RequestCodeResult {
phone_code_hash: string
is_registered: boolean
}
/** Kicks off Telegram phone login - triggers a real login code sent to that number via
* Telegram. The returned phone_code_hash has to be sent back along with the code in
* login() below; Telegram ties the two together server-side. */
export function requestCode(phoneNumber: string) {
return apiFetch<{ status: string; data: RequestCodeResult }>('/auth/request_code', {
method: 'POST',
json: { phone_number: phoneNumber },
auth: false,
})
}
export interface TokenPair { export interface TokenPair {
access_token: string access_token: string
refresh_token: string refresh_token: string
token_type: string token_type: string
} }
export function login(phoneNumber: string, phoneCodeHash: string, code: string) { /** Primary login: plain username + password. */
export function login(username: string, password: string) {
return apiFetch<TokenPair>('/auth/login', { return apiFetch<TokenPair>('/auth/login', {
method: 'POST', method: 'POST',
json: { phone_number: phoneNumber, phone_code_hash: phoneCodeHash, code }, json: { username, password },
auth: false,
})
}
export function register(username: string, password: string) {
return apiFetch<TokenPair>('/auth/register', {
method: 'POST',
json: { username, password },
auth: false, auth: false,
}) })
} }
...@@ -37,6 +30,31 @@ export function logout(refreshToken: string) { ...@@ -37,6 +30,31 @@ export function logout(refreshToken: string) {
}) })
} }
export interface RequestCodeResult {
phone_code_hash: string
is_registered: boolean
}
/** Links a Telegram account to the (already logged-in, username/password) current user -
* used for the chat-scanning music-tagging feature, not for signing in. Triggers a real
* login code sent to that number via Telegram; the returned phone_code_hash has to be sent
* back along with the code in linkTelegram() below, which Telegram ties together server-side. */
export function requestTelegramCode(phoneNumber: string) {
return apiFetch<{ status: string; data: RequestCodeResult }>('/auth/telegram/request_code', {
method: 'POST',
json: { phone_number: phoneNumber },
auth: false,
})
}
export function linkTelegram(phoneNumber: string, phoneCodeHash: string, code: string) {
return apiFetch<TokenPair>('/auth/telegram/login', {
method: 'POST',
json: { phone_number: phoneNumber, phone_code_hash: phoneCodeHash, code },
auth: false,
})
}
export interface Chat { export interface Chat {
id: number id: number
title: string title: string
...@@ -44,7 +62,7 @@ export interface Chat { ...@@ -44,7 +62,7 @@ export interface Chat {
} }
export function getChats() { export function getChats() {
return apiFetch<{ status: string; chats: Chat[] }>('/auth/chats') return apiFetch<{ status: string; chats: Chat[] }>('/auth/telegram/chats')
} }
export type UserRole = 'user' | 'business_admin' | 'super_admin' export type UserRole = 'user' | 'business_admin' | 'super_admin'
......
...@@ -32,118 +32,98 @@ describe('Login', () => { ...@@ -32,118 +32,98 @@ describe('Login', () => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('starts on the phone number step', () => { it('starts in sign-in mode', () => {
renderLogin() renderLogin()
expect(screen.getByLabelText('Phone number')).toBeInTheDocument() expect(screen.getByLabelText('Username')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Send code' })).toBeInTheDocument() expect(screen.getByLabelText('Password')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Sign in' })).toBeInTheDocument()
}) })
it('requests a code and moves to the verification step', async () => { it('signs in with username and password, then lands on the default page', async () => {
const requestCode = vi.spyOn(authApi, 'requestCode').mockResolvedValue({ const login = vi.spyOn(authApi, 'login').mockResolvedValue({
status: 'success', access_token: 'real-access',
data: { phone_code_hash: 'hash-123', is_registered: true }, refresh_token: 'real-refresh',
token_type: 'bearer',
}) })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'alice', role: 'user' } })
renderLogin() renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567') await userEvent.type(screen.getByLabelText('Username'), 'alice')
await userEvent.click(screen.getByRole('button', { name: 'Send code' })) await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
await waitFor(() => expect(requestCode).toHaveBeenCalledWith('+15551234567')) await waitFor(() => expect(login).toHaveBeenCalledWith('alice', 'correcthorse'))
expect(await screen.findByLabelText('Verification code')).toBeInTheDocument() expect(await screen.findByText('Library page')).toBeInTheDocument()
expect(screen.getByText(/Enter the code sent to \+15551234567/)).toBeInTheDocument()
}) })
it('shows the backend error when requesting a code fails (e.g. rate limited)', async () => { it('shows the backend error when login fails, without navigating away', async () => {
vi.spyOn(authApi, 'requestCode').mockRejectedValue( vi.spyOn(authApi, 'login').mockRejectedValue(new ApiError(401, 'Invalid username or password', null))
new ApiError(429, 'Too many code requests for this number, try again later', null),
)
renderLogin() renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567') await userEvent.type(screen.getByLabelText('Username'), 'alice')
await userEvent.click(screen.getByRole('button', { name: 'Send code' })) await userEvent.type(screen.getByLabelText('Password'), 'wrongpassword')
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
expect(await screen.findByText(/Too many code requests/)).toBeInTheDocument() expect(await screen.findByText('Invalid username or password')).toBeInTheDocument()
// Still on the phone step - never advanced past a failed request. expect(screen.queryByText('Library page')).not.toBeInTheDocument()
expect(screen.queryByLabelText('Verification code')).not.toBeInTheDocument()
}) })
it('lets you go back and use a different number', async () => { it('sends the user back to the page they originally tried to reach', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({ vi.spyOn(authApi, 'login').mockResolvedValue({
access_token: 'real-access',
refresh_token: 'real-refresh',
token_type: 'bearer',
})
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success', status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true }, user: { id: 1, username: 'alice', role: 'business_admin' },
}) })
renderLogin() renderLogin([{ pathname: '/login', state: { from: { pathname: '/business' } } }])
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567') await userEvent.type(screen.getByLabelText('Username'), 'alice')
await userEvent.click(screen.getByRole('button', { name: 'Send code' })) await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
await screen.findByLabelText('Verification code') await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
await userEvent.click(screen.getByRole('button', { name: 'Use a different number' }))
expect(screen.getByLabelText('Phone number')).toBeInTheDocument() expect(await screen.findByText('Business page')).toBeInTheDocument()
expect(screen.queryByLabelText('Verification code')).not.toBeInTheDocument()
}) })
it('verifies the code, logs in, and lands on the default page', async () => { it('toggles to register mode and creates an account', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({ const register = vi.spyOn(authApi, 'register').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
const login = vi.spyOn(authApi, 'login').mockResolvedValue({
access_token: 'real-access', access_token: 'real-access',
refresh_token: 'real-refresh', refresh_token: 'real-refresh',
token_type: 'bearer', token_type: 'bearer',
}) })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } }) vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 2, username: 'newuser', role: 'user' } })
renderLogin() renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567') await userEvent.click(screen.getByText("Don't have an account? Register"))
await userEvent.click(screen.getByRole('button', { name: 'Send code' })) expect(screen.getByRole('button', { name: 'Create account' })).toBeInTheDocument()
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify' }))
await waitFor(() => expect(login).toHaveBeenCalledWith('+15551234567', 'hash-123', '12345')) await userEvent.type(screen.getByLabelText('Username'), 'newuser')
await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
await waitFor(() => expect(register).toHaveBeenCalledWith('newuser', 'correcthorse'))
expect(await screen.findByText('Library page')).toBeInTheDocument() expect(await screen.findByText('Library page')).toBeInTheDocument()
}) })
it('sends the user back to the page they originally tried to reach', async () => { it('shows the backend error when registration fails (e.g. duplicate username)', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({ vi.spyOn(authApi, 'register').mockRejectedValue(new ApiError(409, 'Username already taken', null))
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
vi.spyOn(authApi, 'login').mockResolvedValue({
access_token: 'real-access',
refresh_token: 'real-refresh',
token_type: 'bearer',
})
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'x', role: 'business_admin' },
})
renderLogin([{ pathname: '/login', state: { from: { pathname: '/business' } } }]) renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567') await userEvent.click(screen.getByText("Don't have an account? Register"))
await userEvent.click(screen.getByRole('button', { name: 'Send code' })) await userEvent.type(screen.getByLabelText('Username'), 'dupeuser')
await userEvent.type(await screen.findByLabelText('Verification code'), '12345') await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
await userEvent.click(screen.getByRole('button', { name: 'Verify' })) await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
expect(await screen.findByText('Business page')).toBeInTheDocument() expect(await screen.findByText('Username already taken')).toBeInTheDocument()
expect(screen.queryByText('Library page')).not.toBeInTheDocument()
}) })
it('shows the backend error when the code is wrong, without navigating away', async () => { it('lets you toggle back from register to sign-in', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
vi.spyOn(authApi, 'login').mockRejectedValue(new ApiError(400, 'Invalid code', null))
renderLogin() renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567') await userEvent.click(screen.getByText("Don't have an account? Register"))
await userEvent.click(screen.getByRole('button', { name: 'Send code' })) await userEvent.click(screen.getByText('Already have an account? Sign in'))
await userEvent.type(await screen.findByLabelText('Verification code'), '00000') expect(screen.getByRole('button', { name: 'Sign in' })).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Verify' }))
expect(await screen.findByText('Invalid code')).toBeInTheDocument()
expect(screen.queryByText('Library page')).not.toBeInTheDocument()
}) })
}) })
...@@ -4,46 +4,29 @@ import { Headphones } from 'lucide-react' ...@@ -4,46 +4,29 @@ import { Headphones } from 'lucide-react'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input' import { Input } from '../components/ui/Input'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { login, requestCode } from '../api/auth' import { login, register } from '../api/auth'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
type Step = 'phone' | 'code' type Mode = 'login' | 'register'
export function Login() { export function Login() {
const { completeLogin } = useAuth() const { completeLogin } = useAuth()
const navigate = useNavigate() const navigate = useNavigate()
const location = useLocation() const location = useLocation()
const [step, setStep] = useState<Step>('phone') const [mode, setMode] = useState<Mode>('login')
const [phoneNumber, setPhoneNumber] = useState('') const [username, setUsername] = useState('')
const [phoneCodeHash, setPhoneCodeHash] = useState('') const [password, setPassword] = useState('')
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
async function handleSendCode(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
if (!phoneNumber.trim()) return if (!username.trim() || !password) return
setBusy(true) setBusy(true)
setError(null) setError(null)
try { try {
const res = await requestCode(phoneNumber.trim()) const tokens = mode === 'login' ? await login(username.trim(), password) : await register(username.trim(), password)
setPhoneCodeHash(res.data.phone_code_hash)
setStep('code')
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to send a code. Please try again.')
} finally {
setBusy(false)
}
}
async function handleVerifyCode(e: React.FormEvent) {
e.preventDefault()
if (!code.trim()) return
setBusy(true)
setError(null)
try {
const tokens = await login(phoneNumber.trim(), phoneCodeHash, code.trim())
completeLogin(tokens) completeLogin(tokens)
// Sends them back to whatever protected page they originally tried to reach (see // Sends them back to whatever protected page they originally tried to reach (see
// ProtectedRoute/RequireRole, which stash it as location.state.from), not just a fixed // ProtectedRoute/RequireRole, which stash it as location.state.from), not just a fixed
...@@ -51,15 +34,18 @@ export function Login() { ...@@ -51,15 +34,18 @@ export function Login() {
const from = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? '/library' const from = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? '/library'
navigate(from, { replace: true }) navigate(from, { replace: true })
} catch (err) { } catch (err) {
setError(err instanceof ApiError ? err.message : 'That code didn\'t work. Please try again.') if (err instanceof ApiError) {
setError(err.message)
} else {
setError(mode === 'login' ? 'Could not sign in. Please try again.' : 'Could not create an account. Please try again.')
}
} finally { } finally {
setBusy(false) setBusy(false)
} }
} }
function handleChangeNumber() { function toggleMode() {
setStep('phone') setMode((m) => (m === 'login' ? 'register' : 'login'))
setCode('')
setError(null) setError(null)
} }
...@@ -70,52 +56,40 @@ export function Login() { ...@@ -70,52 +56,40 @@ export function Login() {
<Headphones size={28} strokeWidth={2} className="text-emerald-400" /> <Headphones size={28} strokeWidth={2} className="text-emerald-400" />
<h1 className="text-xl font-semibold tracking-tight">Stax</h1> <h1 className="text-xl font-semibold tracking-tight">Stax</h1>
<p className="text-sm text-neutral-400"> <p className="text-sm text-neutral-400">
{step === 'phone' ? 'Sign in with your Telegram phone number.' : `Enter the code sent to ${phoneNumber}.`} {mode === 'login' ? 'Sign in to your account.' : 'Create an account.'}
</p> </p>
</div> </div>
{step === 'phone' ? ( <form onSubmit={handleSubmit} className="space-y-3">
<form onSubmit={handleSendCode} className="space-y-3"> <Input
<Input type="text"
type="tel" autoComplete="username"
inputMode="tel" autoFocus
autoComplete="tel" placeholder="Username"
autoFocus value={username}
placeholder="+1 555 123 4567" onChange={(e) => setUsername(e.target.value)}
value={phoneNumber} aria-label="Username"
onChange={(e) => setPhoneNumber(e.target.value)} />
aria-label="Phone number" <Input
/> type="password"
{error && <p className="text-sm text-red-400">{error}</p>} autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
<Button type="submit" disabled={busy || !phoneNumber.trim()} className="w-full"> placeholder="Password"
{busy ? 'Sending code…' : 'Send code'} value={password}
</Button> onChange={(e) => setPassword(e.target.value)}
</form> aria-label="Password"
) : ( />
<form onSubmit={handleVerifyCode} className="space-y-3"> {error && <p className="text-sm text-red-400">{error}</p>}
<Input <Button type="submit" disabled={busy || !username.trim() || !password} className="w-full">
type="text" {busy ? (mode === 'login' ? 'Signing in…' : 'Creating account…') : mode === 'login' ? 'Sign in' : 'Create account'}
inputMode="numeric" </Button>
autoComplete="one-time-code" <button
autoFocus type="button"
placeholder="12345" onClick={toggleMode}
value={code} className="w-full text-center text-sm text-neutral-500 transition-colors hover:text-neutral-300"
onChange={(e) => setCode(e.target.value)} >
aria-label="Verification code" {mode === 'login' ? "Don't have an account? Register" : 'Already have an account? Sign in'}
/> </button>
{error && <p className="text-sm text-red-400">{error}</p>} </form>
<Button type="submit" disabled={busy || !code.trim()} className="w-full">
{busy ? 'Verifying…' : 'Verify'}
</Button>
<button
type="button"
onClick={handleChangeNumber}
className="w-full text-center text-sm text-neutral-500 transition-colors hover:text-neutral-300"
>
Use a different number
</button>
</form>
)}
</div> </div>
</div> </div>
) )
......
...@@ -111,13 +111,13 @@ const FEATURES: Feature[] = [ ...@@ -111,13 +111,13 @@ const FEATURES: Feature[] = [
}, },
{ {
name: 'Auth', name: 'Auth',
sub: 'Telegram phone/code login', sub: 'Username/password login',
status: 'warn', status: 'warn',
statusLabel: 'Backend solid, UI landing now', statusLabel: 'Backend + UI shipped',
built: 'Real DB-backed rate limiting, refresh-token rotation, a real server-side logout that revokes the token — not just a client-side drop. A real login screen is being added now.', built: 'Plain username/password is the primary login (PBKDF2-hashed, stdlib only, no bcrypt dependency), with refresh-token rotation and a real server-side logout that revokes the token — not just a client-side drop. Telegram phone/code (/auth/telegram/*) is now a separate account-linking flow, feeding the chat-scanning music-tagging feature rather than being the identity mechanism.',
gaps: 'Per-IP limiter has no proxy-header handling, so every user could share one bucket in production. The real Telegram sign-in code path is fully mocked in every test.', gaps: 'Per-IP limiter on /auth/telegram/request_code has no proxy-header handling, so every user could share one bucket in production. No brute-force rate limit on /auth/login yet. The real Telegram sign-in code path is fully mocked in every test. No frontend UI yet to actually link a Telegram account post-login.',
backendTests: '12', backendTests: '20',
frontendTests: '—', frontendTests: '7',
}, },
] ]
...@@ -129,7 +129,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[ ...@@ -129,7 +129,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[
items: [ items: [
'Auth-gate /remix and derive user_id from the JWT instead of a form field.', 'Auth-gate /remix and derive user_id from the JWT instead of a form field.',
'Fix the room WebSocket — stop trusting a bare user_id query param.', 'Fix the room WebSocket — stop trusting a bare user_id query param.',
'Real login screen — landing now, so the app finally works for someone other than the dev account.', 'Real login screen — shipped as username/password, so the app finally works for someone other than the dev account.',
], ],
}, },
{ {
...@@ -143,6 +143,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[ ...@@ -143,6 +143,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[
"Wire remix's library linking into the composer UI.", "Wire remix's library linking into the composer UI.",
'Library search box on the Library page.', 'Library search box on the Library page.',
'Test coverage for Upload, Discovery, and Remix — all currently zero.', 'Test coverage for Upload, Discovery, and Remix — all currently zero.',
'Telegram linking UI — phone number + code, attaches a session to the logged-in user so /auth/telegram/chats can actually be used from the app.',
], ],
}, },
{ {
...@@ -154,6 +155,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[ ...@@ -154,6 +155,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[
'Real "couldn\'t identify" feedback in Discovery — surface a confidence score instead of one generic error.', 'Real "couldn\'t identify" feedback in Discovery — surface a confidence score instead of one generic error.',
"Rate-limit Discovery's identify endpoint the way auth's request_code already is.", "Rate-limit Discovery's identify endpoint the way auth's request_code already is.",
'Proxy-aware IP detection for the auth rate limiter before this sits behind a real load balancer.', 'Proxy-aware IP detection for the auth rate limiter before this sits behind a real load balancer.',
'Telegram chat scanning — auto-scan all or user-approved linked chats for music, tag and save straight into the library, instead of the current one-chat-at-a-time /auth/telegram/chats/{id}/music lookup.',
], ],
}, },
] ]
......
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