-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
751 lines (714 loc) · 30.9 KB
/
index.html
File metadata and controls
751 lines (714 loc) · 30.9 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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VoteLive – Live Election Management</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
width: 100%;
max-width: 1200px;
background: rgba(255,255,255,0.95);
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 30px;
backdrop-filter: blur(10px);
}
h1, h2 {
color: #333;
margin-bottom: 20px;
text-align: center;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: 500;
}
input, select, button {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 16px;
transition: border 0.3s;
}
input:focus, select:focus {
outline: none;
border-color: #667eea;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
cursor: pointer;
font-weight: 600;
margin-top: 10px;
transition: transform 0.2s;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102,126,234,0.4);
}
.card {
background: white;
border-radius: 12px;
padding: 20px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
.flex {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.candidate-card {
flex: 1 1 200px;
text-align: center;
padding: 15px;
border: 1px solid #eee;
border-radius: 12px;
transition: all 0.3s;
}
.candidate-card:hover {
transform: scale(1.05);
box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.symbol {
font-size: 40px;
margin-bottom: 10px;
}
.vote-btn {
background: #4CAF50;
margin-top: 10px;
}
.vote-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
.hidden {
display: none;
}
.modal {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 12px;
max-width: 400px;
text-align: center;
}
.winner-announcement {
background: gold;
color: #333;
padding: 20px;
border-radius: 12px;
font-size: 24px;
font-weight: bold;
animation: pulse 1s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background: #f5f5f5;
}
.chart-container {
margin-top: 30px;
height: 300px;
}
.logout {
float: right;
background: #f44336;
width: auto;
padding: 8px 16px;
}
</style>
<!-- Chart.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Socket.io client -->
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div class="container" id="app">
<!-- Login / Register Section -->
<div id="auth-section">
<h1>VoteLive – Secure Election System</h1>
<div class="flex">
<div class="card" style="flex:1">
<h2>Voter Login</h2>
<form id="login-form">
<div class="form-group">
<label>Email</label>
<input type="email" id="login-email" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="login-password" required>
</div>
<button type="submit">Login</button>
</form>
<p style="text-align:center; margin-top:15px">
<a href="#" id="show-register">New voter? Register</a> |
<a href="#" id="show-admin-register">Admin setup</a>
</p>
</div>
</div>
</div>
<!-- Voter Registration Form (hidden initially) -->
<div id="register-section" class="hidden">
<h2>Voter Registration</h2>
<form id="register-form">
<div class="form-group">
<label>CNIC (XXXXX-XXXXXXX-X)</label>
<input type="text" id="reg-cnic" pattern="\d{5}-\d{7}-\d" required>
</div>
<div class="form-group">
<label>Full Name</label>
<input type="text" id="reg-name" required>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="reg-email" required>
</div>
<div class="form-group">
<label>Password (min 6)</label>
<input type="password" id="reg-password" minlength="6" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" id="reg-confirm" required>
</div>
<div class="form-group">
<label>Date of Birth</label>
<input type="date" id="reg-dob" required>
</div>
<div class="form-group">
<label>Father's Name</label>
<input type="text" id="reg-father" required>
</div>
<button type="submit">Register</button>
<button type="button" id="back-to-login">Back</button>
</form>
</div>
<!-- Admin Registration (with secret key) -->
<div id="admin-register-section" class="hidden">
<h2>Admin Setup (First Admin Only)</h2>
<form id="admin-register-form">
<div class="form-group">
<label>Secret Key</label>
<input type="password" id="admin-secret" required>
</div>
<div class="form-group">
<label>CNIC</label>
<input type="text" id="admin-cnic" pattern="\d{5}-\d{7}-\d" required>
</div>
<div class="form-group">
<label>Full Name</label>
<input type="text" id="admin-name" required>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="admin-email" required>
</div>
<div class="form-group">
<label>Password (min 6)</label>
<input type="password" id="admin-password" minlength="6" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" id="admin-confirm" required>
</div>
<div class="form-group">
<label>Date of Birth</label>
<input type="date" id="admin-dob" required>
</div>
<div class="form-group">
<label>Father's Name</label>
<input type="text" id="admin-father" required>
</div>
<button type="submit">Create Admin</button>
<button type="button" id="back-to-login-admin">Back</button>
</form>
</div>
<!-- Voter Dashboard (hidden) -->
<div id="voter-dashboard" class="hidden">
<button class="logout" id="logout-btn">Logout</button>
<h2>Voter Dashboard</h2>
<div id="active-elections"></div>
<!-- Election details will be populated here -->
</div>
<!-- Admin Dashboard (hidden) -->
<div id="admin-dashboard" class="hidden">
<button class="logout" id="admin-logout-btn">Logout</button>
<h2>Admin Dashboard</h2>
<div class="flex">
<div class="card" style="flex:1">
<h3>Create Election</h3>
<form id="create-election-form">
<input type="text" id="election-title" placeholder="Election Title" required>
<button type="submit">Create</button>
</form>
</div>
<div class="card" style="flex:1">
<h3>Add Candidate</h3>
<form id="add-candidate-form">
<select id="candidate-election" required></select>
<input type="text" id="candidate-name" placeholder="Candidate Name" required>
<input type="text" id="candidate-party" placeholder="Party Name" required>
<input type="text" id="candidate-symbol" placeholder="Symbol (e.g., 🐘 or URL)" required>
<button type="submit">Add</button>
</form>
</div>
</div>
<div class="card">
<h3>Manage Elections</h3>
<div id="elections-list"></div>
</div>
<div class="card">
<h3>Live Results</h3>
<select id="live-election-select"></select>
<div class="chart-container">
<canvas id="results-chart"></canvas>
</div>
</div>
<div class="card">
<h3>Voter Information</h3>
<button id="load-voters">Load Voters</button>
<div id="voters-table"></div>
</div>
<div class="card">
<h3>Export Votes</h3>
<select id="export-election"></select>
<button id="export-pdf">Export as PDF</button>
</div>
<div id="winner-modal" class="modal hidden">
<div class="modal-content winner-announcement" id="winner-text"></div>
</div>
</div>
</div>
<script>
const socket = io();
let currentUser = null;
let chart;
// Helper: show/hide sections
function showAuth() {
document.getElementById('auth-section').classList.remove('hidden');
document.getElementById('register-section').classList.add('hidden');
document.getElementById('admin-register-section').classList.add('hidden');
document.getElementById('voter-dashboard').classList.add('hidden');
document.getElementById('admin-dashboard').classList.add('hidden');
}
// Event listeners for navigation
document.getElementById('show-register').addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('auth-section').classList.add('hidden');
document.getElementById('register-section').classList.remove('hidden');
});
document.getElementById('show-admin-register').addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('auth-section').classList.add('hidden');
document.getElementById('admin-register-section').classList.remove('hidden');
});
document.getElementById('back-to-login').addEventListener('click', showAuth);
document.getElementById('back-to-login-admin').addEventListener('click', showAuth);
// Registration
document.getElementById('register-form').addEventListener('submit', async (e) => {
e.preventDefault();
const password = document.getElementById('reg-password').value;
const confirm = document.getElementById('reg-confirm').value;
if (password !== confirm) return alert('Passwords do not match');
const data = {
cnic: document.getElementById('reg-cnic').value,
name: document.getElementById('reg-name').value,
email: document.getElementById('reg-email').value,
password,
dob: document.getElementById('reg-dob').value,
fatherName: document.getElementById('reg-father').value
};
try {
const res = await fetch('/api/register/voter', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await res.json();
if (res.ok) {
alert('Registration successful! Please login.');
showAuth();
} else {
alert(result.error || 'Registration failed');
}
} catch (err) {
alert('Error: ' + err.message);
}
});
// Admin registration
document.getElementById('admin-register-form').addEventListener('submit', async (e) => {
e.preventDefault();
const password = document.getElementById('admin-password').value;
const confirm = document.getElementById('admin-confirm').value;
if (password !== confirm) return alert('Passwords do not match');
const data = {
cnic: document.getElementById('admin-cnic').value,
name: document.getElementById('admin-name').value,
email: document.getElementById('admin-email').value,
password,
dob: document.getElementById('admin-dob').value,
fatherName: document.getElementById('admin-father').value,
secretKey: document.getElementById('admin-secret').value
};
try {
const res = await fetch('/api/register/admin', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await res.json();
if (res.ok) {
alert('Admin created! Please login.');
showAuth();
} else {
alert(result.error || 'Registration failed');
}
} catch (err) {
alert('Error: ' + err.message);
}
});
// Login
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('login-email').value;
const password = document.getElementById('login-password').value;
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await res.json();
if (res.ok) {
localStorage.setItem('token', data.token);
currentUser = { role: data.role };
if (data.role === 'admin') {
loadAdminDashboard();
} else {
loadVoterDashboard();
}
} else {
alert(data.error || 'Login failed');
}
} catch (err) {
alert('Error: ' + err.message);
}
});
// Logout
document.getElementById('logout-btn').addEventListener('click', () => {
localStorage.removeItem('token');
currentUser = null;
showAuth();
});
document.getElementById('admin-logout-btn').addEventListener('click', () => {
localStorage.removeItem('token');
currentUser = null;
showAuth();
});
// Voter Dashboard
async function loadVoterDashboard() {
document.getElementById('auth-section').classList.add('hidden');
document.getElementById('voter-dashboard').classList.remove('hidden');
const electionsDiv = document.getElementById('active-elections');
electionsDiv.innerHTML = 'Loading...';
try {
const token = localStorage.getItem('token');
const res = await fetch('/api/elections', {
headers: { 'Authorization': `Bearer ${token}` }
});
const elections = await res.json();
const active = elections.filter(e => e.status === 'running');
let html = '';
for (let election of active) {
const candidatesRes = await fetch(`/api/elections/${election._id}/candidates`);
const candidates = await candidatesRes.json();
html += `<div class="card"><h3>${election.title}</h3><div class="flex">`;
candidates.forEach(c => {
html += `<div class="candidate-card">
<div class="symbol">${c.partySymbol}</div>
<h4>${c.name}</h4>
<p>${c.partyName}</p>
<button class="vote-btn" data-candidate="${c._id}" data-election="${election._id}">Vote</button>
</div>`;
});
html += `</div><div class="chart-container"><canvas id="chart-${election._id}"></canvas></div></div>`;
}
electionsDiv.innerHTML = html || 'No active elections';
// Attach vote buttons
document.querySelectorAll('.vote-btn').forEach(btn => {
btn.addEventListener('click', async (e) => {
const candidateId = btn.dataset.candidate;
const electionId = btn.dataset.election;
if (confirm('Confirm your vote? This cannot be undone.')) {
try {
const res = await fetch('/api/vote', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ candidateId, electionId })
});
if (res.ok) {
alert('Vote cast successfully!');
} else {
const err = await res.json();
alert(err.error);
}
} catch (err) {
alert(err.message);
}
}
});
});
// Setup charts for each election
active.forEach(election => {
fetch(`/api/elections/${election._id}/results`)
.then(res => res.json())
.then(candidates => {
const ctx = document.getElementById(`chart-${election._id}`).getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: candidates.map(c => c.name),
datasets: [{
label: 'Votes',
data: candidates.map(c => c.voteCount),
backgroundColor: 'rgba(102,126,234,0.5)'
}]
}
});
});
});
// Socket listeners for real-time updates
active.forEach(e => {
socket.emit('join-election', e._id);
});
} catch (err) {
electionsDiv.innerHTML = 'Error loading elections';
}
}
// Admin Dashboard
async function loadAdminDashboard() {
document.getElementById('auth-section').classList.add('hidden');
document.getElementById('admin-dashboard').classList.remove('hidden');
const token = localStorage.getItem('token');
// Load elections into selects
async function loadElectionSelects() {
const res = await fetch('/api/elections', { headers: { 'Authorization': `Bearer ${token}` } });
const elections = await res.json();
const selects = ['candidate-election', 'live-election-select', 'export-election'];
selects.forEach(id => {
const select = document.getElementById(id);
select.innerHTML = elections.map(e => `<option value="${e._id}">${e.title}</option>`).join('');
});
return elections;
}
// Create election
document.getElementById('create-election-form').addEventListener('submit', async (e) => {
e.preventDefault();
const title = document.getElementById('election-title').value;
const res = await fetch('/api/elections', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ title })
});
if (res.ok) {
alert('Election created');
loadElectionSelects();
loadElectionsList();
} else {
const err = await res.json();
alert(err.error);
}
});
// Add candidate
document.getElementById('add-candidate-form').addEventListener('submit', async (e) => {
e.preventDefault();
const electionId = document.getElementById('candidate-election').value;
const name = document.getElementById('candidate-name').value;
const partyName = document.getElementById('candidate-party').value;
const partySymbol = document.getElementById('candidate-symbol').value;
const res = await fetch(`/api/elections/${electionId}/candidates`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ name, partyName, partySymbol })
});
if (res.ok) {
alert('Candidate added');
} else {
const err = await res.json();
alert(err.error);
}
});
// Load elections list with controls
async function loadElectionsList() {
const res = await fetch('/api/elections', { headers: { 'Authorization': `Bearer ${token}` } });
const elections = await res.json();
let html = '<table><tr><th>Title</th><th>Status</th><th>Actions</th></tr>';
elections.forEach(e => {
html += `<tr>
<td>${e.title}</td>
<td>${e.status}</td>
<td>
<button onclick="updateElectionStatus('${e._id}', 'running')">Start</button>
<button onclick="updateElectionStatus('${e._id}', 'paused')">Pause</button>
<button onclick="updateElectionStatus('${e._id}', 'closed')">Close</button>
</td>
</tr>`;
});
html += '</table>';
document.getElementById('elections-list').innerHTML = html;
}
window.updateElectionStatus = async (id, status) => {
const res = await fetch(`/api/elections/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ status })
});
if (res.ok) {
loadElectionsList();
} else {
alert('Failed to update status');
}
};
// Live results chart
document.getElementById('live-election-select').addEventListener('change', async (e) => {
const electionId = e.target.value;
const res = await fetch(`/api/elections/${electionId}/results`);
const candidates = await res.json();
if (chart) chart.destroy();
const ctx = document.getElementById('results-chart').getContext('2d');
chart = new Chart(ctx, {
type: 'bar',
data: {
labels: candidates.map(c => c.name),
datasets: [{
label: 'Votes',
data: candidates.map(c => c.voteCount),
backgroundColor: 'rgba(102,126,234,0.5)'
}]
}
});
});
// Load voters
document.getElementById('load-voters').addEventListener('click', async () => {
const res = await fetch('/api/admin/voters', { headers: { 'Authorization': `Bearer ${token}` } });
const voters = await res.json();
let html = '<table><tr><th>CNIC</th><th>Name</th><th>Email</th><th>IP</th><th>Has Voted</th></tr>';
voters.forEach(v => {
html += `<tr>
<td>${v.cnic}</td>
<td>${v.name}</td>
<td>${v.email}</td>
<td>${v.deviceIp}</td>
<td>${v.hasVoted ? 'Yes' : 'No'}</td>
</tr>`;
});
html += '</table>';
document.getElementById('voters-table').innerHTML = html;
});
// Export PDF
document.getElementById('export-pdf').addEventListener('click', () => {
const electionId = document.getElementById('export-election').value;
window.open(`/api/admin/export/${electionId}`, '_blank');
});
// Socket listeners for admin
socket.on('vote-update', (candidates) => {
// Update chart if current election matches
const electionId = document.getElementById('live-election-select').value;
if (candidates.length > 0 && candidates[0].electionId === electionId) {
chart.data.datasets[0].data = candidates.map(c => c.voteCount);
chart.update();
}
});
socket.on('winner', (winner) => {
const modal = document.getElementById('winner-modal');
document.getElementById('winner-text').innerText = `Winner: ${winner.name} (${winner.partyName}) with ${winner.voteCount} votes!`;
modal.classList.remove('hidden');
setTimeout(() => modal.classList.add('hidden'), 5000);
});
socket.on('status-change', (election) => {
alert(`Election ${election.title} status changed to ${election.status}`);
loadElectionsList();
});
// Initial load
await loadElectionSelects();
loadElectionsList();
}
// Check if already logged in on page load
(async function init() {
const token = localStorage.getItem('token');
if (token) {
try {
// Decode token to get role (simple, no verification)
const payload = JSON.parse(atob(token.split('.')[1]));
currentUser = { role: payload.role };
if (payload.role === 'admin') {
loadAdminDashboard();
} else {
loadVoterDashboard();
}
} catch {
showAuth();
}
} else {
showAuth();
}
})();
</script>
</body>
</html>