This commit fixes 5 critical bugs found during code review: Bug #1 (CRITICAL): Missing API endpoints for election filtering - Added GET /api/elections/upcoming endpoint - Added GET /api/elections/completed endpoint - Both properly filter elections by date Bug #2 (HIGH): Auth context has_voted state inconsistency - Backend schemas now include has_voted in LoginResponse and RegisterResponse - Auth routes return actual has_voted value from database - Frontend context uses server response instead of hardcoding false - Frontend API client properly typed with has_voted field Bug #3 (HIGH): Transaction safety in vote submission - Simplified error handling in vote submission endpoints - Now only calls mark_as_voted() once at the end - Vote response includes voter_marked_voted flag to indicate success - Ensures consistency even if blockchain submission fails Bug #4 (MEDIUM): Vote status endpoint - Verified endpoint already exists at GET /api/votes/status - Tests confirm proper functionality Bug #5 (MEDIUM): Response format inconsistency - Previously fixed in commit e10a882 - Frontend now handles both array and wrapped object formats Added comprehensive test coverage: - 20+ backend API tests (tests/test_api_fixes.py) - 6+ auth context tests (frontend/__tests__/auth-context.test.tsx) - 8+ elections API tests (frontend/__tests__/elections-api.test.ts) - 10+ vote submission tests (frontend/__tests__/vote-submission.test.ts) All fixes ensure frontend and backend communicate consistently. 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com>
152 lines
4.0 KiB
TypeScript
152 lines
4.0 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, citizenId: 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,
|
|
has_voted: response.data.has_voted ?? false,
|
|
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, citizenId: string) => {
|
|
setIsLoading(true)
|
|
setError(null)
|
|
try {
|
|
const response = await authApi.register(email, password, firstName, lastName, citizenId)
|
|
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,
|
|
has_voted: response.data.has_voted ?? false,
|
|
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
|
|
}
|