auth, login + register

This commit is contained in:
JSC
2025-06-28 19:20:15 +02:00
parent e23e4bca2e
commit 984334d948
13 changed files with 929 additions and 7 deletions

View File

@@ -1,6 +1,30 @@
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { AuthProvider } from '@/contexts/AuthContext'
import { LoginPage } from '@/pages/LoginPage'
import { RegisterPage } from '@/pages/RegisterPage'
import { DashboardPage } from '@/pages/DashboardPage'
import { ProtectedRoute } from '@/components/ProtectedRoute'
function App() {
return (
<div>App</div>
<AuthProvider>
<Router>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<DashboardPage />
</ProtectedRoute>
}
/>
<Route path="/" element={<Navigate to="/dashboard" replace />} />
<Route path="*" element={<Navigate to="/dashboard" replace />} />
</Routes>
</Router>
</AuthProvider>
)
}

View File

@@ -0,0 +1,51 @@
import { type ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '@/contexts/AuthContext'
interface ProtectedRouteProps {
children: ReactNode
requireAdmin?: boolean
}
export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) {
const { user, loading } = useAuth()
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto"></div>
<p className="mt-2 text-gray-600">Loading...</p>
</div>
</div>
)
}
if (!user) {
return <Navigate to="/login" replace />
}
if (requireAdmin && user.role !== 'admin') {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<h1 className="text-2xl font-bold text-gray-900 mb-2">Access Denied</h1>
<p className="text-gray-600">You don't have permission to access this page.</p>
</div>
</div>
)
}
if (!user.is_active) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<h1 className="text-2xl font-bold text-gray-900 mb-2">Account Disabled</h1>
<p className="text-gray-600">Your account has been disabled. Please contact support.</p>
</div>
</div>
)
}
return <>{children}</>
}

View File

