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

@@ -4,6 +4,7 @@
"": {
"name": "frontend",
"dependencies": {
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-slot": "^1.2.3",
"@tailwindcss/vite": "^4.1.11",
"class-variance-authority": "^0.7.1",
@@ -11,7 +12,8 @@
"lucide-react": "^0.525.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.6.3",
"react-router-dom": "^7.6.3",
"sidebar": "^1.0.2",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.11",
},
@@ -21,6 +23,7 @@
"@types/node": "^24.0.7",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@types/react-router-dom": "^5.3.3",
"@vitejs/plugin-react": "^4.5.2",
"eslint": "^9.29.0",
"eslint-plugin-react-hooks": "^5.2.0",
@@ -169,6 +172,10 @@
"@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
"@radix-ui/react-label": ["@radix-ui/react-label@2.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ=="],
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
"@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.19", "", {}, "sha512-3FL3mnMbPu0muGOCaKAhhFEYmqv9eTfPSJRJmANrCwtgK8VuxpsZDGK+m0LYAGoyO8+0j5uRe4PeyPDK1yA/hA=="],
@@ -255,6 +262,8 @@
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/history": ["@types/history@4.7.11", "", {}, "sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA=="],
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
"@types/node": ["@types/node@24.0.7", "", { "dependencies": { "undici-types": "~7.8.0" } }, "sha512-YIEUUr4yf8q8oQoXPpSlnvKNVKDQlPMWrmOcgzoduo7kvA2UF0/BwJ/eMKFTiTtkNL17I0M6Xe2tvwFU7be6iw=="],
@@ -263,6 +272,10 @@
"@types/react-dom": ["@types/react-dom@19.1.6", "", { "peerDependencies": { "@types/react": "^19.0.0" } }, "sha512-4hOiT/dwO8Ko0gV1m/TJZYk3y0KBnY9vzDh7W+DH17b2HFSOGgdj33dhihPeuy3l0q23+4e+hoXHV6hCC4dCXw=="],
"@types/react-router": ["@types/react-router@5.1.20", "", { "dependencies": { "@types/history": "^4.7.11", "@types/react": "*" } }, "sha512-jGjmu/ZqS7FjSH6owMcD5qpq19+1RS9DeVRqfl1FeBMxTDQAGwlMWOcs52NDoXaNKyG3d1cYQFMs9rCrb88o9Q=="],
"@types/react-router-dom": ["@types/react-router-dom@5.3.3", "", { "dependencies": { "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router": "*" } }, "sha512-kpqnYK4wcdm5UaWI3fLcELopqLrHgLqNsdpHauzlQktfkHL3npOSwtj1Uz9oKBAzs7lFtVkV8j83voAz2D8fhw=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.35.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.35.0", "@typescript-eslint/type-utils": "8.35.0", "@typescript-eslint/utils": "8.35.0", "@typescript-eslint/visitor-keys": "8.35.0", "graphemer": "^1.4.0", "ignore": "^7.0.0", "natural-compare": "^1.4.0", "ts-api-utils": "^2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.35.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <5.9.0" } }, "sha512-ijItUYaiWuce0N1SoSMrEd0b6b6lYkYt99pqCPfybd+HKVXtEvYhICfLdwp42MhiI5mp0oq7PKEL+g1cNiz/Eg=="],
"@typescript-eslint/parser": ["@typescript-eslint/parser@8.35.0", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.35.0", "@typescript-eslint/types": "8.35.0", "@typescript-eslint/typescript-estree": "8.35.0", "@typescript-eslint/visitor-keys": "8.35.0", "debug": "^4.3.4" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <5.9.0" } }, "sha512-6sMvZePQrnZH2/cJkwRpkT7DxoAWh+g6+GFRK6bV3YQo7ogi3SX5rgF6099r5Q53Ma5qeT7LGmOmuIutF4t3lA=="],
@@ -297,6 +310,8 @@
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"bootstrap": ["bootstrap@3.4.1", "", {}, "sha512-yN5oZVmRCwe5aKwzRj6736nSmKDX7pLYwsXiCj/EYmo16hODaBiT4En5btW/jhBF/seV+XMx3aYwukYC3A49DA=="],
"brace-expansion": ["brace-expansion@1.1.12", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg=="],
"braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
@@ -525,6 +540,8 @@
"react-router": ["react-router@7.6.3", "", { "dependencies": { "cookie": "^1.0.1", "set-cookie-parser": "^2.6.0" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" }, "optionalPeers": ["react-dom"] }, "sha512-zf45LZp5skDC6I3jDLXQUu0u26jtuP4lEGbc7BbdyxenBN1vJSTA18czM2D+h5qyMBuMrD+9uB+mU37HIoKGRA=="],
"react-router-dom": ["react-router-dom@7.6.3", "", { "dependencies": { "react-router": "7.6.3" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" } }, "sha512-DiWJm9qdUAmiJrVWaeJdu4TKu13+iB/8IEi0EW/XgaHCjW/vWGrwzup0GVvaMteuZjKnh5bEvJP/K0MDnzawHw=="],
"resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
"reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],
@@ -543,6 +560,8 @@
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"sidebar": ["sidebar@1.0.2", "", { "dependencies": { "bootstrap": "^3.3.7" } }, "sha512-JvzZ6OLsvdVK0jo6jTHSfTApuHVHeAm3++UnAoHRpoVeTcW1nC7Xm8LRbRvtGXVSJsdeM6qfv5pgDZUXemgkDw=="],
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],

View File

@@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-slot": "^1.2.3",
"@tailwindcss/vite": "^4.1.11",
"class-variance-authority": "^0.7.1",
@@ -17,7 +18,8 @@
"lucide-react": "^0.525.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.6.3",
"react-router-dom": "^7.6.3",
"sidebar": "^1.0.2",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.11"
},
@@ -27,6 +29,7 @@
"@types/node": "^24.0.7",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@types/react-router-dom": "^5.3.3",
"@vitejs/plugin-react": "^4.5.2",
"eslint": "^9.29.0",
"eslint-plugin-react-hooks": "^5.2.0",

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>,
)

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 }