feat: implement authentication flow with login, registration, and OAuth support
This commit is contained in:
42
src/App.tsx
42
src/App.tsx
@@ -1,9 +1,49 @@
|
||||
import { Routes, Route, Navigate } from 'react-router'
|
||||
import { ThemeProvider } from './components/ThemeProvider'
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext'
|
||||
import { LoginPage } from './pages/LoginPage'
|
||||
import { RegisterPage } from './pages/RegisterPage'
|
||||
import { AuthCallbackPage } from './pages/AuthCallbackPage'
|
||||
import { DashboardPage } from './pages/DashboardPage'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
|
||||
if (loading) {
|
||||
return <div className="min-h-screen flex items-center justify-center">Loading...</div>
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
|
||||
function AppRoutes() {
|
||||
const { user } = useAuth()
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={user ? <Navigate to="/" replace /> : <LoginPage />} />
|
||||
<Route path="/register" element={user ? <Navigate to="/" replace /> : <RegisterPage />} />
|
||||
<Route path="/auth/callback" element={<AuthCallbackPage />} />
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<DashboardPage />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
|
||||
<div>App</div>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
99
src/components/auth/LoginForm.tsx
Normal file
99
src/components/auth/LoginForm.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { useState } from 'react'
|
||||
import { useAuth } from '@/contexts/AuthContext'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { OAuthButtons } from './OAuthButtons'
|
||||
import { ApiError } from '@/lib/api'
|
||||
|
||||
export function LoginForm() {
|
||||
const { login } = useAuth()
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
password: '',
|
||||
})
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError('')
|
||||
|
||||
try {
|
||||
await login(formData)
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError('An unexpected error occurred')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[e.target.name]: e.target.value,
|
||||
}))
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-bold text-center">Sign in</CardTitle>
|
||||
<CardDescription className="text-center">
|
||||
Enter your email and password to sign in to your account
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
value={formData.email}
|
||||
onChange={handleChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
value={formData.password}
|
||||
onChange={handleChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-sm text-red-600 bg-red-50 p-3 rounded">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign In'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<OAuthButtons />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
120
src/components/auth/OAuthButtons.tsx
Normal file
120
src/components/auth/OAuthButtons.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { apiService } from '@/lib/api'
|
||||
|
||||
export function OAuthButtons() {
|
||||
const [providers, setProviders] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProviders = async () => {
|
||||
try {
|
||||
const response = await apiService.getOAuthProviders()
|
||||
setProviders(response.providers)
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch OAuth providers:', error)
|
||||
}
|
||||
}
|
||||
|
||||
fetchProviders()
|
||||
}, [])
|
||||
|
||||
const handleOAuthLogin = async (provider: string) => {
|
||||
setLoading(provider)
|
||||
try {
|
||||
const response = await apiService.getOAuthUrl(provider)
|
||||
|
||||
// Store state in sessionStorage for verification
|
||||
sessionStorage.setItem('oauth_state', response.state)
|
||||
|
||||
// Redirect to OAuth provider
|
||||
window.location.href = response.authorization_url
|
||||
} catch (error) {
|
||||
console.error(`${provider} OAuth failed:`, error)
|
||||
setLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const getProviderIcon = (provider: string) => {
|
||||
switch (provider) {
|
||||
case 'google':
|
||||
return (
|
||||
<svg className="w-5 h-5" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
case 'github':
|
||||
return (
|
||||
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const getProviderName = (provider: string) => {
|
||||
return provider.charAt(0).toUpperCase() + provider.slice(1)
|
||||
}
|
||||
|
||||
if (providers.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<Separator className="w-full" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white dark:bg-gray-900 px-2 text-gray-500 dark:text-gray-400">
|
||||
Or continue with
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3">
|
||||
{providers.map((provider) => (
|
||||
<Button
|
||||
key={provider}
|
||||
variant="outline"
|
||||
type="button"
|
||||
disabled={loading !== null}
|
||||
onClick={() => handleOAuthLogin(provider)}
|
||||
className="w-full"
|
||||
>
|
||||
{loading === provider ? (
|
||||
<div className="w-5 h-5 border-2 border-current border-t-transparent rounded-full animate-spin" />
|
||||
) : (
|
||||
getProviderIcon(provider)
|
||||
)}
|
||||
<span className="ml-2">
|
||||
{loading === provider
|
||||
? 'Connecting...'
|
||||
: `Continue with ${getProviderName(provider)}`
|
||||
}
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
144
src/components/auth/RegisterForm.tsx
Normal file
144
src/components/auth/RegisterForm.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { useState } from 'react'
|
||||
import { useAuth } from '@/contexts/AuthContext'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { OAuthButtons } from './OAuthButtons'
|
||||
import { ApiError } from '@/lib/api'
|
||||
|
||||
export function RegisterForm() {
|
||||
const { register } = useAuth()
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
name: '',
|
||||
})
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError('')
|
||||
|
||||
if (formData.password !== formData.confirmPassword) {
|
||||
setError('Passwords do not match')
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (formData.password.length < 8) {
|
||||
setError('Password must be at least 8 characters long')
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await register({
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
name: formData.name,
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError('An unexpected error occurred')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[e.target.name]: e.target.value,
|
||||
}))
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-bold text-center">Create account</CardTitle>
|
||||
<CardDescription className="text-center">
|
||||
Enter your information to create your account
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Full Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
value={formData.name}
|
||||
onChange={handleChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
value={formData.email}
|
||||
onChange={handleChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
value={formData.password}
|
||||
onChange={handleChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Confirm Password</Label>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
name="confirmPassword"
|
||||
type="password"
|
||||
required
|
||||
value={formData.confirmPassword}
|
||||
onChange={handleChange}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-sm text-red-600 bg-red-50 p-3 rounded">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Creating account...' : 'Create Account'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<OAuthButtons />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
74
src/contexts/AuthContext.tsx
Normal file
74
src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
|
||||
import { apiService } from '@/lib/api'
|
||||
import type { AuthContextType, User, LoginRequest, RegisterRequest } from '@/types/auth'
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null)
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext)
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider')
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: AuthProviderProps) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const initAuth = async () => {
|
||||
try {
|
||||
// Try to get user info using cookies
|
||||
const user = await apiService.getMe()
|
||||
setUser(user)
|
||||
} catch {
|
||||
// User is not authenticated - this is normal for logged out users
|
||||
}
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
initAuth()
|
||||
}, [])
|
||||
|
||||
const login = async (credentials: LoginRequest) => {
|
||||
try {
|
||||
const response = await apiService.login(credentials)
|
||||
setUser(response.user)
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const register = async (data: RegisterRequest) => {
|
||||
try {
|
||||
const response = await apiService.register(data)
|
||||
setUser(response.user)
|
||||
} catch (error) {
|
||||
console.error('Registration failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await apiService.logout()
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
const value: AuthContextType = {
|
||||
user,
|
||||
token: user ? 'cookie-based' : null,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
loading,
|
||||
setUser,
|
||||
}
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||
}
|
||||
209
src/lib/api.ts
Normal file
209
src/lib/api.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
import type { LoginRequest, RegisterRequest } from '@/types/auth'
|
||||
|
||||
const API_BASE_URL = 'http://localhost:8000'
|
||||
|
||||
class ApiError extends Error {
|
||||
public status: number
|
||||
public response?: unknown
|
||||
|
||||
constructor(message: string, status: number, response?: unknown) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
this.response = response
|
||||
}
|
||||
}
|
||||
|
||||
class ApiService {
|
||||
private refreshPromise: Promise<void> | null = null
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const url = `${API_BASE_URL}${endpoint}`
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers as Record<string, string>),
|
||||
}
|
||||
|
||||
const config: RequestInit = {
|
||||
...options,
|
||||
headers,
|
||||
credentials: 'include', // Always include cookies
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url, config)
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
try {
|
||||
await this.refreshToken()
|
||||
const retryResponse = await fetch(url, config)
|
||||
|
||||
if (!retryResponse.ok) {
|
||||
throw new ApiError(
|
||||
'Request failed after token refresh',
|
||||
retryResponse.status,
|
||||
await retryResponse.json().catch(() => null)
|
||||
)
|
||||
}
|
||||
|
||||
return await retryResponse.json()
|
||||
} catch (refreshError) {
|
||||
// Only redirect if we're not already on the login page to prevent infinite loops
|
||||
const currentPath = window.location.pathname
|
||||
if (currentPath !== '/login' && currentPath !== '/register') {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
throw refreshError
|
||||
}
|
||||
}
|
||||
|
||||
const errorData = await response.json().catch(() => null)
|
||||
throw new ApiError(
|
||||
errorData?.detail || 'Request failed',
|
||||
response.status,
|
||||
errorData
|
||||
)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error
|
||||
}
|
||||
throw new ApiError('Network error', 0)
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshToken(): Promise<void> {
|
||||
if (this.refreshPromise) {
|
||||
await this.refreshPromise
|
||||
return
|
||||
}
|
||||
|
||||
this.refreshPromise = this.performTokenRefresh()
|
||||
|
||||
try {
|
||||
await this.refreshPromise
|
||||
} finally {
|
||||
this.refreshPromise = null
|
||||
}
|
||||
}
|
||||
|
||||
private async performTokenRefresh(): Promise<void> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v1/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
credentials: 'include', // Send cookies with refresh token
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError('Token refresh failed', response.status)
|
||||
}
|
||||
|
||||
// Token is automatically set in cookies by the backend
|
||||
// No need to handle it manually
|
||||
}
|
||||
|
||||
async login(credentials: LoginRequest): Promise<{ user: User }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v1/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(credentials),
|
||||
credentials: 'include', // Important for cookies
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null)
|
||||
throw new ApiError(
|
||||
errorData?.detail || 'Login failed',
|
||||
response.status,
|
||||
errorData
|
||||
)
|
||||
}
|
||||
|
||||
const user = await response.json()
|
||||
|
||||
return { user }
|
||||
}
|
||||
|
||||
async register(userData: RegisterRequest): Promise<{ user: User }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v1/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(userData),
|
||||
credentials: 'include', // Important for cookies
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null)
|
||||
throw new ApiError(
|
||||
errorData?.detail || 'Registration failed',
|
||||
response.status,
|
||||
errorData
|
||||
)
|
||||
}
|
||||
|
||||
const user = await response.json()
|
||||
|
||||
return { user }
|
||||
}
|
||||
|
||||
async getMe(): Promise<User> {
|
||||
return this.request('/api/v1/auth/me')
|
||||
}
|
||||
|
||||
async logout() {
|
||||
try {
|
||||
await fetch(`${API_BASE_URL}/api/v1/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Logout request failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async getOAuthUrl(provider: string): Promise<{ authorization_url: string; state: string }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v1/auth/${provider}/authorize`, {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null)
|
||||
throw new ApiError(
|
||||
errorData?.detail || 'Failed to get OAuth URL',
|
||||
response.status,
|
||||
errorData
|
||||
)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
async getOAuthProviders(): Promise<{ providers: string[] }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v1/auth/providers`, {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError('Failed to get OAuth providers', response.status)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const apiService = new ApiService()
|
||||
export { ApiError }
|
||||
102
src/pages/AuthCallbackPage.tsx
Normal file
102
src/pages/AuthCallbackPage.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { useAuth } from '@/contexts/AuthContext'
|
||||
import { apiService } from '@/lib/api'
|
||||
|
||||
export function AuthCallbackPage() {
|
||||
const navigate = useNavigate()
|
||||
const { setUser } = useAuth()
|
||||
const [status, setStatus] = useState<'processing' | 'success' | 'error'>('processing')
|
||||
const [error, setError] = useState<string>('')
|
||||
|
||||
useEffect(() => {
|
||||
const handleOAuthCallback = async () => {
|
||||
try {
|
||||
// Get the code from URL parameters
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
const code = urlParams.get('code')
|
||||
|
||||
if (!code) {
|
||||
throw new Error('No authorization code received')
|
||||
}
|
||||
|
||||
console.log('Exchanging OAuth code for tokens...')
|
||||
|
||||
// Exchange the temporary code for proper auth cookies
|
||||
const response = await fetch('http://localhost:8000/api/v1/auth/exchange-oauth-token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ code }),
|
||||
credentials: 'include', // Important for setting cookies
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null)
|
||||
throw new Error(errorData?.detail || 'Token exchange failed')
|
||||
}
|
||||
|
||||
const result = await response.json()
|
||||
console.log('Token exchange successful:', result)
|
||||
|
||||
// Now get the user info
|
||||
const user = await apiService.getMe()
|
||||
console.log('User info retrieved:', user)
|
||||
|
||||
// Update auth context
|
||||
if (setUser) setUser(user)
|
||||
|
||||
setStatus('success')
|
||||
|
||||
// Redirect to dashboard after a short delay
|
||||
setTimeout(() => {
|
||||
navigate('/')
|
||||
}, 1000)
|
||||
|
||||
} catch (error) {
|
||||
console.error('OAuth callback failed:', error)
|
||||
setError(error instanceof Error ? error.message : 'Authentication failed')
|
||||
setStatus('error')
|
||||
|
||||
// Redirect to login after error
|
||||
setTimeout(() => {
|
||||
navigate('/login')
|
||||
}, 3000)
|
||||
}
|
||||
}
|
||||
|
||||
handleOAuthCallback()
|
||||
}, [navigate, setUser])
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="max-w-md w-full space-y-6 text-center">
|
||||
{status === 'processing' && (
|
||||
<div>
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
|
||||
<h2 className="mt-4 text-xl font-semibold">Completing sign in...</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400">Please wait while we set up your account.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === 'success' && (
|
||||
<div>
|
||||
<div className="text-green-600 text-4xl mb-4">✓</div>
|
||||
<h2 className="text-xl font-semibold text-green-600">Sign in successful!</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400">Redirecting to dashboard...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<div>
|
||||
<div className="text-red-600 text-4xl mb-4">✗</div>
|
||||
<h2 className="text-xl font-semibold text-red-600">Sign in failed</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-4">{error}</p>
|
||||
<p className="text-sm text-gray-500">Redirecting to login page...</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
38
src/pages/DashboardPage.tsx
Normal file
38
src/pages/DashboardPage.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { ModeToggle } from '../components/ModeToggle'
|
||||
|
||||
export function DashboardPage() {
|
||||
const { user, logout } = useAuth()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<nav className="shadow-sm border-b">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex justify-between h-16 items-center">
|
||||
<h1 className="text-xl font-semibold">Soundboard</h1>
|
||||
<div className="flex items-center space-x-4">
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">
|
||||
Welcome, {user?.name}
|
||||
</span>
|
||||
<ModeToggle />
|
||||
<button
|
||||
onClick={() => logout()}
|
||||
className="text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<div className="border-4 border-dashed border-gray-200 dark:border-gray-700 rounded-lg h-96 flex items-center justify-center">
|
||||
<p className="text-gray-500 dark:text-gray-400">Dashboard content coming soon...</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
24
src/pages/LoginPage.tsx
Normal file
24
src/pages/LoginPage.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Link } from 'react-router'
|
||||
import { LoginForm } from '@/components/auth/LoginForm'
|
||||
|
||||
export function LoginPage() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="w-full max-w-md space-y-6">
|
||||
<LoginForm />
|
||||
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Don't have an account?{' '}
|
||||
<Link
|
||||
to="/register"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400"
|
||||
>
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
24
src/pages/RegisterPage.tsx
Normal file
24
src/pages/RegisterPage.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Link } from 'react-router'
|
||||
import { RegisterForm } from '@/components/auth/RegisterForm'
|
||||
|
||||
export function RegisterPage() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="w-full max-w-md space-y-6">
|
||||
<RegisterForm />
|
||||
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Already have an account?{' '}
|
||||
<Link
|
||||
to="/login"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
49
src/types/auth.ts
Normal file
49
src/types/auth.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
export interface User {
|
||||
id: number
|
||||
email: string
|
||||
name: string
|
||||
picture?: string
|
||||
role: string
|
||||
credits: number
|
||||
is_active: boolean
|
||||
plan: {
|
||||
id: number
|
||||
name: string
|
||||
max_credits: number
|
||||
features: string[]
|
||||
}
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface TokenResponse {
|
||||
access_token: string
|
||||
token_type: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
user: User
|
||||
token: TokenResponse
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
email: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface RegisterRequest {
|
||||
email: string
|
||||
password: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface AuthContextType {
|
||||
user: User | null
|
||||
token: string | null
|
||||
login: (credentials: LoginRequest) => Promise<void>
|
||||
register: (data: RegisterRequest) => Promise<void>
|
||||
logout: () => Promise<void>
|
||||
loading: boolean
|
||||
setUser?: (user: User | null) => void
|
||||
}
|
||||
Reference in New Issue
Block a user