This repository has been archived by the owner on Jun 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
447 lines (343 loc) · 12.5 KB
/
main.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
"use strict"
const express = require('express');
const mustache = require('mustache-express');
const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');
const SERVER_PORT = 3000;
const NB_OF_QUESTIONS = 3; // Number of questions users have to answer. /!\ IF > number of questions in database, it will freeze when generates a question.
const POINTS_TO_BE_PREMIUM = 100; // Points needed to be premium
const db = require('./db')
const utils = require('./utils');
const app = express();
app.engine('html', mustache());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieSession({ secret: Math.floor(Math.random()*100).toString() }));
app.set('view engine', 'html');
app.set('views', './public_html');
// MIDDLEWARES
function alreadyAuthenticated(req, res, next) {
if (req.session.username !== undefined)
return res.redirect('/home');
return next();
}
function isAuthenticated(req, res, next) {
if (req.session.username !== undefined) {
res.locals.username = req.session.username;
res.locals.isAdmin = req.session.isAdmin;
res.locals.isPremium = req.session.isPremium;
res.locals.connected = true;
return next();
}
res.redirect('/login');
}
function isInQuestionSession(req, res, next) {
if (req.session.inQuestionSession !== undefined)
return next();
res.redirect('/home/');
}
function isPremium(req, res, next) {
if (req.session.isPremium)
return next();
res.redirect('/error/403');
}
function isAdmin(req, res, next) {
if (req.session.isAdmin)
return next();
res.redirect('/error/404'); // To hide to non-admin users admin pages
}
// ROUTES
app.get('/', alreadyAuthenticated, (req, res) => {
res.render('index');
});
app.get('/login', alreadyAuthenticated, (req, res) => {
let error = req.query.error;
if (error == 1) res.locals.error1 = true;
if (error == 2) res.locals.error2 = true;
res.render('login');
});
app.get('/register', alreadyAuthenticated, (req, res) => {
let error = req.query.error;
if (error == 1) res.locals.error1 = true;
if (error == 2) res.locals.error2 = true;
res.render('register');
});
app.post('/login', alreadyAuthenticated, (req, res) => {
let username = req.body.username;
let password = req.body.password;
if (username == "" || password == "")
return res.redirect('/login?error=1');
else if (!db.login(username, password))
return res.redirect('/login?error=2');
req.session.username = username;
req.session.points = db.getPoints(username);
if (req.session.points == null) req.session.points = 0;
req.session.isAdmin = db.isAdmin(username);
req.session.isPremium = db.isPremium(username);
res.redirect('/home/');
});
app.post('/register', alreadyAuthenticated, (req, res) => {
let username = req.body.username;
let password = req.body.password;
let email = req.body.email;
if (username == "" || password == "" || email == "")
return res.redirect('/register?error=1');
if (!db.register(username, password, email))
return res.redirect('/register?error=2');
req.session.username = username;
req.session.points = db.getPoints(username);
req.session.isAdmin = db.isAdmin(username);
req.session.isPremium = db.isPremium(username);
res.redirect('/home/');
});
// AUTHENTICATION REQUIRED UNTIL HERE
app.get('/home/', isAuthenticated, (req, res) => {
let data = {
points: req.session.points
};
res.render('home/index', data);
});
app.get('/home/disconnect', isAuthenticated, (req, res) => {
req.session = undefined;
res.redirect('/');
});
// QUESTIONS
app.get('/home/startQuestions', isAuthenticated, (req, res) => {
if (req.session.inQuestionSession !== undefined)
return res.redirect('/home/q');
req.session.inQuestionSession = true;
req.session.idQuestionsDone = [];
req.session.actualIDQuestion = utils.getRandomInt(db.getNbOfQuestions())+1;
res.redirect('/home/q');
});
app.get('/home/q', isAuthenticated, isInQuestionSession, (req, res) => {
let questionResult = db.getQuestion(req.session.actualIDQuestion);
/*
QUESTION OBJECT :
question.id,
question.title,
question.creator,
question.creationDate <- (timestamp),
question.listIDAnswers <- (must be splitted by ','),
question.idCorrectAnswer
*/
let answersString = questionResult.listIDAnswers.split(',');
let answersArray = [];
answersString.forEach(idAnswer => {
answersArray.push(db.getAnswer(idAnswer));
});
/*
ANSWER OBJECT :
answer.id,
answer.content
*/
let data = {
question: questionResult,
answers: answersArray
}
res.render('home/question', data);
});
app.get('/home/a', isAuthenticated, isInQuestionSession, (req, res) => {
req.session.idQuestionsDone.push(req.session.actualIDQuestion); // ADDING ACTUAL QUESTION
if (db.isGoodAnswer(req.session.actualIDQuestion, req.query.id)) // req.query.a = ID Answer
req.session.points += 1;
else
req.session.points -= 1;
if (req.session.idQuestionsDone.length >= NB_OF_QUESTIONS)
return res.redirect("endQuestions");
let nbOfQuestions = db.getNbOfQuestions();
do {
req.session.actualIDQuestion = utils.getRandomInt(nbOfQuestions)+1;
} while (req.session.idQuestionsDone.includes(req.session.actualIDQuestion)); // CONTINUE UNTIL FOUND QUESTION NOT ASKED BEFORE
res.redirect('/home/q');
});
app.get('/home/endQuestions', isAuthenticated, isInQuestionSession, (req, res) => {
let arrayQuestionsAsked = [];
let arrayAnswers = [];
if (req.session.points < 0) req.session.points = 0;
req.session.idQuestionsDone.forEach((id) => {
let question = db.getQuestion(id);
arrayQuestionsAsked.push(question);
arrayAnswers.push(db.getAnswer(question.idCorrectAnswer));
});
let data = {
oldPoints: db.getPoints(req.session.username),
newPoints: req.session.points,
questionsAsked: arrayQuestionsAsked,
goodAnswers: arrayAnswers
}
db.setPoints(req.session.username, req.session.points);
req.session.inQuestionSession = undefined;
req.session.idQuestionsDone = undefined;
if (!req.session.isPremium && req.session.points >= POINTS_TO_BE_PREMIUM) {
db.setPremium(req.session.username, "true");
data.nowPremium = true;
req.session.isPremium = true;
}
res.render('home/endQuestions', data);
});
// USER PROFILE SETTINGS
app.get('/home/profile', isAuthenticated, (req, res) => {
let data = db.getUser(req.session.username);
res.render('home/profile', data);
});
app.get('/home/profile/updateDescription', isAuthenticated, (req, res) => {
let data = {
userDescription: db.getUser(req.session.username).description
}
res.render('home/updateDescription', data);
});
app.post('/home/profile/updateDescription', isAuthenticated, (req, res) => {
let newDescription = req.body.description;
db.changeDescription(req.session.username, newDescription);
res.redirect('/home/profile');
});
app.get('/home/profile/changePassword', isAuthenticated, (req, res) => {
let data = {};
if (req.query.error == 1)
data.wrongPassword = true;
if (req.query.error == 2)
data.samePassword = true;
if (req.query.error == 3)
data.error1 == true;
if (req.query.success == 1)
data.success = true;
res.render('home/changePassword', data);
});
app.post('/home/profile/changePassword', isAuthenticated, (req, res) => {
let password = req.body.password;
let newPassword = req.body.newPassword;
if (password == undefined || newPassword == undefined)
return res.redirect('/home/profile/changePassword?error=3');
if (!db.login(req.session.username, password))
return res.redirect('/home/profile/changePassword?error=1');
if (password == newPassword)
return res.redirect('/home/profile/changePassword?error=2');
db.changePassword(req.session.username, newPassword);
// res.redirect('/home/changePassword?success=1');
res.redirect('/home/profile');
});
app.get('/home/profile/deleteProfile', isAuthenticated, (req, res) => {
let data = {};
if (req.query.error == 1)
data.wrongPassword = true;
if (req.query.error == 2)
data.notSamePassword = true;
if (req.query.error == 3)
data.error1 = true;
res.render('home/deleteProfile', data);
});
app.post('/home/profile/deleteProfile', isAuthenticated, (req, res) => { // Have to enter password to confirm deletion
let password = req.body.password;
let confirmPassword = req.body.confirmPassword;
if (password == undefined || confirmPassword == undefined)
return res.redirect('/home/profile/deleteProfile?error=3');
if (!db.login(req.session.username, password))
return res.redirect('/home/profile/deleteProfile?error=1');
if (password != confirmPassword)
return res.redirect('/home/profile/deleteProfile?error=2');
db.deleteUser(req.session.username);
req.session = undefined;
res.redirect('/');
});
// ADDING QUESTION
app.get('/home/addQuestion', isAuthenticated, isPremium, (req, res) => {
res.render('home/addQuestion');
});
app.post('/home/addQuestion', isAuthenticated, isPremium, (req, res) => {
let question = req.body.question;
let answers = [
req.body.firstAnswer,
req.body.secondAnswer,
req.body.thirdAnswer,
req.body.fourthAnswer
]
let goodAnswer = req.body.goodAnswer;
let answersID = [];
answers.forEach(answer => {
if (answer !== undefined)
answersID.push(db.addAnswer(answer));
});
if (answersID.length < 2)
return res.redirect('/home/addQuestion/answersError')
if (!(/^[1-4]$/.test(goodAnswer)) || goodAnswer > answersID.length)
return res.redirect('/home/addQuestion/idAnswerError');
db.addQuestion(question, req.session.username, utils.arrayToString(answersID), answersID[goodAnswer-1]);
res.redirect('/home/addQuestion/done');
});
app.get('/home/addQuestion/:status', isAuthenticated, isPremium, (req, res) => {
let status = req.params.status;
let data = {};
switch (status) {
case 'done':
data.done = true;
console.log("Question added!");
break;
case 'answersError':
data.answersError = true;
console.log("Answers error");
break;
case 'idAnswerError':
data.idAnswerError = true;
console.log("idAnswerError");
break;
}
res.render('home/addQuestionAfter', data);
});
// ADMIN ROUTES
app.get('/admin/getQuestions', isAuthenticated, isAdmin, (req, res) => {
let data = {
questions: db.getQuestions()
}
res.render('admin/allQuestions', data);
});
app.get('/admin/getQuestion/:id', isAuthenticated, isAdmin, (req, res) => {
let data = {
question: db.getQuestion(req.params.id),
}
let answersArray = [];
data.question.listIDAnswers.split(',').forEach((answerID) => {
answersArray.push(db.getAnswer(answerID));
if (data.question.idCorrectAnswer == answerID)
data.goodAnswer = answersArray.length;
});
data.answers = answersArray;
res.render('admin/question', data); // TODO : Highlight good answer. Get with data.question.idCorrectAnswer
});
app.get('/admin/questionAction/:action/:id', isAuthenticated, isAdmin, (req, res) => {
let action = req.params.action;
let id = req.params.id;
let data = {};
switch (action) {
case "delete":
if (db.getQuestion(id) === undefined)
data.wrongID = true;
else {
db.deleteQuestion(id);
data.deleted = true;
}
break;
default:
data.wrongAction = true;
break;
}
res.render("admin/questionAction", data);
});
app.get('/error/404', (req, res) => {
res.status(404);
res.render('error/404.html');
});
app.get('/error/403', (req, res) => {
res.status(403);
res.render('error/403.html');
});
app.get('/error/418', (req, res) => {
res.status(418);
res.render('error/418.html');
});
// STATIC FILES
app.use((express.static('public_html')));
// IF NO FILES FOUND
app.use((req, res) => {
res.redirect('/error/404');
});
app.listen(SERVER_PORT, console.log("Server listening on http://localhost:" + SERVER_PORT));