#!/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)