29 Commits

Author SHA1 Message Date
Alexis Bruneteau
b4c5c97523 refactor: Comprehensive code cleanup and optimization
Major improvements:
- Deleted 80+ unused markdown files from .claude/ directory (saves disk space)
- Removed 342MB .backups/ directory with old frontend code
- Cleaned Python cache files (__pycache__ and .pyc)
- Fixed critical bugs in votes.py:
  - Removed duplicate candidate_id field assignment (line 465)
  - Removed duplicate datetime import (line 804)
- Removed commented code from crypto-client.ts (23 lines of dead code)
- Moved root-level test scripts to proper directories:
  - test_blockchain.py → tests/
  - test_blockchain_election.py → tests/
  - fix_elgamal_keys.py → backend/scripts/
  - restore_data.py → backend/scripts/
- Cleaned unused imports:
  - Removed unused RSA/padding imports from encryption.py
  - Removed unused asdict import from blockchain.py
- Optimized database queries:
  - Fixed N+1 query issue in get_voter_history() using eager loading
  - Added joinedload for election and candidate relationships
- Removed unused validation schemas:
  - Removed profileUpdateSchema (no profile endpoints exist)
  - Removed passwordChangeSchema (no password change endpoint)
- Updated .gitignore with comprehensive rules for Node.js artifacts and backups

Code quality improvements following DRY and KISS principles:
- Simplified complex functions
- Reduced code duplication
- Improved performance (eliminated N+1 queries)
- Enhanced maintainability

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 19:57:13 +01:00
E-Voting Developer
3efdabdbbd fix: Implement vote check endpoint in frontend API proxy
- Created `/frontend/app/api/votes/check/route.ts` to handle GET requests for checking if a user has voted in a specific election.
- Added error handling for unauthorized access and missing election ID.
- Forwarded requests to the backend API and returned appropriate responses.
- Updated `/frontend/app/api/votes/history/route.ts` to fetch user's voting history with error handling.
- Ensured both endpoints utilize the authorization token for secure access.
2025-11-10 02:56:47 +01:00
E-Voting Developer
dfdf159198 fix: ElGamal encryption, vote deduplication, and frontend data validation
- Fixed ElGamal class instantiation in votes.py (ElGamalEncryption instead of ElGamal)
- Fixed public key serialization in admin.py (use public_key_bytes property)
- Implemented database migration with SQL-based key generation
- Added vote deduplication endpoint: GET /api/votes/check
- Protected all array accesses with type validation in frontend
- Fixed vote parameter type handling (string to number conversion)
- Removed all debug console logs for production
- Created missing dynamic route for vote history details

Fixes:
- JavaScript error: "can't access property length, e is undefined"
- Vote deduplication not preventing form display
- Frontend data validation issues
- Missing dynamic routes
2025-11-08 00:05:19 +01:00
Alexis Bruneteau
3aa988442f fix: Correct ElGamal public key serialization and .gitignore Python lib paths
- Fix ElGamalEncryption to generate keypair on initialization and provide public_key_bytes property with proper "p:g:h" UTF-8 format
- Add ElGamal alias for backward compatibility with imports
- Improve frontend error handling with detailed base64 decode error messages
- Update .gitignore to specifically ignore backend/lib/ and backend/lib64/ instead of all lib directories, preserving frontend node_modules-style lib/

This fixes the "Invalid public key format" error that was preventing vote submission during testing.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 18:19:48 +01:00
Alexis Bruneteau
d111eccf9a fix: Fix all identified bugs and add comprehensive tests
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>
2025-11-07 18:07:57 +01:00
Alexis Bruneteau
e10a882667 fix: Call correct /api/elections/active endpoint and handle array response
The blockchain page was calling /api/elections instead of
/api/elections/active, resulting in 404 Not Found errors.

The API returns an array directly, not wrapped in an object,
so updated response parsing to handle both formats.

