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'
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 {
access_token: string
refresh_token: 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', {
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,
})
}
......@@ -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 {
id: number
title: string
......@@ -44,7 +62,7 @@ export interface Chat {
}
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'
......
......@@ -32,118 +32,98 @@ describe('Login', () => {
vi.restoreAllMocks()
})
it('starts on the phone number step', () => {
it('starts in sign-in mode', () => {
renderLogin()
expect(screen.getByLabelText('Phone number')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Send code' })).toBeInTheDocument()
expect(screen.getByLabelText('Username')).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 () => {
const requestCode = vi.spyOn(authApi, 'requestCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
it('signs in with username and password, then lands on the default page', async () => {
const login = 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: 'alice', role: 'user' } })
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(screen.getByLabelText('Username'), 'alice')
await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
await waitFor(() => expect(requestCode).toHaveBeenCalledWith('+15551234567'))
expect(await screen.findByLabelText('Verification code')).toBeInTheDocument()
expect(screen.getByText(/Enter the code sent to \+15551234567/)).toBeInTheDocument()
await waitFor(() => expect(login).toHaveBeenCalledWith('alice', 'correcthorse'))
expect(await screen.findByText('Library page')).toBeInTheDocument()
})
it('shows the backend error when requesting a code fails (e.g. rate limited)', async () => {
vi.spyOn(authApi, 'requestCode').mockRejectedValue(
new ApiError(429, 'Too many code requests for this number, try again later', null),
)
it('shows the backend error when login fails, without navigating away', async () => {
vi.spyOn(authApi, 'login').mockRejectedValue(new ApiError(401, 'Invalid username or password', null))
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(screen.getByLabelText('Username'), 'alice')
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()
// Still on the phone step - never advanced past a failed request.
expect(screen.queryByLabelText('Verification code')).not.toBeInTheDocument()
expect(await screen.findByText('Invalid username or password')).toBeInTheDocument()
expect(screen.queryByText('Library page')).not.toBeInTheDocument()
})
it('lets you go back and use a different number', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({
it('sends the user back to the page they originally tried to reach', async () => {
vi.spyOn(authApi, 'login').mockResolvedValue({
access_token: 'real-access',
refresh_token: 'real-refresh',
token_type: 'bearer',
})
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
user: { id: 1, username: 'alice', role: 'business_admin' },
})
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await screen.findByLabelText('Verification code')
await userEvent.click(screen.getByRole('button', { name: 'Use a different number' }))
renderLogin([{ pathname: '/login', state: { from: { pathname: '/business' } } }])
await userEvent.type(screen.getByLabelText('Username'), 'alice')
await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
expect(screen.getByLabelText('Phone number')).toBeInTheDocument()
expect(screen.queryByLabelText('Verification code')).not.toBeInTheDocument()
expect(await screen.findByText('Business page')).toBeInTheDocument()
})
it('verifies the code, logs in, and lands on the default page', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
const login = vi.spyOn(authApi, 'login').mockResolvedValue({
it('toggles to register mode and creates an account', async () => {
const register = vi.spyOn(authApi, 'register').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: 'user' } })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 2, username: 'newuser', role: 'user' } })
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify' }))
await userEvent.click(screen.getByText("Don't have an account? Register"))
expect(screen.getByRole('button', { name: 'Create account' })).toBeInTheDocument()
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()
})
it('sends the user back to the page they originally tried to reach', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({
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' },
})
it('shows the backend error when registration fails (e.g. duplicate username)', async () => {
vi.spyOn(authApi, 'register').mockRejectedValue(new ApiError(409, 'Username already taken', null))
renderLogin([{ pathname: '/login', state: { from: { pathname: '/business' } } }])
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify' }))
renderLogin()
await userEvent.click(screen.getByText("Don't have an account? Register"))
await userEvent.type(screen.getByLabelText('Username'), 'dupeuser')
await userEvent.type(screen.getByLabelText('Password'), 'correcthorse')
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 () => {
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))
it('lets you toggle back from register to sign-in', async () => {
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '00000')
await userEvent.click(screen.getByRole('button', { name: 'Verify' }))
expect(await screen.findByText('Invalid code')).toBeInTheDocument()
expect(screen.queryByText('Library page')).not.toBeInTheDocument()
await userEvent.click(screen.getByText("Don't have an account? Register"))
await userEvent.click(screen.getByText('Already have an account? Sign in'))
expect(screen.getByRole('button', { name: 'Sign in' })).toBeInTheDocument()
})
})
......@@ -4,46 +4,29 @@ import { Headphones } from 'lucide-react'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { ApiError } from '../api/client'
import { login, requestCode } from '../api/auth'
import { login, register } from '../api/auth'
import { useAuth } from '../context/AuthContext'
type Step = 'phone' | 'code'
type Mode = 'login' | 'register'
export function Login() {
const { completeLogin } = useAuth()
const navigate = useNavigate()
const location = useLocation()
const [step, setStep] = useState<Step>('phone')
const [phoneNumber, setPhoneNumber] = useState('')
const [phoneCodeHash, setPhoneCodeHash] = useState('')
const [code, setCode] = useState('')
const [mode, setMode] = useState<Mode>('login')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSendCode(e: React.FormEvent) {
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (!phoneNumber.trim()) return
if (!username.trim() || !password) return
setBusy(true)
setError(null)
try {
const res = await requestCode(phoneNumber.trim())
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())
const tokens = mode === 'login' ? await login(username.trim(), password) : await register(username.trim(), password)
completeLogin(tokens)
// 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
......@@ -51,15 +34,18 @@ export function Login() {
const from = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? '/library'
navigate(from, { replace: true })
} 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 {
setBusy(false)
}
}
function handleChangeNumber() {
setStep('phone')
setCode('')
function toggleMode() {
setMode((m) => (m === 'login' ? 'register' : 'login'))
setError(null)
}
......@@ -70,52 +56,40 @@ export function Login() {
<Headphones size={28} strokeWidth={2} className="text-emerald-400" />
<h1 className="text-xl font-semibold tracking-tight">Stax</h1>
<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>
</div>
{step === 'phone' ? (
<form onSubmit={handleSendCode} className="space-y-3">
<Input
type="tel"
inputMode="tel"
autoComplete="tel"
autoFocus
placeholder="+1 555 123 4567"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
aria-label="Phone number"
/>
{error && <p className="text-sm text-red-400">{error}</p>}
<Button type="submit" disabled={busy || !phoneNumber.trim()} className="w-full">
{busy ? 'Sending code…' : 'Send code'}
</Button>
</form>
) : (
<form onSubmit={handleVerifyCode} className="space-y-3">
<Input
type="text"
inputMode="numeric"
autoComplete="one-time-code"
autoFocus
placeholder="12345"
value={code}
onChange={(e) => setCode(e.target.value)}
aria-label="Verification code"
/>
{error && <p className="text-sm text-red-400">{error}</p>}
<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>
)}
<form onSubmit={handleSubmit} className="space-y-3">
<Input
type="text"
autoComplete="username"
autoFocus
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
aria-label="Username"
/>
<Input
type="password"
autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
aria-label="Password"
/>
{error && <p className="text-sm text-red-400">{error}</p>}
<Button type="submit" disabled={busy || !username.trim() || !password} className="w-full">
{busy ? (mode === 'login' ? 'Signing in…' : 'Creating account…') : mode === 'login' ? 'Sign in' : 'Create account'}
</Button>
<button
type="button"
onClick={toggleMode}
className="w-full text-center text-sm text-neutral-500 transition-colors hover:text-neutral-300"
>
{mode === 'login' ? "Don't have an account? Register" : 'Already have an account? Sign in'}
</button>
</form>
</div>
</div>
)
......
......@@ -111,13 +111,13 @@ const FEATURES: Feature[] = [
},
{
name: 'Auth',
sub: 'Telegram phone/code login',
sub: 'Username/password login',
status: 'warn',
statusLabel: 'Backend solid, UI landing now',
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.',
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.',
backendTests: '12',
frontendTests: '—',
statusLabel: 'Backend + UI shipped',
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 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: '20',
frontendTests: '7',
},
]
......@@ -129,7 +129,7 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[
items: [
'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.',
'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[
"Wire remix's library linking into the composer UI.",
'Library search box on the Library page.',
'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[
'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.",
'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