@@ -0,0 +1,72 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@@ -0,0 +1,79 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import { authService, type User } from '@/services/auth'
interface AuthContextType {
user: User | null
loading: boolean
login: (email: string, password: string) => Promise<void>
register: (email: string, password: string, name: string) => Promise<void>
logout: () => Promise<void>
refreshUser: () => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
const refreshUser = async () => {
try {
const currentUser = await authService.getCurrentUser()
setUser(currentUser)
} catch (error) {
setUser(null)
}
}
useEffect(() => {
const initAuth = async () => {
await refreshUser()
setLoading(false)
}
initAuth()
}, [])
// Handle OAuth redirect - only run once when page loads
useEffect(() => {
// If we land on dashboard without user data, try to refresh once
// This handles OAuth redirects
if (window.location.pathname === '/dashboard' && !user && !loading) {
refreshUser()
}
}, [loading]) // Only depend on loading state
const login = async (email: string, password: string) => {
const userData = await authService.login(email, password)
setUser(userData)
}
const register = async (email: string, password: string, name: string) => {
const userData = await authService.register(email, password, name)
setUser(userData)
}
const logout = async () => {
await authService.logout()
setUser(null)
}
const value = {
user,
loading,
login,
register,
logout,
refreshUser,
}
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth() {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}

View File

@@ -1,10 +1,7 @@
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import { BrowserRouter } from "react-router";
createRoot(document.getElementById('root')!).render(
<BrowserRouter>
<App />
</BrowserRouter>,
<App />
)

143
src/pages/DashboardPage.tsx Normal file
View File

@@ -0,0 +1,143 @@
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useAuth } from '@/contexts/AuthContext'
import { useNavigate } from 'react-router-dom'
export function DashboardPage() {
const { user, logout } = useAuth()
const navigate = useNavigate()
const handleLogout = async () => {
try {
await logout()
navigate('/login')
} catch (error) {
console.error('Logout failed:', error)
}
}
if (!user) return null
return (
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-6">
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<Button onClick={handleLogout} variant="outline">
Sign out
</Button>
</div>
</div>
</header>
<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="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{/* User Profile Card */}
<Card>
<CardHeader>
<CardTitle>Profile Information</CardTitle>
<CardDescription>Your account details</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<div className="flex items-center space-x-2">
{user.picture && (
<img
src={user.picture}
alt="Profile"
className="w-8 h-8 rounded-full"
/>
)}
<div>
<p className="font-medium">{user.name}</p>
<p className="text-sm text-gray-600">{user.email}</p>
</div>
</div>
<div className="pt-2">
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
user.role === 'admin'
? 'bg-purple-100 text-purple-800'
: 'bg-green-100 text-green-800'
}`}>
{user.role}
</span>
{user.is_active && (
<span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
Active
</span>
)}
</div>
</CardContent>
</Card>
{/* Authentication Methods Card */}
<Card>
<CardHeader>
<CardTitle>Authentication Methods</CardTitle>
<CardDescription>How you can sign in</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{user.providers.map((provider) => (
<div key={provider} className="flex items-center justify-between">
<span className="text-sm font-medium capitalize">{provider}</span>
<span className="text-xs text-green-600">Connected</span>
</div>
))}
</div>
</CardContent>
</Card>
{/* Account Status Card */}
<Card>
<CardHeader>
<CardTitle>Account Status</CardTitle>
<CardDescription>Current account information</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<div className="flex justify-between">
<span className="text-sm">Status:</span>
<span className={`text-sm font-medium ${
user.is_active ? 'text-green-600' : 'text-red-600'
}`}>
{user.is_active ? 'Active' : 'Disabled'}
</span>
</div>
<div className="flex justify-between">
<span className="text-sm">Role:</span>
<span className="text-sm font-medium">{user.role}</span>
</div>
<div className="flex justify-between">
<span className="text-sm">User ID:</span>
<span className="text-sm font-mono">{user.id}</span>
</div>
</CardContent>
</Card>
</div>
{/* Admin Section */}
{user.role === 'admin' && (
<div className="mt-8">
<Card>
<CardHeader>
<CardTitle>Admin Panel</CardTitle>
<CardDescription>Administrative functions</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-gray-600 mb-4">
You have administrator privileges. You can manage users and system settings.
</p>
<div className="space-x-2">
<Button size="sm">Manage Users</Button>
<Button size="sm" variant="outline">System Settings</Button>
</div>
</CardContent>
</Card>
</div>
)}
</div>
</main>
</div>
)
}

158
src/pages/LoginPage.tsx Normal file
View File

@@ -0,0 +1,158 @@
import { useState, useEffect } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
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 { useAuth } from '@/contexts/AuthContext'
import { authService } from '@/services/auth'
export function LoginPage() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [oauthProviders, setOauthProviders] = useState<Record<string, { name: string; display_name: string }>>({})
const { login, user } = useAuth()
const navigate = useNavigate()
const [searchParams] = useSearchParams()
// Check for OAuth error in URL params
useEffect(() => {
const errorParam = searchParams.get('error')
if (errorParam) {
if (errorParam === 'oauth_failed') {
setError('OAuth authentication failed. Please try again.')
} else {
setError(`Authentication error: ${errorParam}`)
}
}
}, [searchParams])
// Redirect if already logged in
useEffect(() => {
if (user) {
navigate('/')
}
}, [user, navigate])
// Load OAuth providers
useEffect(() => {
const loadProviders = async () => {
try {
const providers = await authService.getOAuthProviders()
setOauthProviders(providers)
} catch (error) {
console.error('Failed to load OAuth providers:', error)
}
}
loadProviders()
}, [])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
setError('')
try {
await login(email, password)
navigate('/')
} catch (error) {
setError(error instanceof Error ? error.message : 'Login failed')
} finally {
setLoading(false)
}
}
const handleOAuthLogin = (provider: string) => {
window.location.href = authService.getOAuthLoginUrl(provider)
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<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">
{error && (
<div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-md text-sm">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
disabled={loading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
disabled={loading}
/>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</Button>
</form>
{Object.keys(oauthProviders).length > 0 && (
<>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">Or continue with</span>
</div>
</div>
<div className="space-y-2">
{Object.entries(oauthProviders).map(([key, provider]) => (
<Button
key={key}
variant="outline"
className="w-full"
onClick={() => handleOAuthLogin(key)}
disabled={loading}
>
Sign in with {provider.display_name}
</Button>
))}
</div>
</>
)}
<div className="text-center text-sm">
Don't have an account?{' '}
<Link to="/register" className="font-medium text-primary hover:underline">
Sign up
</Link>
</div>
</CardContent>
</Card>
</div>
)
}

200
src/pages/RegisterPage.tsx Normal file
View File

@@ -0,0 +1,200 @@
import { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
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 { useAuth } from '@/contexts/AuthContext'
import { authService } from '@/services/auth'
export function RegisterPage() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
confirmPassword: '',
})
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [oauthProviders, setOauthProviders] = useState<Record<string, { name: string; display_name: string }>>({})
const { register, user } = useAuth()
const navigate = useNavigate()
// Redirect if already logged in
useEffect(() => {
if (user) {
navigate('/')
}
}, [user, navigate])
// Load OAuth providers
useEffect(() => {
const loadProviders = async () => {
try {
const providers = await authService.getOAuthProviders()
setOauthProviders(providers)
} catch (error) {
console.error('Failed to load OAuth providers:', error)
}
}
loadProviders()
}, [])
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target
setFormData(prev => ({
...prev,
[name]: value
}))
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
setError('')
// Validation
if (formData.password !== formData.confirmPassword) {
setError('Passwords do not match')
setLoading(false)
return
}
if (formData.password.length < 6) {
setError('Password must be at least 6 characters long')
setLoading(false)
return
}
try {
await register(formData.email, formData.password, formData.name)
navigate('/')
} catch (error) {
setError(error instanceof Error ? error.message : 'Registration failed')
} finally {
setLoading(false)
}
}
const handleOAuthLogin = (provider: string) => {
window.location.href = authService.getOAuthLoginUrl(provider)
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<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">
{error && (
<div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-md text-sm">
{error}
</div>
)}
<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"
placeholder="Enter your full name"
value={formData.name}
onChange={handleInputChange}
required
disabled={loading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
name="email"
type="email"
placeholder="Enter your email"
value={formData.email}
onChange={handleInputChange}
required
disabled={loading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
name="password"
type="password"
placeholder="Create a password"
value={formData.password}
onChange={handleInputChange}
required
disabled={loading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirm Password</Label>
<Input
id="confirmPassword"
name="confirmPassword"
type="password"
placeholder="Confirm your password"
value={formData.confirmPassword}
onChange={handleInputChange}
required
disabled={loading}
/>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'Creating account...' : 'Create account'}
</Button>
</form>
{Object.keys(oauthProviders).length > 0 && (
<>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">Or continue with</span>
</div>
</div>
<div className="space-y-2">
{Object.entries(oauthProviders).map(([key, provider]) => (
<Button
key={key}
variant="outline"
className="w-full"
onClick={() => handleOAuthLogin(key)}
disabled={loading}
>
Sign up with {provider.display_name}
</Button>
))}
</div>
</>
)}
<div className="text-center text-sm">
Already have an account?{' '}
<Link to="/login" className="font-medium text-primary hover:underline">
Sign in
</Link>
</div>
</CardContent>
</Card>
</div>
)
}

127
src/services/auth.ts Normal file
View File

@@ -0,0 +1,127 @@
interface User {
id: string
email: string
name: string
picture?: string
role: string
is_active: boolean
provider: string
providers: string[]
}
interface AuthResponse {
message: string
user: User
}
interface ErrorResponse {
error: string
}
const API_BASE = 'http://localhost:5000/api'
class AuthService {
async register(email: string, password: string, name: string): Promise<User> {
const response = await fetch(`${API_BASE}/auth/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ email, password, name }),
})
const data = await response.json()
if (!response.ok) {
throw new Error((data as ErrorResponse).error || 'Registration failed')
}
return (data as AuthResponse).user
}
async login(email: string, password: string): Promise<User> {
const response = await fetch(`${API_BASE}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ email, password }),
})
const data = await response.json()
if (!response.ok) {
throw new Error((data as ErrorResponse).error || 'Login failed')
}
return (data as AuthResponse).user
}
async logout(): Promise<void> {
const response = await fetch(`${API_BASE}/auth/logout`, {
credentials: 'include',
})
if (!response.ok) {
throw new Error('Logout failed')
}
}
async getCurrentUser(): Promise<User | null> {
try {
const response = await fetch(`${API_BASE}/auth/me`, {
credentials: 'include',
})
if (!response.ok) {
return null
}
const data = await response.json()
return data.user
} catch (error) {
console.error('getCurrentUser error:', error)
return null
}
}
async getOAuthProviders(): Promise<Record<string, { name: string; display_name: string }>> {
try {
const response = await fetch(`${API_BASE}/auth/providers`)
if (!response.ok) {
throw new Error('Failed to get OAuth providers')
}
const data = await response.json()
return data.providers
} catch (error) {
console.warn('Backend not available, using fallback OAuth providers')
// Fallback OAuth providers when backend is not running
return {
google: { name: 'google', display_name: 'Google' },
github: { name: 'github', display_name: 'GitHub' }
}
}
}
getOAuthLoginUrl(provider: string): string {
return `${API_BASE}/auth/login/${provider}`
}
async refreshToken(): Promise<void> {
const response = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
credentials: 'include',
})
if (!response.ok) {
throw new Error('Token refresh failed')
}
}
}
export const authService = new AuthService()
export type { User }