CIA/e-voting-system/frontend/lib/auth-context.tsx
Alexis Bruneteau 546785ef67 feat: Integrate backend API with frontend - Authentication & Elections
Core Integration:
- Create API client with TypeScript types for all endpoints
- Implement authentication context provider for user state management
- Add protected route component for dashboard access control
- Connect login/register pages to backend authentication endpoints
- Implement user session persistence with localStorage tokens

Authentication:
- Login page now connects to /api/auth/login endpoint
- Register page connects to /api/auth/register with validation
- Password strength requirements (min 8 chars)
- Form validation and error handling
- Automatic redirect to dashboard on successful auth
- Logout functionality with session cleanup

Protected Routes:
- Dashboard pages require authentication
- Non-authenticated users redirected to login
- Loading spinner during auth verification
- User name displayed in dashboard header
- Proper session management

Election/Vote APIs:
- Dashboard fetches active elections from /api/elections/active
- Display real election data with candidates count
- Handle loading and error states
- Skeleton loaders for better UX

Type Safety:
- Full TypeScript interfaces for all API responses
- Proper error handling with try-catch blocks
- API response types: AuthToken, VoterProfile, Election, Candidate, Vote, VoteHistory

Environment:
- API URL configurable via NEXT_PUBLIC_API_URL env variable
- Default to http://localhost:8000 for local development

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 17:15:34 +01:00

150 lines
3.8 KiB
TypeScript

/**
* Authentication Context
* Manages user authentication state globally
*/
"use client"
import React, { createContext, useContext, useState, useEffect, ReactNode } from "react"
import { authApi, getAuthToken, setAuthToken, clearAuthToken, VoterProfile } from "./api"
interface AuthContextType {
user: VoterProfile | null
isLoading: boolean
isAuthenticated: boolean
error: string | null
login: (email: string, password: string) => Promise<void>
register: (email: string, password: string, firstName: string, lastName: string) => Promise<void>
logout: () => void
refreshProfile: () => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<VoterProfile | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// Check if user is already logged in on mount
useEffect(() => {
const checkAuth = async () => {
const token = getAuthToken()
if (token) {
try {
const response = await authApi.getProfile()
if (response.data) {
setUser(response.data)
} else {
clearAuthToken()
}
} catch (err) {
clearAuthToken()
}
}
setIsLoading(false)
}
checkAuth()
}, [])
const login = async (email: string, password: string) => {
setIsLoading(true)
setError(null)
try {
const response = await authApi.login(email, password)
if (response.error) {
throw new Error(response.error)
}
if (response.data) {
setAuthToken(response.data.access_token)
setUser({
id: response.data.id,
email: response.data.email,
first_name: response.data.first_name,
last_name: response.data.last_name,
created_at: new Date().toISOString(),
})
}
} catch (err) {
const message = err instanceof Error ? err.message : "Login failed"
setError(message)
throw err
} finally {
setIsLoading(false)
}
}
const register = async (email: string, password: string, firstName: string, lastName: string) => {
setIsLoading(true)
setError(null)
try {
const response = await authApi.register(email, password, firstName, lastName)
if (response.error) {
throw new Error(response.error)
}
if (response.data) {
setAuthToken(response.data.access_token)
setUser({
id: response.data.id,
email: response.data.email,
first_name: response.data.first_name,
last_name: response.data.last_name,
created_at: new Date().toISOString(),
})
}
} catch (err) {
const message = err instanceof Error ? err.message : "Registration failed"
setError(message)
throw err
} finally {
setIsLoading(false)
}
}
const logout = () => {
authApi.logout()
setUser(null)
setError(null)
}
const refreshProfile = async () => {
try {
const response = await authApi.getProfile()
if (response.data) {
setUser(response.data)
} else {
clearAuthToken()
setUser(null)
}
} catch (err) {
clearAuthToken()
setUser(null)
}
}
const value: AuthContextType = {
user,
isLoading,
isAuthenticated: user !== null,
error,
login,
register,
logout,
refreshProfile,
}
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
/**
* Hook to use authentication context
*/
export function useAuth() {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider")
}
return context
}