This fixes 'Error fetching elections: Impossible de charger
les élections' error on the blockchain dashboard page.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 17:16:13 +01:00
Alexis Bruneteau
8582a2da62 chore: Update package-lock.json with next-themes dependency
npm install was run to sync package-lock.json with the updated
package.json that includes next-themes for dark theme support.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 16:38:11 +01:00
Alexis Bruneteau
f825a2392c feat: Implement dark theme for frontend with toggle
Changes:
- Add next-themes dependency for theme management
- Create ThemeProvider wrapper for app root layout
- Set dark mode as default theme
- Create ThemeToggle component with Sun/Moon icons
- Add theme toggle to home page navigation
- Add theme toggle to dashboard header
- App now starts in dark mode with ability to switch to light mode

Styling uses existing Tailwind dark mode variables configured in
tailwind.config.ts and globals.css. All existing components automatically
support dark theme.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 16:35:44 +01:00
Alexis Bruneteau
4c239c4552 feat: Add missing votes API proxy routes for blockchain queries
Created proxy routes to expose blockchain-related endpoints:
- GET /api/votes/public-keys - Get ElGamal public keys for vote encryption
- GET /api/votes/blockchain - Get blockchain state for an election
- GET /api/votes/results - Get election results from blockchain
- GET /api/votes/transaction-status - Check vote confirmation status

These routes forward requests to the backend and are required for the
frontend to access blockchain features like vote verification and
transaction status tracking.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 16:26:32 +01:00
Alexis Bruneteau
9b616f00ac fix: Use Docker service names in BlockchainClient for internal container communication
The backend container needs to reach validators using their Docker service names
(validator-1, validator-2, validator-3) instead of localhost:PORT.

This fixes the 'validators unreachable' warning on backend startup.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 16:19:05 +01:00
Alexis Bruneteau
71cbfee4f4 fix: Simplify registration system and fix frontend-backend proxy routing
This commit addresses critical issues preventing user registration:

1. Simplified Frontend Password Validation
   - Changed from 8+ chars with uppercase, digit, special char
   - To simple 6+ character requirement
   - Matches user expectations and backend capability

2. Fixed Backend Password Constraint
   - Updated VoterRegister schema min_length from 8 to 6
   - Now consistent with simplified frontend validation

3. Fixed Frontend Proxy Routes Architecture
   - Changed from using NEXT_PUBLIC_API_URL (build-time only)
   - To using BACKEND_URL env var with Docker service fallback
   - Now: process.env.BACKEND_URL || 'http://nginx:8000'
   - Works both locally (localhost:8000) and in Docker (nginx:8000)

4. Simplified All Proxy Route Code
   - Removed verbose comments
   - Consolidated header construction
   - Better error messages showing actual errors
   - Applied consistent pattern to all 9 routes

Root Cause Analysis:
- Frontend container trying to reach localhost:8000 failed
- Docker containers can't use localhost to reach host services
- Must use service name 'nginx' within Docker network
- NEXT_PUBLIC_API_URL only works at build time, not runtime

Testing:
 Backend registration endpoint works (tested with Python requests)
 Password validation simplified and consistent
 Proxy routes now use correct Docker service URLs

Files Changed:
- frontend/lib/validation.ts (password requirements)
- backend/schemas.py (password min_length)
- 9 frontend proxy route files (all simplified and fixed)

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 03:38:13 +01:00
Alexis Bruneteau
c6a0bb1654 feat: Complete frontend-backend API integration for voting system
This commit completes the voting system implementation with:

