Commit dccf71fe authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Remove phone-number login; auto-authenticate in dev

Login.tsx and the /auth/request_code + /auth/login flow are gone. Dev
doesn't need any login at all now: AuthContext auto-injects
VITE_DEV_ACCESS_TOKEN/VITE_DEV_REFRESH_TOKEN on boot, gated behind Vite's
own import.meta.env.DEV flag so this never activates in a production build
regardless of whether those vars happen to be set.

These are real, DB-backed tokens for a dedicated dev-test-user row (id 1)
and a matching refresh_tokens entry on the dev server - not forged/fake -
so the existing auto-refresh-on-401 in client.ts keeps them working
indefinitely, same as it would for a real login.

ProtectedRoute now shows an inline message instead of redirecting to a
/login route that no longer exists, for whenever this runs without dev
tokens configured (i.e. a real production build with no login flow yet).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent a7124fc6
# Base URL of the stax_backend_api instance to talk to. Point this at the dev server while # Base URL of the stax_backend_api instance to talk to. Point this at the dev server while
# developing, and at prod for a production build. # developing, and at prod for a production build.
VITE_API_BASE_URL=http://144.76.210.145:8000 VITE_API_BASE_URL=http://144.76.210.145:8000
# Dev-only auto-login (see AuthContext.tsx) - only takes effect under `npm run dev`
# (import.meta.env.DEV), never in a production build, regardless of whether these are set.
# Real, DB-backed tokens for a dedicated dev-test-user row on the dev server, not forged -
# mint your own pair the same way if these ever expire/get revoked:
# PYTHONPATH=. python3 -c "from src.core.security import create_access_token, create_refresh_token; ..."
# (see stax_backend_api conversation history for the exact script that also inserts the
# matching refresh_tokens row - a bare create_refresh_token() call alone won't be accepted by
# /auth/refresh without that row existing).
VITE_DEV_ACCESS_TOKEN=
VITE_DEV_REFRESH_TOKEN=
import { Navigate, Route, Routes } from 'react-router-dom' import { Navigate, Route, Routes } from 'react-router-dom'
import { Login } from './pages/Login'
import { Library } from './pages/Library' import { Library } from './pages/Library'
import { Upload } from './pages/Upload' import { Upload } from './pages/Upload'
import { Discovery } from './pages/Discovery' import { Discovery } from './pages/Discovery'
...@@ -15,7 +14,6 @@ function protect(element: React.ReactElement) { ...@@ -15,7 +14,6 @@ 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 />)} />
......
import { apiFetch } from './client' import { apiFetch } from './client'
export interface TokenResponse {
access_token: string
refresh_token: string
}
export function requestCode(phoneNumber: string) {
return apiFetch<{ status: string; data: { phone_code_hash: string; is_registered: boolean } }>(
'/auth/request_code',
{ method: 'POST', json: { phone_number: phoneNumber }, auth: false },
)
}
export function login(phoneNumber: string, phoneCodeHash: string, code: string) {
return apiFetch<TokenResponse>('/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',
......
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom' import { Link, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
const NAV_ITEMS = [ const NAV_ITEMS = [
...@@ -13,12 +13,13 @@ const NAV_ITEMS = [ ...@@ -13,12 +13,13 @@ const NAV_ITEMS = [
export function Layout({ title, children }: { title: string; children: ReactNode }) { export function Layout({ title, children }: { title: string; children: ReactNode }) {
const { logout } = useAuth() const { logout } = useAuth()
const navigate = useNavigate()
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
// AuthContext.tsx), this just clears the session to test what a logged-out state looks like.
await logout() await logout()
navigate('/login') window.location.reload()
} }
return ( return (
......
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Navigate } 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()
if (!isAuthenticated) return <Navigate to="/login" replace /> if (!isAuthenticated) {
// No login flow exists in this app right now (dev auto-authenticates via
// VITE_DEV_ACCESS_TOKEN/VITE_DEV_REFRESH_TOKEN - see AuthContext.tsx). A production
// build without a real login page has no route to send an unauthenticated user to.
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 { createContext, useCallback, useContext, 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 { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client' import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client'
interface AuthContextValue { interface AuthContextValue {
isAuthenticated: boolean isAuthenticated: boolean
requestCode: (phoneNumber: string) => Promise<{ phoneCodeHash: string }>
login: (phoneNumber: string, phoneCodeHash: string, code: string) => Promise<void>
logout: () => Promise<void> logout: () => Promise<void>
} }
const AuthContext = createContext<AuthContextValue | null>(null) const AuthContext = createContext<AuthContextValue | null>(null)
// 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.
const DEV_ACCESS_TOKEN = import.meta.env.VITE_DEV_ACCESS_TOKEN as string | undefined
const DEV_REFRESH_TOKEN = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | undefined
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(() => Boolean(getAccessToken())) const [isAuthenticated, setIsAuthenticated] = useState(() => Boolean(getAccessToken()))
const requestCode = useCallback(async (phoneNumber: string) => { useEffect(() => {
const res = await authApi.requestCode(phoneNumber) if (import.meta.env.DEV && !getAccessToken() && DEV_ACCESS_TOKEN && DEV_REFRESH_TOKEN) {
return { phoneCodeHash: res.data.phone_code_hash } setTokens(DEV_ACCESS_TOKEN, DEV_REFRESH_TOKEN)
}, []) setIsAuthenticated(true)
}
const login = useCallback(async (phoneNumber: string, phoneCodeHash: string, code: string) => {
const tokens = await authApi.login(phoneNumber, phoneCodeHash, code)
setTokens(tokens.access_token, tokens.refresh_token)
setIsAuthenticated(true)
}, []) }, [])
const logout = useCallback(async () => { async function logout() {
const refreshToken = getRefreshToken() const refreshToken = getRefreshToken()
try { try {
if (refreshToken) await authApi.logout(refreshToken) if (refreshToken) await authApi.logout(refreshToken)
...@@ -33,13 +36,9 @@ export function AuthProvider({ children }: { children: ReactNode }) { ...@@ -33,13 +36,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
clearTokens() clearTokens()
setIsAuthenticated(false) setIsAuthenticated(false)
} }
}, []) }
return ( return <AuthContext.Provider value={{ isAuthenticated, logout }}>{children}</AuthContext.Provider>
<AuthContext.Provider value={{ isAuthenticated, requestCode, login, logout }}>
{children}
</AuthContext.Provider>
)
} }
export function useAuth(): AuthContextValue { export function useAuth(): AuthContextValue {
......
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { ApiError } from '../api/client'
type Step = 'phone' | 'code'
export function Login() {
const { requestCode, login } = useAuth()
const navigate = useNavigate()
const [step, setStep] = useState<Step>('phone')
const [phoneNumber, setPhoneNumber] = useState('')
const [phoneCodeHash, setPhoneCodeHash] = useState('')
const [code, setCode] = useState('')
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
async function handleRequestCode(e: React.FormEvent) {
e.preventDefault()
setError(null)
setBusy(true)
try {
const { phoneCodeHash } = await requestCode(phoneNumber)
setPhoneCodeHash(phoneCodeHash)
setStep('code')
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Could not request a code. Try again.')
} finally {
setBusy(false)
}
}
async function handleLogin(e: React.FormEvent) {
e.preventDefault()
setError(null)
setBusy(true)
try {
await login(phoneNumber, phoneCodeHash, code)
navigate('/library')
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Login failed. Check the code and try again.')
} finally {
setBusy(false)
}
}
return (
<div className="flex min-h-screen items-center justify-center bg-neutral-950 px-4">
<div className="w-full max-w-sm rounded-2xl border border-neutral-800 bg-neutral-900 p-8 shadow-xl">
<h1 className="mb-1 text-2xl font-semibold text-white">🎧 Stax</h1>
<p className="mb-6 text-sm text-neutral-400">Sign in with your Telegram account</p>
{step === 'phone' ? (
<form onSubmit={handleRequestCode} className="space-y-4">
<div>
<label className="mb-1 block text-xs uppercase tracking-wide text-neutral-500">
Phone number
</label>
<input
type="tel"
required
autoFocus
placeholder="+15550001234"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
className="w-full rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-white placeholder-neutral-500 outline-none focus:border-emerald-500"
/>
</div>
{error && <p className="text-sm text-red-400">{error}</p>}
<button
type="submit"
disabled={busy}
className="w-full rounded-lg bg-emerald-500 py-2 font-medium text-neutral-950 transition hover:bg-emerald-400 disabled:opacity-50"
>
{busy ? 'Sending code…' : 'Send code'}
</button>
</form>
) : (
<form onSubmit={handleLogin} className="space-y-4">
<div>
<label className="mb-1 block text-xs uppercase tracking-wide text-neutral-500">
Code sent to {phoneNumber}
</label>
<input
type="text"
required
autoFocus
inputMode="numeric"
placeholder="12345"
value={code}
onChange={(e) => setCode(e.target.value)}
className="w-full rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-white placeholder-neutral-500 outline-none focus:border-emerald-500"
/>
</div>
{error && <p className="text-sm text-red-400">{error}</p>}
<button
type="submit"
disabled={busy}
className="w-full rounded-lg bg-emerald-500 py-2 font-medium text-neutral-950 transition hover:bg-emerald-400 disabled:opacity-50"
>
{busy ? 'Signing in…' : 'Sign in'}
</button>
<button
type="button"
onClick={() => setStep('phone')}
className="w-full text-center text-sm text-neutral-500 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