Commit be345ade authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add real Telegram phone/code login, replacing the dev-only auto-auth gap

Nothing but the dev account could ever use this app - ProtectedRoute and
RequireRole just showed a static "not authenticated" message with no
way forward. Adds a real two-step login screen (phone -> code, via the
backend's existing /auth/request_code + /auth/login, unchanged) and
wires it in as the actual destination: both guards now redirect to
/login (preserving the originally-requested page via router state) and
land back where the user was trying to go, matching a normal auth flow
instead of a dead end.

Also fixes a real race this surfaced during live testing: the dev-only
auto-login bootstrap ran in a useEffect, which only fires *after* the
first render. ProtectedRoute's brand-new <Navigate> redirect renders
before that effect ever gets a chance to run, so isAuthenticated was
still false on the very first paint - every fresh dev-mode load bounced
through /login before the bootstrap could authenticate it, sometimes
stranding the session there since flipping isAuthenticated true a
moment later doesn't undo an already-completed redirect. Moved the
bootstrap into the isAuthenticated state's lazy initializer instead, so
it runs synchronously before the first render - the same reason a real
user's already-stored token doesn't have this problem.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 558c6513
...@@ -10,6 +10,8 @@ import { Remix } from './pages/Remix' ...@@ -10,6 +10,8 @@ import { Remix } from './pages/Remix'
import { Nearby } from './pages/Nearby' import { Nearby } from './pages/Nearby'
import { BusinessPanel } from './pages/BusinessPanel' import { BusinessPanel } from './pages/BusinessPanel'
import { AdminPanel } from './pages/AdminPanel' import { AdminPanel } from './pages/AdminPanel'
import { Roadmap } from './pages/Roadmap'
import { Login } from './pages/Login'
import { ProtectedRoute } from './components/ProtectedRoute' import { ProtectedRoute } from './components/ProtectedRoute'
import { RequireRole } from './components/RequireRole' import { RequireRole } from './components/RequireRole'
...@@ -20,6 +22,7 @@ function protect(element: React.ReactElement) { ...@@ -20,6 +22,7 @@ function protect(element: React.ReactElement) {
export function App() { export function App() {
return ( return (
<Routes> <Routes>
<Route path="/login" element={<Login />} />
<Route path="/library" element={protect(<Library />)} /> <Route path="/library" element={protect(<Library />)} />
<Route path="/upload" element={protect(<Upload />)} /> <Route path="/upload" element={protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />)} /> <Route path="/discovery" element={protect(<Discovery />)} />
...@@ -45,6 +48,14 @@ export function App() { ...@@ -45,6 +48,14 @@ export function App() {
</RequireRole> </RequireRole>
} }
/> />
<Route
path="/roadmap"
element={
<RequireRole role="super_admin">
<Roadmap />
</RequireRole>
}
/>
<Route path="*" element={<Navigate to="/library" replace />} /> <Route path="*" element={<Navigate to="/library" replace />} />
</Routes> </Routes>
) )
......
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 {
access_token: string
refresh_token: string
token_type: string
}
export function login(phoneNumber: string, phoneCodeHash: string, code: string) {
return apiFetch<TokenPair>('/auth/login', {
method: 'POST',
json: { phone_number: phoneNumber, phone_code_hash: phoneCodeHash, code },
auth: false,
})
}
export function logout(refreshToken: string) { export function logout(refreshToken: string) {
return apiFetch<{ status: string }>('/auth/logout', { return apiFetch<{ status: string }>('/auth/logout', {
method: 'POST', method: 'POST',
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
Headphones, Headphones,
Library, Library,
LogOut, LogOut,
Map,
MapPin, MapPin,
MapPinned, MapPinned,
Radio, Radio,
...@@ -41,10 +42,11 @@ export function Layout({ title, children }: { title: string; children: ReactNode ...@@ -41,10 +42,11 @@ export function Layout({ title, children }: { title: string; children: ReactNode
const location = useLocation() const location = useLocation()
async function handleLogout() { async function handleLogout() {
// No login page to send them to - dev re-authenticates automatically on next load (see // No reload needed: once isAuthenticated flips false, the ProtectedRoute/RequireRole
// AuthContext.tsx), this just clears the session to test what a logged-out state looks like. // wrapping whatever page is currently mounted re-renders and redirects to /login on its
// own. A full reload would just re-trigger the dev-only auto-login bootstrap in DEV mode
// (see AuthContext.tsx) instead of actually landing on the login page.
await logout() await logout()
window.location.reload()
} }
return ( return (
...@@ -85,6 +87,18 @@ export function Layout({ title, children }: { title: string; children: ReactNode ...@@ -85,6 +87,18 @@ export function Layout({ title, children }: { title: string; children: ReactNode
<span className="hidden sm:inline" aria-hidden="true">Admin</span> <span className="hidden sm:inline" aria-hidden="true">Admin</span>
</Link> </Link>
)} )}
{isSuperAdmin && (
<Link
to="/roadmap"
aria-label="Status and roadmap"
className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors duration-150 ${
location.pathname === '/roadmap' ? 'bg-neutral-900 text-white' : 'text-neutral-400 hover:text-white'
}`}
>
<Map size={15} strokeWidth={2} aria-hidden="true" />
<span className="hidden sm:inline" aria-hidden="true">Roadmap</span>
</Link>
)}
<Button variant="ghost" size="sm" onClick={handleLogout} aria-label="Log out" className="gap-1.5 !px-3"> <Button variant="ghost" size="sm" onClick={handleLogout} aria-label="Log out" className="gap-1.5 !px-3">
<LogOut size={15} strokeWidth={2} aria-hidden="true" /> <LogOut size={15} strokeWidth={2} aria-hidden="true" />
<span className="hidden sm:inline" aria-hidden="true">Log out</span> <span className="hidden sm:inline" aria-hidden="true">Log out</span>
......
import { render, screen } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'
import { ProtectedRoute } from './ProtectedRoute'
import * as AuthContextModule from '../context/AuthContext'
function mockAuth(isAuthenticated: boolean) {
vi.spyOn(AuthContextModule, 'useAuth').mockReturnValue({
isAuthenticated,
role: null,
isBusinessAdmin: false,
isSuperAdmin: false,
logout: vi.fn(),
completeLogin: vi.fn(),
})
}
function renderProtected() {
return render(
<MemoryRouter initialEntries={['/library']}>
<Routes>
<Route
path="/library"
element={
<ProtectedRoute>
<p>Library content</p>
</ProtectedRoute>
}
/>
<Route path="/login" element={<p>Login screen</p>} />
</Routes>
</MemoryRouter>,
)
}
describe('ProtectedRoute', () => {
it('renders the page when authenticated', () => {
mockAuth(true)
renderProtected()
expect(screen.getByText('Library content')).toBeInTheDocument()
})
it('redirects to /login when not authenticated', () => {
mockAuth(false)
renderProtected()
expect(screen.getByText('Login screen')).toBeInTheDocument()
expect(screen.queryByText('Library content')).not.toBeInTheDocument()
})
})
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
export function ProtectedRoute({ children }: { children: ReactNode }) { export function ProtectedRoute({ children }: { children: ReactNode }) {
const { isAuthenticated } = useAuth() const { isAuthenticated } = useAuth()
const location = useLocation()
if (!isAuthenticated) { if (!isAuthenticated) {
// No login flow exists in this app right now (dev auto-authenticates via // Login.tsx reads location.state.from to send them back here once they're signed in,
// VITE_DEV_ACCESS_TOKEN/VITE_DEV_REFRESH_TOKEN - see AuthContext.tsx). A production // instead of dumping everyone at the same default page regardless of what they wanted.
// build without a real login page has no route to send an unauthenticated user to. return <Navigate to="/login" state={{ from: location }} replace />
return (
<div className="flex min-h-screen items-center justify-center bg-neutral-950 px-4 text-center text-neutral-400">
<p>Not authenticated - no login flow is wired up in this build.</p>
</div>
)
} }
return <>{children}</> return <>{children}</>
} }
import { render, screen } from '@testing-library/react' import { render, screen } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest' import { describe, expect, it, vi } from 'vitest'
import { RequireRole } from './RequireRole' import { RequireRole } from './RequireRole'
import * as AuthContextModule from '../context/AuthContext' import * as AuthContextModule from '../context/AuthContext'
...@@ -10,77 +11,74 @@ function mockAuth(overrides: Partial<ReturnType<typeof AuthContextModule.useAuth ...@@ -10,77 +11,74 @@ function mockAuth(overrides: Partial<ReturnType<typeof AuthContextModule.useAuth
isBusinessAdmin: false, isBusinessAdmin: false,
isSuperAdmin: false, isSuperAdmin: false,
logout: vi.fn(), logout: vi.fn(),
completeLogin: vi.fn(),
...overrides, ...overrides,
}) })
} }
/** Renders RequireRole behind a real route so Navigate redirects (which need a Router context
* and don't render visible content themselves) can be observed by checking which route actually
* ended up on screen - a stand-in /login route plays the same role Login.tsx does for real. */
function renderGuarded(role: 'business_admin' | 'super_admin', content = 'Secret content') {
return render(
<MemoryRouter initialEntries={['/protected']}>
<Routes>
<Route
path="/protected"
element={
<RequireRole role={role}>
<p>{content}</p>
</RequireRole>
}
/>
<Route path="/login" element={<p>Login screen</p>} />
</Routes>
</MemoryRouter>,
)
}
describe('RequireRole', () => { describe('RequireRole', () => {
it('shows a not-authenticated message when the user is not logged in', () => { it('redirects to /login when the user is not logged in', () => {
mockAuth({ isAuthenticated: false, role: null }) mockAuth({ isAuthenticated: false, role: null })
render( renderGuarded('business_admin')
<RequireRole role="business_admin"> expect(screen.getByText('Login screen')).toBeInTheDocument()
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText(/Not authenticated/)).toBeInTheDocument()
expect(screen.queryByText('Secret content')).not.toBeInTheDocument() expect(screen.queryByText('Secret content')).not.toBeInTheDocument()
}) })
it('renders nothing while role is still resolving (avoids flashing "access denied")', () => { it('renders nothing while role is still resolving (avoids flashing "access denied")', () => {
mockAuth({ isAuthenticated: true, role: null }) mockAuth({ isAuthenticated: true, role: null })
const { container } = render( renderGuarded('business_admin')
<RequireRole role="business_admin"> expect(screen.queryByText('Secret content')).not.toBeInTheDocument()
<p>Secret content</p> expect(screen.queryByText('Login screen')).not.toBeInTheDocument()
</RequireRole>, expect(screen.queryByText(/access/)).not.toBeInTheDocument()
)
expect(container).toBeEmptyDOMElement()
}) })
it('denies a plain user access to a business_admin-gated page', () => { it('denies a plain user access to a business_admin-gated page', () => {
mockAuth({ isAuthenticated: true, role: 'user', isBusinessAdmin: false, isSuperAdmin: false }) mockAuth({ isAuthenticated: true, role: 'user', isBusinessAdmin: false, isSuperAdmin: false })
render( renderGuarded('business_admin')
<RequireRole role="business_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText(/don't have access/)).toBeInTheDocument() expect(screen.getByText(/don't have access/)).toBeInTheDocument()
expect(screen.queryByText('Secret content')).not.toBeInTheDocument() expect(screen.queryByText('Secret content')).not.toBeInTheDocument()
}) })
it('allows a business_admin into a business_admin-gated page', () => { it('allows a business_admin into a business_admin-gated page', () => {
mockAuth({ isAuthenticated: true, role: 'business_admin', isBusinessAdmin: true, isSuperAdmin: false }) mockAuth({ isAuthenticated: true, role: 'business_admin', isBusinessAdmin: true, isSuperAdmin: false })
render( renderGuarded('business_admin')
<RequireRole role="business_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText('Secret content')).toBeInTheDocument() expect(screen.getByText('Secret content')).toBeInTheDocument()
}) })
it('denies a business_admin access to a super_admin-gated page', () => { it('denies a business_admin access to a super_admin-gated page', () => {
mockAuth({ isAuthenticated: true, role: 'business_admin', isBusinessAdmin: true, isSuperAdmin: false }) mockAuth({ isAuthenticated: true, role: 'business_admin', isBusinessAdmin: true, isSuperAdmin: false })
render( renderGuarded('super_admin')
<RequireRole role="super_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText(/don't have access/)).toBeInTheDocument() expect(screen.getByText(/don't have access/)).toBeInTheDocument()
}) })
it('allows a super_admin into both business_admin- and super_admin-gated pages (elevated privileges)', () => { it('allows a super_admin into both business_admin- and super_admin-gated pages (elevated privileges)', () => {
mockAuth({ isAuthenticated: true, role: 'super_admin', isBusinessAdmin: true, isSuperAdmin: true }) mockAuth({ isAuthenticated: true, role: 'super_admin', isBusinessAdmin: true, isSuperAdmin: true })
const { rerender } = render( renderGuarded('business_admin', 'Business content')
<RequireRole role="business_admin">
<p>Business content</p>
</RequireRole>,
)
expect(screen.getByText('Business content')).toBeInTheDocument() expect(screen.getByText('Business content')).toBeInTheDocument()
rerender( mockAuth({ isAuthenticated: true, role: 'super_admin', isBusinessAdmin: true, isSuperAdmin: true })
<RequireRole role="super_admin"> renderGuarded('super_admin', 'Admin content')
<p>Admin content</p>
</RequireRole>,
)
expect(screen.getByText('Admin content')).toBeInTheDocument() expect(screen.getByText('Admin content')).toBeInTheDocument()
}) })
}) })
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
export function RequireRole({ role, children }: { role: 'business_admin' | 'super_admin'; children: ReactNode }) { export function RequireRole({ role, children }: { role: 'business_admin' | 'super_admin'; children: ReactNode }) {
const { isAuthenticated, role: currentRole, isBusinessAdmin, isSuperAdmin } = useAuth() const { isAuthenticated, role: currentRole, isBusinessAdmin, isSuperAdmin } = useAuth()
const location = useLocation()
if (!isAuthenticated) { if (!isAuthenticated) {
return ( return <Navigate to="/login" state={{ from: location }} replace />
<div className="flex min-h-screen items-center justify-center bg-neutral-950 px-4 text-center text-neutral-400">
<p>Not authenticated - no login flow is wired up in this build.</p>
</div>
)
} }
// Still resolving /auth/me - render nothing rather than flashing "access denied" for // Still resolving /auth/me - render nothing rather than flashing "access denied" for
......
...@@ -192,6 +192,49 @@ describe('AuthProvider dev auto-login', () => { ...@@ -192,6 +192,49 @@ describe('AuthProvider dev auto-login', () => {
}) })
}) })
describe('completeLogin', () => {
afterEach(() => {
vi.unstubAllEnvs()
clearTokens()
vi.restoreAllMocks()
})
it('stores the real token pair from a login and flips isAuthenticated to true', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'real-user', role: 'user' },
})
function LoginButton() {
const { completeLogin } = useAuth()
return (
<button onClick={() => completeLogin({ access_token: 'real-access', refresh_token: 'real-refresh', token_type: 'bearer' })}>
Complete login
</button>
)
}
render(
<AuthProvider>
<LoginButton />
<Probe useAuth={useAuth} />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('not-authenticated')
screen.getByText('Complete login').click()
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
expect(getAccessToken()).toBe('real-access')
expect(getRefreshToken()).toBe('real-refresh')
await waitFor(() => expect(screen.getByTestId('role')).toHaveTextContent('user'))
})
})
describe('logout', () => { describe('logout', () => {
afterEach(() => { afterEach(() => {
vi.unstubAllEnvs() vi.unstubAllEnvs()
......
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import * as authApi from '../api/auth' import * as authApi from '../api/auth'
import type { UserRole } from '../api/auth' import type { TokenPair, UserRole } from '../api/auth'
import { ApiError, clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client' import { ApiError, clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client'
interface AuthContextValue { interface AuthContextValue {
...@@ -12,36 +12,45 @@ interface AuthContextValue { ...@@ -12,36 +12,45 @@ interface AuthContextValue {
isBusinessAdmin: boolean isBusinessAdmin: boolean
isSuperAdmin: boolean isSuperAdmin: boolean
logout: () => Promise<void> logout: () => Promise<void>
/** Called by Login.tsx once /auth/login returns a real token pair - stores them and flips
* isAuthenticated, same effect a page reload after the old dev-only bootstrap used to have. */
completeLogin: (tokens: TokenPair) => void
} }
const AuthContext = createContext<AuthContextValue | null>(null) const AuthContext = createContext<AuthContextValue | null>(null)
function bootstrapAuth(): boolean {
if (getAccessToken()) return true
// This dev-only bootstrap is separate from (and skipped entirely for) the real login flow in
// Login.tsx/completeLogin below - it exists purely so `npm run dev` doesn't require clicking
// through a real Telegram code every time. import.meta.env.DEV is Vite's own flag (true for
// `npm run dev`, false in a production build), so this never runs outside local development
// no matter what. The tokens are for a real, DB-backed dev-test-user row and refresh_tokens
// entry on the dev server (not a fake/forged pair) - the existing auto-refresh-on-401 in
// client.ts keeps working against them indefinitely, same as a real login would.
//
// Runs synchronously as the isAuthenticated state's lazy initializer, not a useEffect: an
// effect only fires *after* the first render, so ProtectedRoute/RequireRole's very first
// render would still see isAuthenticated as false and redirect to /login via <Navigate>
// before this ever got a chance to run - stranding a dev session on the login page even
// though it was about to auto-authenticate a moment later. Reading import.meta.env here
// (rather than as a module-level constant) still lets a test's vi.stubEnv() control it,
// since stubEnv always runs in beforeEach - before render() - regardless of whether this is
// an effect or an initializer.
if (!import.meta.env.DEV) return false
const devAccessToken = import.meta.env.VITE_DEV_ACCESS_TOKEN as string | undefined
const devRefreshToken = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | undefined
if (devAccessToken && devRefreshToken) {
setTokens(devAccessToken, devRefreshToken)
return true
}
return false
}
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(() => Boolean(getAccessToken())) const [isAuthenticated, setIsAuthenticated] = useState(bootstrapAuth)
const [role, setRole] = useState<UserRole | null>(null) const [role, setRole] = useState<UserRole | null>(null)
useEffect(() => {
// Real Telegram phone/code login is gone from this app for now - dev doesn't need it at
// all. import.meta.env.DEV is Vite's own flag (true for `npm run dev`, false in a
// production build), so this bootstrap never runs outside local development no matter
// what. The tokens are for a real, DB-backed dev-test-user row and refresh_tokens entry on
// the dev server (not a fake/forged pair) - the existing auto-refresh-on-401 in client.ts
// keeps working against them indefinitely, same as a real login would.
//
// Read fresh here on every mount rather than as module-level constants: import.meta.env is
// captured once at module-evaluation time otherwise, which a test's vi.stubEnv() (run in
// its own beforeEach, after this module has already loaded) can never retroactively
// change - every test file rendering AuthProvider without vi.resetModules() gymnastics
// would otherwise silently pick up .env's real dev tokens and, if those happen to be
// currently valid, make a genuine network call to the live backend during `npm test`.
const devAccessToken = import.meta.env.VITE_DEV_ACCESS_TOKEN as string | undefined
const devRefreshToken = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | undefined
if (import.meta.env.DEV && !getAccessToken() && devAccessToken && devRefreshToken) {
setTokens(devAccessToken, devRefreshToken)
setIsAuthenticated(true)
}
}, [])
useEffect(() => { useEffect(() => {
if (!isAuthenticated) { if (!isAuthenticated) {
setRole(null) setRole(null)
...@@ -80,11 +89,16 @@ export function AuthProvider({ children }: { children: ReactNode }) { ...@@ -80,11 +89,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} }
} }
function completeLogin(tokens: TokenPair) {
setTokens(tokens.access_token, tokens.refresh_token)
setIsAuthenticated(true)
}
const isBusinessAdmin = role === 'business_admin' || role === 'super_admin' const isBusinessAdmin = role === 'business_admin' || role === 'super_admin'
const isSuperAdmin = role === 'super_admin' const isSuperAdmin = role === 'super_admin'
return ( return (
<AuthContext.Provider value={{ isAuthenticated, role, isBusinessAdmin, isSuperAdmin, logout }}> <AuthContext.Provider value={{ isAuthenticated, role, isBusinessAdmin, isSuperAdmin, logout, completeLogin }}>
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>
) )
......
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Login } from './Login'
import { AuthProvider } from '../context/AuthContext'
import { ApiError } from '../api/client'
import * as authApi from '../api/auth'
function renderLogin(initialEntries: { pathname: string; state?: unknown }[] = [{ pathname: '/login' }]) {
return render(
<MemoryRouter initialEntries={initialEntries}>
<AuthProvider>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/library" element={<p>Library page</p>} />
<Route path="/business" element={<p>Business page</p>} />
</Routes>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Login', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('starts on the phone number step', () => {
renderLogin()
expect(screen.getByLabelText('Phone number')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Send code' })).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 },
})
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await waitFor(() => expect(requestCode).toHaveBeenCalledWith('+15551234567'))
expect(await screen.findByLabelText('Verification code')).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 () => {
vi.spyOn(authApi, 'requestCode').mockRejectedValue(
new ApiError(429, 'Too many code requests for this number, try again later', null),
)
renderLogin()
await userEvent.type(screen.getByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
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()
})
it('lets you go back and use a different number', async () => {
vi.spyOn(authApi, 'requestCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
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' }))
expect(screen.getByLabelText('Phone number')).toBeInTheDocument()
expect(screen.queryByLabelText('Verification code')).not.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({
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' } })
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 waitFor(() => expect(login).toHaveBeenCalledWith('+15551234567', 'hash-123', '12345'))
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' },
})
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' }))
expect(await screen.findByText('Business page')).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))
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()
})
})
import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
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 { useAuth } from '../context/AuthContext'
type Step = 'phone' | 'code'
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 [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSendCode(e: React.FormEvent) {
e.preventDefault()
if (!phoneNumber.trim()) 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())
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
// default - a business admin bookmarking /business shouldn't land on /library first.
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.')
} finally {
setBusy(false)
}
}
function handleChangeNumber() {
setStep('phone')
setCode('')
setError(null)
}
return (
<div className="flex min-h-screen items-center justify-center bg-neutral-950 px-4 text-white">
<div className="w-full max-w-sm">
<div className="mb-8 flex flex-col items-center gap-2 text-center">
<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}.`}
</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>
)}
</div>
</div>
)
}
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