Repository navigation
Expand file tree
/
Copy pathproject.py
More file actions
579 lines (477 loc) · 21.2 KB
/
Copy pathproject.py
File metadata and controls
579 lines (477 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import tkinter as t
from tkinter import ttk, messagebox
import os
import sys
import hashlib
import secrets
import base64
import mysql.connector
from mysql.connector import Error
from dotenv import load_dotenv
load_dotenv() # reads variables from a local .env file, if present
# ------------------ THEME ------------------
COLORS = {
"bg": "#0f172a", # slate-900, app background
"panel": "#1e293b", # slate-800, card background
"panel_alt": "#111827",
"accent": "#38bdf8", # sky-400
"accent_dark": "#0284c7",
"text": "#e2e8f0",
"muted": "#94a3b8",
"danger": "#f87171",
"success": "#4ade80",
}
FONT_TITLE = ("Segoe UI", 20, "bold")
FONT_LABEL = ("Segoe UI", 11)
FONT_ENTRY = ("Segoe UI", 11)
FONT_BUTTON = ("Segoe UI", 11, "bold")
PARTY_COLORS = {
"BJP": "#f97316",
"INC": "#38bdf8",
"AAP": "#4ade80",
"SP": "#f43f5e",
"INDIA": "#a78bfa",
"NOTA": "#64748b",
}
current_voter_id = None # Identifier of whichever voter is currently logged in
# ------------------ PASSWORD HASHING (SHORTENED) ------------------
def hash_password(plain_password: str) -> str:
# 3 bytes of randomness = 6 hex characters
salt = secrets.token_hex(3)
# Hash the password and compress it into base64, then truncate to 20 characters
raw_hash = hashlib.sha256((salt + plain_password).encode("utf-8")).digest()
digest = base64.b64encode(raw_hash).decode('utf-8')[:20]
# Total length: 6 (salt) + 1 ($) + 20 (hash) = 27 characters
return f"{salt}${digest}"
def verify_password(plain_password: str, stored_value: str) -> bool:
try:
salt, digest = stored_value.split("$", 1)
raw_hash = hashlib.sha256((salt + plain_password).encode("utf-8")).digest()
expected_digest = base64.b64encode(raw_hash).decode('utf-8')[:20]
return expected_digest == digest
except (ValueError, AttributeError):
# Fallback for plain-text unhashed values in legacy tables
return plain_password == stored_value
# ------------------ DATABASE CONNECTION ------------------
def get_connection():
return mysql.connector.connect(
host=os.getenv("DB_HOST", "localhost"),
user=os.getenv("DB_USER"),
password=os.getenv("DB_PASSWORD"),
database=os.getenv("DB_NAME", "vote_db")
)
def run_db(action):
"""
Runs a DB action safely.
action: a function that takes (cur, conn) and returns a result.
Handles connect/close and errors in one place so every button
doesn't repeat the same try/except/finally boilerplate.
"""
conn = None
try:
conn = get_connection()
cur = conn.cursor(buffered=True) # buffered=True prevents unread result errors
result = action(cur, conn)
conn.commit()
return result
except Error as e:
if getattr(e, "errno", None) == 1062: # Duplicate entry for UNIQUE/PRIMARY KEY column
messagebox.showwarning("Already Voted", "This vote has already been cast. Duplicate voting is not allowed.")
# Catch foreign key constraint failures
elif getattr(e, "errno", None) == 1452:
messagebox.showerror("Database Error", "Integrity error: This user does not exist in the registration database.")
else:
messagebox.showerror("Database Error", str(e))
return None
finally:
if conn is not None and conn.is_connected():
cur.close()
conn.close()
def _ensure_voter_table(cur):
"""Creates the voter table and applies schema migrations if necessary."""
cur.execute("""
CREATE TABLE IF NOT EXISTS voter (
AadharNo BIGINT PRIMARY KEY,
Name VARCHAR(100),
FatherName VARCHAR(100),
Age INT,
City VARCHAR(100),
Gender VARCHAR(10),
Password VARCHAR(60),
Pincode INT,
Address VARCHAR(255),
MobileNo BIGINT
)
""")
try:
cur.execute("ALTER TABLE voter CHANGE COLUMN AdharNo AadharNo BIGINT")
except Error:
pass
try:
cur.execute("ALTER TABLE voter MODIFY COLUMN AadharNo BIGINT")
except Error:
pass
try:
cur.execute("ALTER TABLE voter MODIFY COLUMN Password VARCHAR(60)")
except Error:
pass
# ------------------ REGISTRATION ------------------
def submitButton():
if not eaadhar.get() or not ename.get() or not epass.get():
messagebox.showwarning("Missing Info", "Please fill in ID, Name and Password.")
return
if len(eaadhar.get()) != 12:
messagebox.showwarning("Invalid ID", "ID Number must be exactly 12 digits.")
return
if emob.get() and len(emob.get()) != 10:
messagebox.showwarning("Invalid Mobile Number", "Mobile Number must be exactly 10 digits.")
return
def action(cur, conn):
_ensure_voter_table(cur)
q = """INSERT INTO voter (AadharNo, Name, FatherName, Age, City, Gender, Password, Pincode, Address, MobileNo)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
v = (eaadhar.get(), ename.get(), efname.get(), eage.get(), ecity.get(),
m.get(), hash_password(epass.get()), epin.get(), eadd.get(), emob.get())
cur.execute(q, v)
return True
if run_db(action):
messagebox.showinfo("Registered", "Registration Complete")
loginPage()
# ------------------ LOGIN ------------------
def loginButton():
aadhar_entered = eaadhar.get()
if len(aadhar_entered) != 12:
messagebox.showwarning("Invalid ID", "ID Number must be exactly 12 digits.")
return
def action(cur, conn):
_ensure_voter_table(cur)
cur.execute("SELECT * FROM voter WHERE AadharNo = %s", (aadhar_entered,))
row = cur.fetchone()
return row if row else False
rec = run_db(action)
if rec and verify_password(epass.get(), rec[6]): # column 6 = Password
global current_voter_id
current_voter_id = aadhar_entered
messagebox.showinfo("Success", "Login Success")
votingPage()
elif rec is not None:
messagebox.showerror("Failed", "Login Failed")
# ------------------ EC LOGIN ------------------
def ecLoginButton():
def action(cur, conn):
cur.execute("""
CREATE TABLE IF NOT EXISTS ec_login (
ec_id VARCHAR(50) PRIMARY KEY,
password VARCHAR(60)
)
""")
try:
cur.execute("ALTER TABLE ec_login MODIFY COLUMN password VARCHAR(60)")
except Error:
pass
# Load administrator credentials strictly from .env without hardcoded defaults
secure_ec_id = os.getenv("EC_ID")
secure_ec_pass = os.getenv("EC_PASSWORD")
if not secure_ec_id or not secure_ec_pass:
messagebox.showerror("Configuration Error", "EC credentials are not set in the .env file.")
return None
cur.execute("SELECT * FROM ec_login WHERE ec_id = %s", (secure_ec_id,))
if not cur.fetchone():
cur.execute(
"INSERT INTO ec_login (ec_id, password) VALUES (%s, %s)",
(secure_ec_id, hash_password(secure_ec_pass))
)
cur.execute("SELECT * FROM ec_login WHERE ec_id = %s", (ec_id.get(),))
row = cur.fetchone()
return row if row else False
rec = run_db(action)
if rec and verify_password(ec_pass.get(), rec[1]): # column 1 = password
messagebox.showinfo("Success", "EC Login Success")
ecHomePage()
elif rec is not None:
messagebox.showerror("Failed", "EC Login Failed")
def _ensure_votes_table(cur):
"""Creates the votes table with a proper Foreign Key linking back to the voter table."""
cur.execute("""
CREATE TABLE IF NOT EXISTS votes (
AadharNo BIGINT PRIMARY KEY,
party VARCHAR(50),
FOREIGN KEY (AadharNo) REFERENCES voter(AadharNo) ON DELETE CASCADE
)
""")
# Migrations for existing databases
try:
cur.execute("ALTER TABLE votes ADD COLUMN AadharNo BIGINT UNIQUE")
except Error:
pass
try:
cur.execute("ALTER TABLE votes MODIFY COLUMN AadharNo BIGINT")
except Error:
pass
# Add foreign key to legacy tables if it doesn't already exist
try:
cur.execute("""
ALTER TABLE votes
ADD CONSTRAINT fk_voter_id
FOREIGN KEY (AadharNo) REFERENCES voter(AadharNo)
ON DELETE CASCADE
""")
except Error:
pass
def has_already_voted(cur, conn):
_ensure_votes_table(cur)
cur.execute("SELECT party FROM votes WHERE AadharNo = %s", (current_voter_id,))
return cur.fetchone()
# ------------------ VOTING ------------------
def voteButton(party):
if not messagebox.askyesno("Confirm Vote", f"Cast your vote for {party}? This cannot be undone."):
return
def action(cur, conn):
_ensure_votes_table(cur)
cur.execute("INSERT INTO votes (AadharNo, party) VALUES (%s, %s)", (current_voter_id, party))
return True
if run_db(action):
messagebox.showinfo("Success", "Voting Done Successfully")
registerPage()
# ------------------ SHARED UI HELPERS ------------------
def clearWindow():
for widget in root.winfo_children():
widget.destroy()
def make_header(parent, title, subtitle=None):
header = t.Frame(parent, bg=COLORS["bg"])
header.pack(fill="x", pady=(0, 20))
t.Label(header, text=title, font=FONT_TITLE, fg=COLORS["accent"], bg=COLORS["bg"]).pack()
if subtitle:
t.Label(header, text=subtitle, font=FONT_LABEL, fg=COLORS["muted"], bg=COLORS["bg"]).pack(pady=(4, 0))
def make_card(parent):
card = t.Frame(parent, bg=COLORS["panel"], padx=30, pady=25,
highlightbackground=COLORS["accent_dark"], highlightthickness=1)
card.pack(padx=20, pady=10)
return card
def _digit_limit_validator(widget, max_len):
def validate(P):
if P == "":
return True
return P.isdigit() and len(P) <= max_len
return (widget.register(validate), '%P')
def add_field(card, row, label_text, var, show=None, max_digits=None):
t.Label(card, text=label_text, font=FONT_LABEL, fg=COLORS["muted"], bg=COLORS["panel"], anchor="w")\
.grid(row=row, column=0, sticky="w", padx=(0, 15), pady=8)
entry = t.Entry(card, width=28, font=FONT_ENTRY, textvariable=var, show=show,
bg=COLORS["panel_alt"], fg=COLORS["text"], insertbackground=COLORS["text"],
relief="flat", highlightthickness=1, highlightbackground=COLORS["accent_dark"])
if max_digits is not None:
vcmd = _digit_limit_validator(entry, max_digits)
entry.config(validate="key", validatecommand=vcmd)
entry.grid(row=row, column=1, sticky="ew", pady=8, ipady=4)
return entry
def styled_button(parent, text, command, bg=None, fg="white"):
bg = bg or COLORS["accent_dark"]
btn = t.Button(parent, text=text, font=FONT_BUTTON, fg=fg, bg=bg,
activebackground=COLORS["accent"], activeforeground="black",
relief="flat", padx=16, pady=8, cursor="hand2", command=command,
borderwidth=0)
return btn
# ------------------ PAGES ------------------
def registerPage():
clearWindow()
root.title("Voter Registration")
root.configure(bg=COLORS["bg"])
make_header(root, "VOTER REGISTRATION", "Create your account to vote")
card = make_card(root)
card.columnconfigure(1, weight=1)
add_field(card, 0, "ID NUMBER", eaadhar, max_digits=12)
add_field(card, 1, "NAME", ename)
add_field(card, 2, "FATHER'S NAME", efname)
add_field(card, 3, "AGE", eage)
add_field(card, 4, "PASSWORD", epass, show="*")
add_field(card, 5, "PINCODE", epin)
add_field(card, 6, "ADDRESS", eadd)
add_field(card, 7, "MOBILE NUMBER", emob, max_digits=10)
add_field(card, 8, "CITY", ecity)
t.Label(card, text="GENDER", font=FONT_LABEL, fg=COLORS["muted"], bg=COLORS["panel"], anchor="w")\
.grid(row=9, column=0, sticky="w", pady=8)
gender_frame = t.Frame(card, bg=COLORS["panel"])
gender_frame.grid(row=9, column=1, sticky="w", pady=8)
for text in ("Male", "Female"):
t.Radiobutton(gender_frame, text=text, value=text, variable=m,
font=FONT_LABEL, fg=COLORS["text"], bg=COLORS["panel"],
selectcolor=COLORS["panel_alt"], activebackground=COLORS["panel"],
activeforeground=COLORS["accent"]).pack(side="left", padx=(0, 15))
btn_row = t.Frame(root, bg=COLORS["bg"])
btn_row.pack(pady=15)
styled_button(btn_row, "REGISTER", submitButton, bg=COLORS["accent_dark"]).pack(side="left", padx=8)
styled_button(btn_row, "ALREADY REGISTERED? LOG IN", loginPage, bg=COLORS["panel_alt"]).pack(side="left", padx=8)
styled_button(btn_row, "EC LOGIN", ecLoginPage, bg=COLORS["panel_alt"]).pack(side="left", padx=8)
def loginPage():
clearWindow()
root.title("Voter Login")
root.configure(bg=COLORS["bg"])
make_header(root, "VOTER LOGIN", "Enter your credentials to vote")
card = make_card(root)
card.columnconfigure(1, weight=1)
add_field(card, 0, "ID NUMBER", eaadhar, max_digits=12)
add_field(card, 1, "PASSWORD", epass, show="*")
btn_row = t.Frame(root, bg=COLORS["bg"])
btn_row.pack(pady=15)
styled_button(btn_row, "LOG IN", loginButton, bg=COLORS["accent_dark"]).pack(side="left", padx=8)
styled_button(btn_row, "NEW HERE? REGISTER", registerPage, bg=COLORS["panel_alt"]).pack(side="left", padx=8)
def ecLoginPage():
clearWindow()
root.title("Election Commission Login")
root.configure(bg=COLORS["bg"])
make_header(root, "ELECTION COMMISSION LOGIN", "Administrator access only")
card = make_card(root)
card.columnconfigure(1, weight=1)
add_field(card, 0, "EC ID", ec_id)
add_field(card, 1, "PASSWORD", ec_pass, show="*")
btn_row = t.Frame(root, bg=COLORS["bg"])
btn_row.pack(pady=15)
styled_button(btn_row, "LOG IN", ecLoginButton, bg=COLORS["accent_dark"]).pack(side="left", padx=8)
styled_button(btn_row, "BACK", registerPage, bg=COLORS["panel_alt"]).pack(side="left", padx=8)
def votingPage():
clearWindow()
root.title("Cast Your Vote")
root.configure(bg=COLORS["bg"])
already_voted = run_db(has_already_voted)
if already_voted:
make_header(root, "YOU HAVE ALREADY VOTED", "Duplicate voting is not allowed")
card = t.Frame(root, bg=COLORS["panel"], padx=40, pady=30)
card.pack(pady=20)
t.Label(card, text=f"Your vote for {already_voted[0]} has already been recorded.",
font=FONT_LABEL, fg=COLORS["text"], bg=COLORS["panel"]).pack(pady=(0, 15))
styled_button(card, "LOG OUT", registerPage, bg=COLORS["panel_alt"]).pack()
return
make_header(root, "CAST YOUR VOTE", "Choose one party below")
grid = t.Frame(root, bg=COLORS["bg"])
grid.pack(pady=10)
parties = ["BJP", "INC", "AAP", "SP", "INDIA", "NOTA"]
for i, party in enumerate(parties):
row, col = divmod(i, 3)
card = t.Frame(grid, bg=COLORS["panel"], padx=20, pady=20,
highlightbackground=PARTY_COLORS[party], highlightthickness=2)
card.grid(row=row, column=col, padx=12, pady=12)
t.Label(card, text=party, font=("Segoe UI", 14, "bold"),
fg=PARTY_COLORS[party], bg=COLORS["panel"]).pack(pady=(0, 10))
styled_button(card, "VOTE", lambda p=party: voteButton(p),
bg=PARTY_COLORS[party], fg="black").pack()
def ecHomePage():
clearWindow()
root.title("EC Dashboard")
root.configure(bg=COLORS["bg"])
make_header(root, "EC DASHBOARD", "Live voting results")
def action(cur, conn):
_ensure_votes_table(cur)
cur.execute("SELECT party, COUNT(*) FROM votes GROUP BY party")
results = cur.fetchall()
cur.execute("""
CREATE TABLE IF NOT EXISTS results (
party VARCHAR(50) PRIMARY KEY,
vote_count INT
)
""")
parties = ["BJP", "INC", "AAP", "SP", "INDIA", "NOTA"]
for party in parties:
vote_count = next((r[1] for r in results if r[0] == party), 0)
cur.execute("""
INSERT INTO results (party, vote_count)
VALUES (%s, %s)
ON DUPLICATE KEY UPDATE vote_count = %s
""", (party, vote_count, vote_count))
cur.execute("SELECT ec_id FROM ec_login")
ec_users = cur.fetchall()
return results, ec_users
data = run_db(action)
results, ec_users = data if data else ([], [])
parties = ["BJP", "INC", "AAP", "SP", "INDIA", "NOTA"]
counts = {p: next((r[1] for r in results if r[0] == p), 0) for p in parties}
total_votes = sum(counts.values())
body = t.Frame(root, bg=COLORS["bg"])
body.pack(fill="both", expand=True, padx=20)
# ---- Left: results table ----
left = t.Frame(body, bg=COLORS["panel"], padx=20, pady=20)
left.grid(row=0, column=0, sticky="n", padx=(0, 15))
t.Label(left, text=f"Total Votes Cast: {total_votes}", font=("Segoe UI", 13, "bold"),
fg=COLORS["accent"], bg=COLORS["panel"]).pack(anchor="w", pady=(0, 12))
style = ttk.Style()
style.theme_use("clam")
style.configure("Results.Treeview",
background=COLORS["panel_alt"], fieldbackground=COLORS["panel_alt"],
foreground=COLORS["text"], rowheight=28, font=FONT_LABEL, borderwidth=0)
style.configure("Results.Treeview.Heading", background=COLORS["accent_dark"],
foreground="white", font=("Segoe UI", 10, "bold"))
style.map("Results.Treeview", background=[("selected", COLORS["accent_dark"])])
tree = ttk.Treeview(left, columns=("party", "votes"), show="headings",
style="Results.Treeview", height=len(parties))
tree.heading("party", text="Party")
tree.heading("votes", text="Votes")
tree.column("party", width=140, anchor="w")
tree.column("votes", width=80, anchor="center")
sorted_parties = sorted(parties, key=lambda p: counts[p], reverse=True)
for p in sorted_parties:
tree.insert("", "end", values=(p, counts[p]), tags=(p,))
tree.tag_configure(p, foreground=PARTY_COLORS[p])
tree.pack(fill="x")
if results:
sorted_by_votes = sorted(results, key=lambda x: x[1], reverse=True)
winner = sorted_by_votes[0][0]
runner_up = sorted_by_votes[1][0] if len(sorted_by_votes) > 1 else "None"
else:
winner, runner_up = "None", "None"
t.Label(left, text=f"🏆 Winner: {winner}", font=("Segoe UI", 12, "bold"),
fg=COLORS["success"], bg=COLORS["panel"]).pack(anchor="w", pady=(15, 2))
t.Label(left, text=f"Runner-up: {runner_up}", font=FONT_LABEL,
fg=COLORS["muted"], bg=COLORS["panel"]).pack(anchor="w")
# ---- Right: EC users ----
right = t.Frame(body, bg=COLORS["panel"], padx=20, pady=20)
right.grid(row=0, column=1, sticky="n")
t.Label(right, text="EC Users", font=("Segoe UI", 13, "bold"),
fg=COLORS["accent"], bg=COLORS["panel"]).pack(anchor="w", pady=(0, 12))
if ec_users:
for user in ec_users:
t.Label(right, text=f"• {user[0]}", font=FONT_LABEL,
fg=COLORS["text"], bg=COLORS["panel"]).pack(anchor="w", pady=2)
else:
t.Label(right, text="No EC users found.", font=FONT_LABEL,
fg=COLORS["muted"], bg=COLORS["panel"]).pack(anchor="w")
styled_button(root, "LOG OUT", registerPage, bg=COLORS["panel_alt"]).pack(pady=20)
# ------------------ MAIN ------------------
required_env_vars = ["DB_USER", "DB_PASSWORD", "EC_ID", "EC_PASSWORD"]
missing_vars = [var for var in required_env_vars if not os.getenv(var)]
if missing_vars:
print(
f"ERROR: Missing environment configuration: {', '.join(missing_vars)}\n"
"Create a '.env' file next to this script with:\n"
" DB_HOST=localhost\n"
" DB_USER=<your_database_user>\n"
" DB_PASSWORD=<your_database_password>\n"
" DB_NAME=vote_db\n"
" EC_ID=<your_admin_id>\n"
" EC_PASSWORD=<your_admin_password>\n"
)
sys.exit(1)
root = t.Tk()
root.geometry("1000x700")
root.configure(bg=COLORS["bg"])
# Center window on screen
root.update_idletasks()
w, h = 1000, 700
x = (root.winfo_screenwidth() // 2) - (w // 2)
y = (root.winfo_screenheight() // 2) - (h // 2)
root.geometry(f"{w}x{h}+{x}+{y}")
# Variables
eaadhar = t.StringVar()
ename = t.StringVar()
efname = t.StringVar()
eage = t.StringVar()
epass = t.StringVar()
epin = t.StringVar()
eadd = t.StringVar()
emob = t.StringVar()
ecity = t.StringVar()
m = t.StringVar(value="Male")
ec_id = t.StringVar()
ec_pass = t.StringVar()
# Start with registration page
registerPage()
root.mainloop()