-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
300 lines (256 loc) · 8.59 KB
/
Copy pathserver.js
File metadata and controls
300 lines (256 loc) · 8.59 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
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Data file paths
const votersFile = path.join(__dirname, 'data', 'voters.json');
const candidatesFile = path.join(__dirname, 'data', 'candidates.json');
// Helper functions to read/write JSON files
const readJSON = (filePath) => {
try {
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error(`Error reading ${filePath}:`, error);
return null;
}
};
const writeJSON = (filePath, data) => {
try {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
return true;
} catch (error) {
console.error(`Error writing ${filePath}:`, error);
return false;
}
};
// ==================== API ROUTES ====================
/**
* POST /api/login
* Validate Voter ID and check if already voted
* Body: { voterId: string }
*/
app.post('/api/login', (req, res) => {
const { voterId } = req.body;
if (!voterId || voterId.trim() === '') {
return res.status(400).json({
success: false,
message: 'Please enter a valid Voter ID'
});
}
const votersData = readJSON(votersFile);
if (!votersData) {
return res.status(500).json({
success: false,
message: 'Server error: Unable to read voter database'
});
}
// Find the voter
const voter = votersData.voters.find(
v => v.voterId.toUpperCase() === voterId.toUpperCase().trim()
);
if (!voter) {
return res.status(404).json({
success: false,
message: 'Invalid Voter ID. Please check and try again.'
});
}
if (voter.hasVoted) {
return res.status(403).json({
success: false,
message: 'You have already voted. Each voter can only vote once.'
});
}
// Login successful
res.json({
success: true,
message: 'Login successful',
voter: {
voterId: voter.voterId,
name: voter.name
}
});
});
/**
* GET /api/candidates
* Get list of all candidates
*/
app.get('/api/candidates', (req, res) => {
const candidatesData = readJSON(candidatesFile);
if (!candidatesData) {
return res.status(500).json({
success: false,
message: 'Server error: Unable to read candidates database'
});
}
// Return candidates without vote counts (for security)
const candidates = candidatesData.candidates.map(c => ({
id: c.id,
name: c.name,
party: c.party,
symbol: c.symbol
}));
res.json({
success: true,
candidates
});
});
/**
* POST /api/vote
* Cast a vote for a candidate
* Body: { voterId: string, candidateId: number }
*/
app.post('/api/vote', (req, res) => {
const { voterId, candidateId } = req.body;
if (!voterId || !candidateId) {
return res.status(400).json({
success: false,
message: 'Invalid request: Voter ID and Candidate ID are required'
});
}
// Read current data
const votersData = readJSON(votersFile);
const candidatesData = readJSON(candidatesFile);
if (!votersData || !candidatesData) {
return res.status(500).json({
success: false,
message: 'Server error: Unable to read database'
});
}
// Find the voter
const voterIndex = votersData.voters.findIndex(
v => v.voterId.toUpperCase() === voterId.toUpperCase().trim()
);
if (voterIndex === -1) {
return res.status(404).json({
success: false,
message: 'Invalid Voter ID'
});
}
if (votersData.voters[voterIndex].hasVoted) {
return res.status(403).json({
success: false,
message: 'You have already voted. Each voter can only vote once.'
});
}
// Find the candidate
const candidateIndex = candidatesData.candidates.findIndex(
c => c.id === parseInt(candidateId)
);
if (candidateIndex === -1) {
return res.status(404).json({
success: false,
message: 'Invalid Candidate ID'
});
}
// Record the vote
votersData.voters[voterIndex].hasVoted = true;
candidatesData.candidates[candidateIndex].votes += 1;
// Save updated data
const votersSaved = writeJSON(votersFile, votersData);
const candidatesSaved = writeJSON(candidatesFile, candidatesData);
if (!votersSaved || !candidatesSaved) {
return res.status(500).json({
success: false,
message: 'Server error: Unable to save vote'
});
}
res.json({
success: true,
message: 'Your vote has been recorded successfully!',
candidateName: candidatesData.candidates[candidateIndex].name
});
});
/**
* GET /api/check-voted/:voterId
* Check if a voter has already voted
*/
app.get('/api/check-voted/:voterId', (req, res) => {
const { voterId } = req.params;
const votersData = readJSON(votersFile);
if (!votersData) {
return res.status(500).json({
success: false,
message: 'Server error: Unable to read voter database'
});
}
const voter = votersData.voters.find(
v => v.voterId.toUpperCase() === voterId.toUpperCase().trim()
);
if (!voter) {
return res.status(404).json({
success: false,
message: 'Voter not found'
});
}
res.json({
success: true,
hasVoted: voter.hasVoted
});
});
/**
* GET /api/results
* Get current vote counts (Admin only - for demo purposes)
*/
app.get('/api/results', (req, res) => {
const candidatesData = readJSON(candidatesFile);
if (!candidatesData) {
return res.status(500).json({
success: false,
message: 'Server error: Unable to read candidates database'
});
}
const totalVotes = candidatesData.candidates.reduce((sum, c) => sum + c.votes, 0);
res.json({
success: true,
totalVotes,
results: candidatesData.candidates.map(c => ({
id: c.id,
name: c.name,
party: c.party,
symbol: c.symbol,
votes: c.votes,
percentage: totalVotes > 0 ? ((c.votes / totalVotes) * 100).toFixed(2) : 0
}))
});
});
// ==================== SERVE HTML PAGES ====================
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/ballot', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'ballot.html'));
});
app.get('/thankyou', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'thankyou.html'));
});
app.get('/results', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'results.html'));
});
// ==================== START SERVER ====================
app.listen(PORT, () => {
console.log(`
╔═══════════════════════════════════════════════════════════╗
║ ║
║ 🗳️ ONLINE VOTING SYSTEM - SERVER RUNNING 🗳️ ║
║ ║
╠═══════════════════════════════════════════════════════════╣
║ ║
║ Server is running on: http://localhost:${PORT} ║
║ ║
║ Available Pages: ║
║ • Login: http://localhost:${PORT}/ ║
║ • Ballot: http://localhost:${PORT}/ballot ║
║ • Results: http://localhost:${PORT}/results ║
║ ║
║ Sample Voter IDs: VOTER001 to VOTER010 ║
║ ║
╚═══════════════════════════════════════════════════════════╝
`);
});