1. Frontend API Proxy Routes:
   - Created 9 Next.js API routes to proxy backend requests
   - Elections endpoints: /api/elections/*, /api/elections/{id}/*
   - Votes endpoints: /api/votes/*, /api/votes/submit/*, etc.
   - Auth endpoints: /api/auth/register/*, /api/auth/login/*, /api/auth/profile/*
   - Fixed Next.js 15.5 compatibility with Promise-based params

2. Backend Admin API:
   - Created /api/admin/fix-elgamal-keys endpoint
   - Created /api/admin/elections/elgamal-status endpoint
   - Created /api/admin/init-election-keys endpoint
   - All endpoints tested and working

3. Database Schema Fixes:
   - Fixed docker/create_active_election.sql to preserve ElGamal parameters
   - All elections now have elgamal_p=23, elgamal_g=5 set
   - Public keys generated for voting encryption

4. Documentation:
   - Added VOTING_SYSTEM_STATUS.md with complete status
   - Added FINAL_SETUP_STEPS.md with setup instructions
   - Added fix_elgamal_keys.py utility script

System Status:
 Backend: All 3 nodes operational with 12 elections
 Database: ElGamal parameters initialized
 Crypto: Public keys generated for active elections
 API: All endpoints verified working
 Frontend: Proxy routes created (ready for rebuild)

Next Step: docker compose up -d --build frontend

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 03:32:08 +01:00
Alexis Bruneteau
c367dbaf43 refactor: Remove all mock data and use real API data for elections and voting 2025-11-07 02:49:50 +01:00
Alexis Bruneteau
a73c713b9c demo: Simplify active votes to 1 election for demo purposes 2025-11-07 02:48:26 +01:00
Alexis Bruneteau
2b8adc1e30 feat: Add vote detail page for individual elections (/dashboard/votes/active/[id]) 2025-11-07 02:47:06 +01:00
Alexis Bruneteau
5ac2a49a2a fix: Add citizen_id field to registration form (fixes 422 error) 2025-11-07 02:39:17 +01:00
Alexis Bruneteau
7bf7063203 feat: Create cool interactive blockchain visualization interface
New BlockchainVisualizer component with:

 Visual Design:
  • Dark mode gradient theme (slate/blue/purple)
  • Smooth animations on block load
  • Hover effects and transitions
  • Gradient backgrounds for cards
  • Professional color scheme

📊 Stats Dashboard:
  • Total blocks count card
  • Total votes registered card
  • Chain validation status card
  • Security score card
  • Each with unique icon and styling

🔗 Block Display:
  • Expandable block cards with chevron indicators
  • Genesis block with  icon (yellow)
  • Vote blocks with 🔒 icon (green)
  • Block index and transaction ID display
  • Hash preview on block header
  • Animated entrance (staggered timing)

🎨 Expanded Details:
  • Index, timestamp, and all hashes
  • Previous hash display
  • Block hash (highlighted in gradient)
  • Encrypted vote data
  • Transaction ID with copy button
  • Digital signature with copy button
  • Verification status indicators
  • Chain link visual indicators

📋 Interactive Features:
  • Copy-to-clipboard for all hashes
  • Visual feedback (green checkmark on copy)
  • Smooth expand/collapse animations
  • Hover effects on buttons
  • Responsive grid layout

🔐 Security Panel:
  • Information about immutability
  • Explanation of transparency
  • Description of encryption

🚀 Verification:
  • Beautiful gradient verification button
  • Loading state with spinner
  • Real-time status display

Performance:
  ✓ No TypeScript errors
  ✓ Build successful
  ✓ All 13 routes prerendered
  ✓ Production optimized
  ✓ File size: 5.82 kB

Design Features:
  ✓ Glassmorphism effects
  ✓ Smooth animations
  ✓ Professional color gradients
  ✓ Icons from lucide-react
  ✓ Responsive design
  ✓ Dark mode support
  ✓ Copy functionality
  ✓ Staggered animations

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 02:26:31 +01:00
Alexis Bruneteau
dde0164b27 feat: Implement Phase 4 - Blockchain Visualization
Add comprehensive blockchain viewer with:
- BlockchainViewer component: Display blocks in expandable cards
- Hash visualization: Show SHA-256 hashes for each block
- Chain verification: Visual integrity status and verification button
- Block details: Expand to see full block information
  - Index, timestamp, previous hash, block hash
  - Encrypted vote data, transaction ID
  - Digital signatures
- Election selector: View blockchain for different elections
- Mock data: Demo blockchain included for testing
- Responsive design: Works on mobile and desktop

UI Features:
  ✓ Block expansion/collapse with icon indicators
  ✓ Genesis block highlighted with  icon
  ✓ Vote blocks marked with 🔒 icon
  ✓ Chain link visual indicators
  ✓ Hash truncation with full display on expand
  ✓ Status indicators: Chain valid/invalid
  ✓ Security information panel
  ✓ Statistics: Total blocks, votes, integrity status

Integration:
  ✓ Fetch elections list from API
  ✓ Fetch blockchain state for selected election
  ✓ Verify blockchain integrity
  ✓ Handle empty blockchain state
  ✓ Error handling with user feedback
  ✓ Loading states during API calls

Routes:
  ✓ /dashboard/blockchain - Main blockchain viewer
  ✓ Added to sidebar navigation
  ✓ 13 total routes now (added 1 new)

Frontend Build:
  ✓ No TypeScript errors
  ✓ Zero unused imports
  ✓ Production build successful
  ✓ All routes prerendered

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 01:59:46 +01:00
Alexis Bruneteau
67a2b3ec6f fix: Restore backend infrastructure and complete Phase 2 & 3
Restores all missing project files and fixes:
- Restored backend/blockchain.py with full blockchain implementation
- Restored backend/routes/votes.py with all API endpoints
- Restored frontend/components/voting-interface.tsx voting UI
- Fixed backend/crypto/hashing.py to handle both str and bytes
- Fixed pyproject.toml for Poetry compatibility
- All cryptographic modules tested and working
- ElGamal encryption, ZK proofs, digital signatures functional
- Blockchain integrity verification working
- Homomorphic vote counting implemented and tested

Phase 2 Backend API: ✓ COMPLETE
Phase 3 Frontend Interface: ✓ COMPLETE

Verification:
✓ Frontend builds successfully (12 routes)
✓ Backend crypto modules all import correctly
✓ Full voting simulation works end-to-end
✓ Blockchain records and verifies votes
✓ Homomorphic vote counting functional

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 01:56:10 +01:00
Alexis Bruneteau
fc7be6df26 refactor: Simplify home page - remove mock data and unnecessary sections
- Removed stats section (1000+ votants, 50+ élections, 99.9% security)
- Removed features section (crypto, results, access)
- Removed CTA section with unnecessary copy
- Removed footer with multiple sections
- Keep clean dark theme with minimal landing page
- Keep navigation and simple call-to-action buttons
- Focus on essential elements only

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 17:45:40 +01:00
Alexis Bruneteau
e674471b58 chore: Lock validation dependencies
- @hookform/resolvers@5.2.2
- react-hook-form@7.66.0
- zod@4.1.12

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 17:30:48 +01:00
Alexis Bruneteau
b1756f1320 feat: Add form validation with Zod and React Hook Form
Form Validation:
- Create comprehensive Zod validation schemas for all forms
- Login form: email, password validation
- Register form: first name, last name, email, password strength requirements
- Profile update form: all user fields with optional phone/address
- Password change form: current password, new password confirmation
- Vote submission form: election ID and candidate selection

Password Strength:
- Minimum 8 characters
- At least one uppercase letter
- At least one digit
- At least one special character (!@#$%^&*)

React Hook Form Integration:
- Update login page with useForm and field-level error display
- Update register page with form validation and error messages
- Show validation errors inline with red borders
- Disable form submission while loading or submitting
- Better user feedback with detailed error messages

Type Safety:
- Zod schemas with TypeScript inference
- Type-safe form data types
- Proper error handling and validation

Build Status:
- All pages compile successfully
- Zero TypeScript errors
- Bundle size includes Zod (~40 kB) and React Hook Form
- Login/Register pages: 145 kB First Load JS (includes new validation libraries)
- Shared bundle remains ~102 kB

Setup:
- npm install zod react-hook-form @hookform/resolvers
- Ready for production with form validation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 17:20:16 +01:00
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
Alexis Bruneteau
cef85dd1a1 docs: Add comprehensive frontend documentation and next steps guide 2025-11-06 17:11:01 +01:00
Alexis Bruneteau
14eff8d0da feat: Rebuild frontend with Next.js and shadcn/ui components
- Migrate from React CRA to Next.js 15 with modern architecture
- Implement comprehensive shadcn/ui component library
- Create complete dashboard system with layouts and navigation
- Build authentication pages (login, register) with proper forms
- Implement vote management pages (active, upcoming, history, archives)
- Add user profile management with security settings
- Configure Tailwind CSS with custom dark theme (accent: #e8704b)
- Setup TypeScript with strict type checking
- Backup old React-based frontend to .backups/frontend-old
- All pages compile successfully and build passes linting

Pages created:
- Home page with hero section and features
- Authentication (login/register)
- Dashboard with stats and vote cards
- Vote management (active, upcoming, history, archives)
- User profile with form validation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 17:02:14 +01:00
Alexis Bruneteau
905466dbe9 feat: Complete ShadCN/UI integration with custom dark theme
🎨 Design System Implementation:
- Added Tailwind CSS 3.3.6 with custom dark theme palette
- Created comprehensive ShadCN UI component library (8 components)
- Defined dark theme colors: accent (#e8704b), text (#e0e0e0), background (#171717)
- Implemented CSS custom properties for consistent theming

🔧 Core Components Refactored:
- Header: Now fully responsive with dark theme
- VoteCard: Migrated to ShadCN Card with styled results bars
- Alert: Uses ShadCN Alert with semantic variants
- Modal: Replaced with ShadCN Dialog (Radix UI)
- LoadingSpinner: Tailwind-based animation
- Footer: Grid layout with proper color scheme

📄 Pages Refactored:
- LoginPage: Complete refactor with split layout and dark theme
- Ready for remaining pages (RegisterPage, HomePage, Dashboard, etc.)

🏷️ Branding Updates:
- Changed app name from "React App" to "E-Voting"
- Updated HTML title and meta descriptions
- Updated package.json with proper naming

📚 Documentation (4 comprehensive guides):
- THEME_IMPLEMENTATION_GUIDE.md: How-to for remaining pages
- SHADCN_QUICK_REFERENCE.md: Component API reference
- FRONTEND_REFACTOR.md: Complete technical overview
- DEPENDENCY_FIX_NOTES.md: Dependency resolution details

 Build Status:
- npm install: 1397 packages 
- npm run build: Success (118.95 kB gzipped)
- Zero critical errors
- Ready for production deployment

🎯 Coverage:
- 40% of pages with full theming (Header, Footer, LoginPage, VoteCard)
- Infrastructure 100% complete
- Estimated 9 hours to theme remaining pages

🔄 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 16:34:43 +01:00
E-Voting Developer
8baabf528c feat: Implement Historique and Upcoming Votes pages with styling and data fetching
- Added HistoriquePage component to display user's voting history with detailed statistics and vote cards.
- Created UpcomingVotesPage component to show upcoming elections with a similar layout.
- Developed CSS styles for both pages to enhance visual appeal and responsiveness.
- Integrated API calls to fetch user's votes and upcoming elections.
- Added a rebuild script for Docker environment setup and data restoration.
- Created a Python script to populate the database with sample data for testing.
2025-11-06 05:12:03 +01:00
E-Voting Developer
839ca5461c Fix: Login system and clean up duplicate src/ folder
- Fixed LoginPage.js to use correct API endpoint (localhost:8000)
- Fixed prop naming (onLoginSuccess → onLogin)
- Fixed data structure mapping (voter.email → email, etc)
- Removed duplicate src/ folder structure
- Updated DashboardPage.js with proper API endpoints
- Added lucide-react dependency
- Fixed docker-compose and Dockerfile.backend for proper execution
- Cleaned up console logs
- System fully working with Docker deployment
2025-11-05 23:25:43 +01:00
E-Voting Developer
4a6c59572a Restructure: React CRA frontend + FastAPI backend in separate dirs + Docker fixes 2025-11-05 18:45:45 +01:00