-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
591 lines (516 loc) · 18.7 KB
/
server.js
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
const express = require("express");
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
const bcrypt = require("bcrypt") //importing bcrypt hash
const LocalStrategy = require("passport-local").Strategy
const saltRounds = 10;
const bodyParser = require('body-parser');
const crypto = require('crypto');
const nodemailer = require('nodemailer');
const randomstring = require('randomstring');
require('dotenv').config();
const ejs = require('ejs');
const session = require('cookie-session');
var tokenExpiration = 60 * 1000;
var tokens = {};
const port = process.env.PORT || 4000;
app.use(session({
secret: 'your secret key',
resave: false,
saveUninitialized: true,
cookie: { secure: false,maxAge: 24 * 60 * 60 * 1000 }
}));
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD
}
});
app.set('view engine', 'ejs');
const mysql = require("mysql");
const connection = mysql.createConnection({
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
});
app.use(bodyParser.json());
app.use(express.urlencoded({extended: false}))
app.use(bodyParser.urlencoded({extended: true}));
var PW = generateRandomPassword(10);
app.post('/adminlogout', (req, res) => {
delete req.session.isAuthenticated;
delete req.session.user;
res.redirect('/');
});
app.post("/register", function(req, res) {
var firstname = req.body.f_name;
var middlename = req.body.m_name;
var lastname = req.body.l_name;
var NID = req.body.nid;
var emaill = req.body.email;
var PN = req.body.phone;
console.log('Pass:',PW);
// Check if NID exists in nidcheck vanni table ma //tannai nid haru store huncha
var sql_check = `SELECT * FROM sql12615458.nidcheck WHERE national_id='${NID}'`;
connection.query(sql_check, function(error, result) {
if (error) throw error;
if (result.length > 0) {
var sql = `INSERT INTO sql12615458.verified_users(NID, PH_NO) VALUES('${NID}', '${PN}')`;
connection.query(sql, function(error, result) {
if (error) throw error;
console.log("verified.");
});
// NID exists in other table, insert record in unauth_user table
bcrypt.hash(PW, saltRounds, function(err, hash) {
if (err) throw err;
var sql_insert = `INSERT INTO sql12615458.unauth_user(first_name, middle_name, last_name, national_id, email, phone_number, password) VALUES('${firstname}', '${middlename}', '${lastname}', '${NID}', '${emaill}', '${PN}', '${hash}')`;
connection.query(sql_insert, function(error, result) {
if (error) throw error;
res.redirect("/sregister");
console.log("success");
});
});
const mailOptions = {
from: '[email protected]',
to: emaill,
subject: 'E-voting security alert',
text: `Dear ${firstname},
We hope this email finds you well. As a user of E-voting site, we are writing to provide you with a new password to access the E-voting website. This password is needed for you to securely access through and use the features of the app.
Your password is as follows:
password : ${PW}
Please note that this password is automatically generated by our system.
Thank you for using E-voting.
Best regards,
E-voting Project
`
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.status(500).send('Error sending email');
} else {
console.log('Email sent: ' + info.response);
}
});
} else {
// NID does not exist in other table, user is not eligible to vote
res.redirect("/nregister");
}
});
});
app.post('/login', function(req, res) {
var nid = req.body.nid;
var email = req.body.Email;
var pass = req.body.password;
var secretKey = 'mySecretKey';
// 1 min in milliseconds
var tokenExpiration = 1 * 60 * 1000;
var token;
var sql = `SELECT * FROM sql12615458.unauth_user WHERE national_id = '${nid}' AND email = '${email}'`;
connection.query(sql, function(error, results) {
if (error) throw error;
if (results.length > 0) {
var hash = results[0].password;
bcrypt.compare(pass, hash, function(err, match) {
if (err) throw err;
if (match) {
// Passwords match
console.log(match);
// Check if user has already voted
var votedSql = `SELECT * FROM sql12615458.votedperson WHERE national_id = '${nid}'`;
connection.query(votedSql, function(error, results) {
if (error) throw error;
if (results.length > 0) {
// User has already voted
res.redirect("/alreadyvoted");
} else {
// User has not voted yet
// Insert user into active poll list
var activePollSql = `INSERT INTO sql12615458.active_poll_list (national_id) VALUES ('${nid}')`;
connection.query(activePollSql, function(error, results) {
if (error) throw error;
// Generate a token with a timestamp
var timestamp = Date.now();
token = nid + secretKey + randomstring.generate(10) + timestamp;
// Send email with unique link to voting page
var mailOptions = {
from: '[email protected]',
to: email,
subject: 'Your unique link to the voting page',
html: `<p>Hi there,</p><p>Please use the following link to access your voting page:</p><p><a href="https://evoting2080.onrender.com/vote/${token}"><b>https://evoting2080.onrender.com/vote/${token}/</b></a></p>`
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
// Set a timeout to delete the token after it expires
setTimeout(function() {
delete tokens[token];
}, tokenExpiration);
res.redirect("/loggedin");
console.log("logged in");
});
}
});
} else {
// Passwords don't match
res.redirect("/incorrect");
}
});
} else {
res.redirect("/incorrect");
}
});
});
app.post('/verify', function(req,res)
{
var nid = req.body.nid;
var ph = req.body.phone;
connection.query(function(error)
{
var sql = `SELECT * FROM sql12615458.verified_users WHERE NID = '${nid}' AND PH_NO = '${ph}' `;
connection.query(sql,function(error,result)
{
if (error)
{
throw error;
}
else if(result.length > 0)
{
res.redirect("/yverify");
}
else
{
res.redirect("/nverify");
}
res.end();
});
});
})
/*app.post("/register", async (req, res) => {
try
{
//For hashed password and info
const hashedPassword = await bcrypt.hash(req.body.password)
users.push({
id: Date.now().toString(),
fname: req.body.f_name,
mname: req.body.m_name,
lname: req.body.l_name,
nid: req.body.nid,
email: req.body.email,
phone: req.body.phone
})
res.redirect("/")
}
catch(e)
{
console.log(e);
res.redirect("/register")
}
})*/
//routes
app.use("/css", express.static("css"));
app.use("/img", express.static("img"));
app.use("/js", express.static("js"));
app.use("/uploads", express.static("uploads"));
app.get('/', (req, res) => {
// Render the index.ejs file and pass in the session variable
res.render('index', { session: req.session });
});
app.get('/login', (req,res) => {
res.render("login.ejs")
})
app.get('/register', (req,res) => {
res.render("register.ejs")
})
app.get('/result', (req, res) => {
const sql = `SELECT candidate, role, COUNT(*) AS count FROM (
SELECT president AS candidate, 'president' AS role FROM sql12615458.voted_list
UNION ALL
SELECT vicepresident AS candidate, 'vice president' AS role FROM sql12615458.voted_list
UNION ALL
SELECT mayor AS candidate, 'mayor' AS role FROM sql12615458.voted_list
UNION ALL
SELECT member AS candidate, 'member' AS role FROM sql12615458.voted_list
) AS candidates
GROUP BY candidate, role ORDER BY role, count DESC`;
connection.query(sql, (error, results) => {
if (error) {
console.error('Error retrieving votes from MySQL database:', error);
res.sendStatus(500);
} else {
console.log('Votes retrieved from MySQL database!');
const presidentResults = results.filter(result => result.role === 'president');
const vicePresidentResults = results.filter(result => result.role === 'vice president');
const mayorResults = results.filter(result => result.role === 'mayor');
const memberResults = results.filter(result => result.role === 'member');
res.render('result', { presidentResults, vicePresidentResults, mayorResults, memberResults });
}
});
});
app.get('/loggedin', (req,res) => {
res.render("loggedin.ejs")
})
app.get('/aboutus', (req,res) => {
res.render("aboutus.ejs")
})
app.get('/contactus', (req,res) => {
res.render("contactus.ejs")
})
app.get('/remember', (req,res) => {
res.render("for_pass.ejs")
})
app.get('/verify', (req,res) => {
res.render("verify.ejs")
})
app.get('/yverify', (req,res) => {
res.render("verified.ejs")
})
app.get('/invalidtoken', (req,res) => {
res.render("tokenexpired.ejs")
})
app.get('/nverify', (req,res) => {
res.render("not_verified.ejs")
})
app.get('/sregister', (req,res) => {
res.render("registered.ejs")
})
app.get('/howtovote', (req,res) => {
res.render("howtovote.ejs")
})
app.get('/adminpage', (req, res) => {
// check if the user is authenticated and has the admin role
if (!req.session.isAuthenticated || req.session.user.role !== 'admin') {
// if not, redirect to the login page
return res.redirect('/adminlogin');
}
// if yes, render the admin page
res.render('adminpage.ejs');
});
app.get('/adminlogin', (req,res) => {
res.render("admin_login.ejs")
})
app.get('/nregister', (req,res) => {
res.render("nregistered.ejs")
})
app.get('/incorrect', (req,res) => {
res.render("incorrectpassword.ejs")
})
app.get('/alreadyvoted', (req,res) => {
res.render("alreadyvoted.ejs")
})
app.get('/aftervoted', (req,res) => {
res.render("aftervoted.ejs")
})
// voting page route
// vote route
app.get('/vote/:token', function(req, res) {
// define variables in outer scope
let candidates;
let viceCandidates;
let mayorCandidates;
let memberCandidates;
// retrieve presidential candidates from MySQL database
connection.query('SELECT * FROM candidates WHERE position = "president"', (err, rows, fields) => {
if (err) throw err;
candidates = rows;
// retrieve vice presidential candidates from MySQL database
connection.query('SELECT * FROM candidates WHERE position = "vicepresident"', (err, rows, fields) => {
if (err) throw err;
viceCandidates = rows;
// retrieve mayor candidates from MySQL database
connection.query('SELECT * FROM candidates WHERE position = "mayor"', (err, rows, fields) => {
if (err) throw err;
mayorCandidates = rows;
// retrieve member candidates from MySQL database
connection.query('SELECT * FROM candidates WHERE position = "member"', (err, rows, fields) => {
if (err) throw err;
memberCandidates = rows;
// get token and nid from request parameters
var token = req.params.token;
var secretKey = 'mySecretKey';
var nid = token.slice(0, -secretKey.length - 23);
// check if token is valid and render voting page
if (isValidToken(token)) {
const sql3 = 'INSERT INTO sql12615458.votedperson (national_id) VALUES (?)';
const values3 = [nid];
connection.query(sql3, values3, (error3, result3) => {
if(error3){console.error('error:',error3)}
});
res.render('votingpage.ejs', {
token: token,
nid: nid,
candidates: candidates,
viceCandidates: viceCandidates,
mayorCandidates: mayorCandidates,
memberCandidates: memberCandidates
});
} else {
res.redirect('/invalidtoken');
}
});
});
});
});
});
app.post('/insert', upload.single('image'), (req, res) => {
const { name, position, party } = req.body;
const imagePath = req.file ? req.file.path : null;
connection.query('INSERT INTO candidates (name, position, party, image) VALUES (?, ?, ?, ?)', [name, position, party, imagePath], (err, result) => {
if (err) throw err;
console.log('New candidate added to database');
res.redirect('/adminpage');
});
});
app.post('/cdelete', (req, res) => {
connection.query('DELETE FROM candidates', (err, result) => {
if (err) throw err;
console.log('All candidates deleted from database');
res.redirect('/adminpage');
});
});
app.post('/vdelete', (req, res) => {
connection.query('DELETE FROM votedperson', (err, result) => {
if (err) throw err;
console.log('All votedperson nid deleted from database');
});
connection.query('DELETE FROM voted_list', (err, result) => {
if (err) throw err;
console.log('All votedlist data deleted from database');
});
res.redirect('/adminpage');
});
app.post('/udelete', (req, res) => {
connection.query('DELETE FROM unauth_user', (err, result) => {
if (err) throw err;
console.log('All user data deleted from database');
});
connection.query('DELETE FROM verified_users', (err, result) => {
if (err) throw err;
console.log('All verified user data deleted from database');
});
res.redirect('/adminpage');
});
app.post('/vote/:token', (req, res) => {
const nid = req.body.nid;
const president = req.body.president;
const vicepresident = req.body.vicepresident;
const mayor = req.body.mayor;
const member = req.body.member;
bcrypt.hash(nid, saltRounds, function(err, hashedNid) {
const sql = 'INSERT INTO sql12615458.voted_list (national_id,president, vicepresident,mayor,member) VALUES (?, ?, ?, ?, ?)';
const values = [hashedNid,president, vicepresident,mayor,member];
connection.query(sql, values, (error, result) => {
if (error) {
console.error('Error inserting vote into MySQL database:', error);
res.sendStatus(500);
} else {
const sql2 = 'DELETE FROM sql12615458.active_poll_list WHERE national_id = ?';
const values2 = [nid];
connection.query(sql2, values2, (error2, result2) => {
if (error2) {
console.error('Error deleting user from active poll list:', error2);
} else {
console.log('User deleted from active poll list');
}
});
console.log('Vote inserted into MySQL database!');
res.redirect('/aftervoted');
}
});
});
});
app.post('/adminlogin', function(req, res) {
const { u_name, p_name } = req.body;
const sql = `SELECT * FROM adminlogin WHERE username = ? AND password = ?`;
const values = [u_name, p_name];
connection.query(sql, values, function(err, result) {
if (err) throw err;
if (result.length > 0) {
// Login successful
req.session.isAuthenticated = true;
req.session.user = { u_name, role: 'admin' };
res.redirect('/adminpage');
} else {
// Login failed
res.redirect('/incorrect');
}
});
});
// app.post('/admin/pushresult', (req, res) => {
// // Toggle the session variable to show or hide the button
// req.session.showNavButton = !req.session.showNavButton;
// // Redirect back to the admin page
// res.redirect('/adminpage');
// });
app.post('/publish', (req, res) => {
var r = 1;
var id=1;
var sql = `UPDATE sql12615458.publish_result SET resval='${r}' WHERE ID='${id}'`;
connection.query(sql, [r, id] ,function(error,result)
{
if (error)
{
console.log(error);
res.redirect('/adminpage');
}
else
{
res.redirect('/adminpage');
}
});
});
app.post('/extract', (req, res) => {
var r =0;
var id=1;
var sql = `UPDATE sql12615458.publish_result SET resval='${r}' WHERE ID='${id}'`;
connection.query(sql, [r, id] ,function(error,result)
{
if (error)
{
console.log(error);
res.redirect('/adminpage');
}
else
{
res.redirect('/adminpage');
}
});
});
app.get('/count', (req, res) => {
var re = 1;
var id = 1;
var sql = `SELECT * FROM sql12615458.publish_result WHERE resval = '${re}' AND ID = '${id}'`;
connection.query(sql, function (error, result) {
if (result && result.length > 0) { // Check if the result array has at least one element
res.json({ redirect: '/result' }); // Return a JSON response with a redirect property
} else {
res.json({ redirect: '/noresult' }); // Return a JSON response with a redirect property
}
});
});
app.get('/noresult', (req,res) => {
res.render("noresult.ejs")
})
//end routes
function isValidToken(token) {
var timestamp = token.substring(token.length - 13);
var expiration = parseInt(timestamp) + tokenExpiration;
return Date.now() < expiration;
}
function generateRandomPassword(length) {
return crypto.randomBytes(Math.ceil(length/2))
.toString('hex')
.slice(0,length);
}
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});