-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlive.js
More file actions
367 lines (318 loc) · 12.8 KB
/
live.js
File metadata and controls
367 lines (318 loc) · 12.8 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
// live.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const path = require('path');
const PDFDocument = require('pdfkit');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, { cors: { origin: '*' } });
// Environment variables
const PORT = process.env.PORT || 5000;
const MONGO_URI = process.env.MONGO_URI || 'mongodb+srv://urao57726_db_user:NPVIiDzfC1xuwyll@votelive.xtkvegn.mongodb.net/votelive';
const JWT_SECRET = process.env.JWT_SECRET || 'NPVIiDzfC1xuwyll';
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname))); // Serve static files (index.html)
// MongoDB connection
mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));
// Schemas
const voterSchema = new mongoose.Schema({
cnic: { type: String, unique: true, required: true },
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
dob: { type: Date, required: true },
fatherName: { type: String, required: true },
deviceIp: { type: String },
hasVoted: { type: Boolean, default: false },
role: { type: String, enum: ['voter', 'admin'], default: 'voter' }
});
const electionSchema = new mongoose.Schema({
title: { type: String, unique: true, required: true },
status: { type: String, enum: ['pending', 'running', 'paused', 'closed'], default: 'pending' },
startTime: { type: Date },
endTime: { type: Date }
});
const candidateSchema = new mongoose.Schema({
electionId: { type: mongoose.Schema.Types.ObjectId, ref: 'Election', required: true },
name: { type: String, required: true },
partyName: { type: String, required: true },
partySymbol: { type: String, required: true }, // URL or emoji? We'll store as text
voteCount: { type: Number, default: 0 }
});
const voteSchema = new mongoose.Schema({
voterId: { type: mongoose.Schema.Types.ObjectId, ref: 'Voter', required: true },
candidateId: { type: mongoose.Schema.Types.ObjectId, ref: 'Candidate', required: true },
electionId: { type: mongoose.Schema.Types.ObjectId, ref: 'Election', required: true },
timestamp: { type: Date, default: Date.now },
deviceIp: { type: String }
});
const Voter = mongoose.model('Voter', voterSchema);
const Election = mongoose.model('Election', electionSchema);
const Candidate = mongoose.model('Candidate', candidateSchema);
const Vote = mongoose.model('Vote', voteSchema);
// Helper: get client IP
const getClientIp = (req) => req.headers['x-forwarded-for'] || req.socket.remoteAddress;
// Middleware: authenticate token
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// Middleware: admin only
const adminOnly = (req, res, next) => {
if (req.user.role !== 'admin') return res.sendStatus(403);
next();
};
// Socket.io
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('join-election', (electionId) => {
socket.join(`election-${electionId}`);
});
socket.on('disconnect', () => console.log('Client disconnected'));
});
// API Routes
// Register voter
app.post('/api/register/voter', async (req, res) => {
try {
const { cnic, name, email, password, dob, fatherName } = req.body;
// Validate CNIC format (simple regex)
if (!/^\d{5}-\d{7}-\d$/.test(cnic)) {
return res.status(400).json({ error: 'Invalid CNIC format. Use XXXXX-XXXXXXX-X' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const voter = new Voter({
cnic,
name,
email,
password: hashedPassword,
dob,
fatherName,
deviceIp: getClientIp(req)
});
await voter.save();
res.status(201).json({ message: 'Voter registered successfully' });
} catch (err) {
if (err.code === 11000) return res.status(400).json({ error: 'CNIC or email already exists' });
res.status(500).json({ error: err.message });
}
});
// Register admin (first admin only)
app.post('/api/register/admin', async (req, res) => {
try {
const { cnic, name, email, password, dob, fatherName, secretKey } = req.body;
if (secretKey !== '123456admin2026') {
return res.status(403).json({ error: 'Invalid secret key' });
}
// Check if any admin exists
const existingAdmin = await Voter.findOne({ role: 'admin' });
if (existingAdmin) {
return res.status(403).json({ error: 'Admin already exists' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const admin = new Voter({
cnic,
name,
email,
password: hashedPassword,
dob,
fatherName,
deviceIp: getClientIp(req),
role: 'admin'
});
await admin.save();
res.status(201).json({ message: 'Admin registered successfully' });
} catch (err) {
if (err.code === 11000) return res.status(400).json({ error: 'CNIC or email already exists' });
res.status(500).json({ error: err.message });
}
});
// Login
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body;
const user = await Voter.findOne({ email });
if (!user) return res.status(401).json({ error: 'Invalid email or password' });
const valid = await bcrypt.compare(password, user.password);
if (!valid) return res.status(401).json({ error: 'Invalid email or password' });
const token = jwt.sign(
{ id: user._id, email: user.email, role: user.role },
JWT_SECRET,
{ expiresIn: '1d' }
);
res.json({ token, role: user.role });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get all elections (public)
app.get('/api/elections', async (req, res) => {
try {
const elections = await Election.find();
res.json(elections);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Create election (admin only)
app.post('/api/elections', authenticateToken, adminOnly, async (req, res) => {
try {
const { title } = req.body;
const election = new Election({ title });
await election.save();
res.status(201).json(election);
} catch (err) {
if (err.code === 11000) return res.status(400).json({ error: 'Election title must be unique' });
res.status(500).json({ error: err.message });
}
});
// Update election status (admin only)
app.put('/api/elections/:id', authenticateToken, adminOnly, async (req, res) => {
try {
const { status } = req.body;
const election = await Election.findByIdAndUpdate(
req.params.id,
{ status, ...(status === 'running' ? { startTime: new Date() } : {}), ...(status === 'closed' ? { endTime: new Date() } : {}) },
{ new: true }
);
if (!election) return res.status(404).json({ error: 'Election not found' });
// Emit status change
io.to(`election-${election._id}`).emit('status-change', election);
// If closed, compute winner and emit
if (status === 'closed') {
const candidates = await Candidate.find({ electionId: election._id }).sort({ voteCount: -1 });
const winner = candidates.length > 0 ? candidates[0] : null;
io.to(`election-${election._id}`).emit('winner', winner);
}
res.json(election);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get candidates for an election
app.get('/api/elections/:id/candidates', async (req, res) => {
try {
const candidates = await Candidate.find({ electionId: req.params.id });
res.json(candidates);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Add candidate (admin only)
app.post('/api/elections/:id/candidates', authenticateToken, adminOnly, async (req, res) => {
try {
const { name, partyName, partySymbol } = req.body;
const candidate = new Candidate({
electionId: req.params.id,
name,
partyName,
partySymbol
});
await candidate.save();
res.status(201).json(candidate);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Cast vote (voter only)
app.post('/api/vote', authenticateToken, async (req, res) => {
try {
const { candidateId, electionId } = req.body;
const voterId = req.user.id;
const deviceIp = getClientIp(req);
// Check if voter exists and role is voter
const voter = await Voter.findById(voterId);
if (!voter || voter.role !== 'voter') return res.status(403).json({ error: 'Not authorized to vote' });
// Check if election is running
const election = await Election.findById(electionId);
if (!election || election.status !== 'running') return res.status(400).json({ error: 'Election is not running' });
// Check if already voted in this election
const existingVote = await Vote.findOne({ voterId, electionId });
if (existingVote) return res.status(400).json({ error: 'Already voted in this election' });
// Check if same device already voted in this election (additional check)
const deviceVote = await Vote.findOne({ electionId, deviceIp });
if (deviceVote) return res.status(400).json({ error: 'This device has already voted in this election' });
// Record vote
const vote = new Vote({ voterId, candidateId, electionId, deviceIp });
await vote.save();
// Increment candidate vote count
await Candidate.findByIdAndUpdate(candidateId, { $inc: { voteCount: 1 } });
// Update voter hasVoted flag
await Voter.findByIdAndUpdate(voterId, { hasVoted: true });
// Get updated candidate list
const updatedCandidates = await Candidate.find({ electionId });
io.to(`election-${electionId}`).emit('vote-update', updatedCandidates);
res.status(201).json({ message: 'Vote cast successfully' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get results (candidates with vote counts)
app.get('/api/elections/:id/results', async (req, res) => {
try {
const candidates = await Candidate.find({ electionId: req.params.id });
res.json(candidates);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Admin: get all voters with IPs
app.get('/api/admin/voters', authenticateToken, adminOnly, async (req, res) => {
try {
const voters = await Voter.find({}, '-password'); // Exclude password
res.json(voters);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Admin: export votes for an election as PDF
app.get('/api/admin/export/:electionId', authenticateToken, adminOnly, async (req, res) => {
try {
const election = await Election.findById(req.params.electionId);
if (!election) return res.status(404).json({ error: 'Election not found' });
const candidates = await Candidate.find({ electionId: req.params.electionId }).sort({ voteCount: -1 });
const votes = await Vote.find({ electionId: req.params.electionId }).populate('voterId', 'name cnic deviceIp');
// Create PDF
const doc = new PDFDocument();
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename=election-${req.params.electionId}.pdf`);
doc.pipe(res);
doc.fontSize(20).text(`Election: ${election.title}`, { align: 'center' });
doc.moveDown();
doc.fontSize(14).text(`Status: ${election.status}`);
doc.text(`Start: ${election.startTime || 'N/A'}`);
doc.text(`End: ${election.endTime || 'N/A'}`);
doc.moveDown();
doc.fontSize(16).text('Results', { underline: true });
candidates.forEach(c => {
doc.fontSize(12).text(`${c.name} (${c.partyName}): ${c.voteCount} votes`);
});
doc.moveDown();
doc.fontSize(16).text('Voter Details', { underline: true });
votes.forEach(v => {
doc.fontSize(10).text(`${v.voterId.name} (${v.voterId.cnic}) - IP: ${v.deviceIp} - Time: ${v.timestamp}`);
});
doc.end();
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Serve index.html for any other route (SPA fallback)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));