CIA/e-voting-system/backend/scripts/fix_elgamal_keys.py
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

84 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""
Fix script to update elections with missing ElGamal parameters.
This script connects directly to the MariaDB database and updates all
elections with the required ElGamal encryption parameters (p=23, g=5).
"""
import os
import sys
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
# Database configuration
DB_USER = os.getenv('DB_USER', 'evoting_user')
DB_PASS = os.getenv('DB_PASS', 'evoting_pass123')
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = os.getenv('DB_PORT', '3306')
DB_NAME = os.getenv('DB_NAME', 'evoting_db')
# Create database connection string
DATABASE_URL = f"mysql+pymysql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
print(f"Connecting to database: {DB_HOST}:{DB_PORT}/{DB_NAME}")
try:
# Create engine
engine = create_engine(DATABASE_URL)
# Test connection
with engine.connect() as conn:
print("✓ Successfully connected to database")
# Check current status
result = conn.execute(text(
"SELECT id, name, elgamal_p, elgamal_g FROM elections LIMIT 5"
))
print("\nBefore update:")
for row in result:
print(f" ID {row[0]}: {row[1]}")
print(f" elgamal_p: {row[2]}, elgamal_g: {row[3]}")
# Update all elections with ElGamal parameters
print("\nUpdating all elections with ElGamal parameters...")
update_result = conn.execute(text(
"UPDATE elections SET elgamal_p = 23, elgamal_g = 5 WHERE elgamal_p IS NULL OR elgamal_g IS NULL"
))
conn.commit()
rows_updated = update_result.rowcount
print(f"✓ Updated {rows_updated} elections")
# Verify update
result = conn.execute(text(
"SELECT id, name, elgamal_p, elgamal_g FROM elections LIMIT 5"
))
print("\nAfter update:")
for row in result:
print(f" ID {row[0]}: {row[1]}")
print(f" elgamal_p: {row[2]}, elgamal_g: {row[3]}")
# Check active elections
result = conn.execute(text(
"SELECT id, name, elgamal_p, elgamal_g FROM elections WHERE is_active = TRUE"
))
print("\nActive elections with ElGamal keys:")
active_count = 0
for row in result:
if row[2] is not None and row[3] is not None:
print(f" ✓ ID {row[0]}: {row[1]}")
active_count += 1
if active_count > 0:
print(f"\n✓ All {active_count} active elections now have ElGamal keys!")
else:
print("\n⚠ No active elections found")
except Exception as e:
print(f"✗ Error: {e}")
sys.exit(1)