diff --git a/bun.lock b/bun.lock index 3a5abfb..11f2ae1 100644 --- a/bun.lock +++ b/bun.lock @@ -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=="], diff --git a/package.json b/package.json index dc7a13c..fd8a086 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/App.tsx b/src/App.tsx index 9b70586..6c4de99 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 ( -
App
+ + + + } /> + } /> + + + + } + /> + } /> + } /> + + + ) } diff --git a/src/components/ProtectedRoute.tsx b/src/components/ProtectedRoute.tsx new file mode 100644 index 0000000..63212d6 --- /dev/null +++ b/src/components/ProtectedRoute.tsx @@ -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 ( +
+
+
+

Loading...

+
+
+ ) + } + + if (!user) { + return + } + + if (requireAdmin && user.role !== 'admin') { + return ( +
+
+

Access Denied

+

You don't have permission to access this page.

+
+
+ ) + } + + if (!user.is_active) { + return ( +
+
+

Account Disabled

+

Your account has been disabled. Please contact support.

+
+
+ ) + } + + return <>{children} +} \ No newline at end of file diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx new file mode 100644 index 0000000..7991420 --- /dev/null +++ b/src/components/ui/card.tsx @@ -0,0 +1,72 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardFooter.displayName = "CardFooter" + +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } \ No newline at end of file diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx new file mode 100644 index 0000000..30191ec --- /dev/null +++ b/src/components/ui/input.tsx @@ -0,0 +1,25 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +export interface InputProps + extends React.InputHTMLAttributes {} + +const Input = React.forwardRef( + ({ className, type, ...props }, ref) => { + return ( + + ) + } +) +Input.displayName = "Input" + +export { Input } \ No newline at end of file diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsx new file mode 100644 index 0000000..a7cafcd --- /dev/null +++ b/src/components/ui/label.tsx @@ -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, + React.ComponentPropsWithoutRef & + VariantProps +>(({ className, ...props }, ref) => ( + +)) +Label.displayName = LabelPrimitive.Root.displayName + +export { Label } \ No newline at end of file diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx new file mode 100644 index 0000000..28e1f2e --- /dev/null +++ b/src/contexts/AuthContext.tsx @@ -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 + register: (email: string, password: string, name: string) => Promise + logout: () => Promise + refreshUser: () => Promise +} + +const AuthContext = createContext(undefined) + +export function AuthProvider({ children }: { children: ReactNode }) { + const [user, setUser] = useState(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 {children} +} + +export function useAuth() { + const context = useContext(AuthContext) + if (context === undefined) { + throw new Error('useAuth must be used within an AuthProvider') + } + return context +} \ No newline at end of file diff --git a/src/main.tsx b/src/main.tsx index 67c0b7e..a757447 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -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( - - - , + ) diff --git a/src/pages/DashboardPage.tsx b/src/pages/DashboardPage.tsx new file mode 100644 index 0000000..53838e3 --- /dev/null +++ b/src/pages/DashboardPage.tsx @@ -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 ( +
+
+
+
+

Dashboard

+ +
+
+
+ +
+
+
+ {/* User Profile Card */} + + + Profile Information + Your account details + + +
+ {user.picture && ( + Profile + )} +
+

{user.name}

+

{user.email}

+
+
+
+ + {user.role} + + {user.is_active && ( + + Active + + )} +
+
+
+ + {/* Authentication Methods Card */} + + + Authentication Methods + How you can sign in + + +
+ {user.providers.map((provider) => ( +
+ {provider} + Connected +
+ ))} +
+
+
+ + {/* Account Status Card */} + + + Account Status + Current account information + + +
+ Status: + + {user.is_active ? 'Active' : 'Disabled'} + +
+
+ Role: + {user.role} +
+
+ User ID: + {user.id} +
+
+
+
+ + {/* Admin Section */} + {user.role === 'admin' && ( +
+ + + Admin Panel + Administrative functions + + +

+ You have administrator privileges. You can manage users and system settings. +

+
+ + +
+
+
+
+ )} +
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/LoginPage.tsx b/src/pages/LoginPage.tsx new file mode 100644 index 0000000..d1d23b1 --- /dev/null +++ b/src/pages/LoginPage.tsx @@ -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>({}) + + 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 ( +
+ + + Sign in + + Enter your email and password to sign in to your account + + + + {error && ( +
+ {error} +
+ )} + +
+
+ + setEmail(e.target.value)} + required + disabled={loading} + /> +
+ +
+ + setPassword(e.target.value)} + required + disabled={loading} + /> +
+ + +
+ + {Object.keys(oauthProviders).length > 0 && ( + <> +
+
+ +
+
+ Or continue with +
+
+ +
+ {Object.entries(oauthProviders).map(([key, provider]) => ( + + ))} +
+ + )} + +
+ Don't have an account?{' '} + + Sign up + +
+
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/RegisterPage.tsx b/src/pages/RegisterPage.tsx new file mode 100644 index 0000000..7be6cd4 --- /dev/null +++ b/src/pages/RegisterPage.tsx @@ -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>({}) + + 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) => { + 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 ( +
+ + + Create account + + Enter your information to create your account + + + + {error && ( +
+ {error} +
+ )} + +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ + +
+ + {Object.keys(oauthProviders).length > 0 && ( + <> +
+
+ +
+
+ Or continue with +
+
+ +
+ {Object.entries(oauthProviders).map(([key, provider]) => ( + + ))} +
+ + )} + +
+ Already have an account?{' '} + + Sign in + +
+
+
+
+ ) +} \ No newline at end of file diff --git a/src/services/auth.ts b/src/services/auth.ts new file mode 100644 index 0000000..916ad15 --- /dev/null +++ b/src/services/auth.ts @@ -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 { + 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 { + 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 { + const response = await fetch(`${API_BASE}/auth/logout`, { + credentials: 'include', + }) + + if (!response.ok) { + throw new Error('Logout failed') + } + } + + async getCurrentUser(): Promise { + 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> { + 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 { + 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 } \ No newline at end of file