-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1280 lines (1056 loc) · 47.9 KB
/
index.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
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const environment = process.argv[2] || '--prod';
const secrets = require("/config/secrets.json");
const config = require("/config/config.json");
const fastify = require('fastify')({ logger: true })
const mariadb = require('mariadb');
const getUuid = require('uuid-by-string');
const crypto = require('crypto');
const path = require('path')
const fs = require('fs');
const { renderHTML } = require("./render");
const puppeteer = require('puppeteer');
let conn = null;
let sessions = {};
fastify.register(require('@fastify/cookie'), {
secret: secrets.sessionKey,
hook: 'onRequest',
parseOptions: {}
})
fastify.register(require('@fastify/cors'), config.cors);
async function connectDb() {
const pool = await mariadb.createPool(config.sql);
conn = await pool.getConnection({ idleTimeout: 0, keepAliveInitialDelay: 10000, enableKeepAlive: true });
conn.on('error', async function (err) {
if (!err.fatal) return;
fastify.log.error('Connection to DB lost! Reconnecting now.');
await connectDb();
});
await conn.query('USE ' + config.sql.database);
await conn.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
}
const start = async () => {
try {
await connectDb();
const users = await conn.query('SELECT uuid FROM admins');
for (let i = 0; i < users.length; i++)
sessions[users[i].uuid] = {};
fastify.log.info('Starting server on port ', config.port);
await fastify.listen({ port: config.port })
} catch (err) {
console.log(err);
process.exit(1);
}
}
// LOGIN AND LOGOUT
fastify.post('/api/admin/login', async (req, res) => {
try {
fastify.log.info('Starting admin login procedure');
let parsedUserData = req.body;
if (!parsedUserData ||
!parsedUserData.username ||
!parsedUserData.password ||
typeof (parsedUserData.username) !== 'string' ||
typeof (parsedUserData.password) !== 'string'
) throw 'MISSING_FIELDS';
//search for the user in the database
let userSearchResult = await conn.query('SELECT * FROM admins WHERE name=?', [parsedUserData.username]);
if (userSearchResult.length != 1) throw 'USER_DOES_NOT_EXIST';
let user = userSearchResult[0];
let [salt, hash] = user.hash.split(':');
//compute hash from the password that was sent by the user
let userSentHash = generateHash(parsedUserData.password, salt + user.email + user.name + user.uuid);
//check if hashes match
let match = crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(userSentHash));
fastify.log.info('Admin hash matched with password: ' + match);
if (!match) throw 'WRONG_PASSWORD';
//user authenticated, now issue a token
let nonce = crypto.randomBytes(64).toString('base64');
while (sessions[user.uuid][nonce]) nonce = crypto.randomBytes(64).toString('base64');
let tokenObject = {
nonce: nonce,
username: user.name,
email: user.email,
uuid: user.uuid,
admin: true
}
sessions[user.uuid][tokenObject.nonce] = tokenObject;
//sign the token and send it to the user
let token = res.signCookie(JSON.stringify(tokenObject));
fastify.log.info('Issuing cookie to user', token);
res.setCookie('token', token, { path: '/', secure: true, sameSite: environment == '--test' ? 'strict' : 'none', expires: Date.now() + config.cookieMaxAge });
fastify.log.info('Admin login procedure succesfull');
res.code(200).send(tokenObject);
} catch (exception) {
fastify.log.error('Admin login procedure failed with exception ' + exception);
switch (exception) {
case 'USER_DOES_NOT_EXIST':
res.code(404);
break;
case 'MISSING_FIELDS':
res.code(400);
break;
case 'WRONG_PASSWORD':
res.code(403);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.post('/api/admin/logout', (req, res) => {
try {
try {
let userObject = verifyToken(req.cookies.token);
if (userObject)
delete (sessions[userObject.uuid][userObject.nonce]);
} catch (exception) {
fastify.log.error('Error deleting cookie from sessions');
}
fastify.log.info('Logging out an admin.');
res.clearCookie('token').code(200).send();
fastify.log.info('Logging out an admin succefull');
} catch (exception) {
res.code(500).send({ error: exception });
}
})
fastify.post('/api/admin/logoutall', (req, res) => {
try {
let userObject = verifyToken(req.cookies.token);
if (!userObject || userObject == 'TEST_ONLY') throw 'USER_NOT_AUTHENTICATED';
sessions[userObject.uuid] = {};
fastify.log.info('Logging out an adminall.');
res.clearCookie('token').code(200).send();
fastify.log.info('Logging out an admin succefull');
} catch (exception) {
res.code(exception == 'USER_NOT_AUTHENTICATED' ? 401 : 500).send({ error: exception });
}
})
fastify.post('/api/admin/logoutallall', (req, res) => {
try {
let userObject = verifyToken(req.cookies.token);
if (!userObject || userObject == 'TEST_ONLY') throw 'USER_NOT_AUTHENTICATED';
for (const uuid in sessions) sessions[uuid] = {};
fastify.log.info('Logging out an adminallall.');
res.clearCookie('token').code(200).send();
fastify.log.info('Logging out an admin succefull');
} catch (exception) {
res.code(exception == 'USER_NOT_AUTHENTICATED' ? 401 : 500).send({ error: exception });
}
})
fastify.get('/api/admin/currentuser', async (req, res) => {
try {
fastify.log.info('Starting current user procedure.');
let token = req.cookies.token;
if (!token) throw 'NO_COOKIE';
let signedCorrectly = fastify.unsignCookie(token).valid;
if (!signedCorrectly) throw 'INVALID_SIGNATURE';
let cookieData = JSON.parse(fastify.unsignCookie(token).value);
let userResponse = await conn.query('SELECT * FROM admins WHERE uuid=?', cookieData.uuid);
if (userResponse.length == 0) throw 'USER_NOT_AUTHENTICATED';
if (!sessions[cookieData.uuid] || !sessions[cookieData.uuid][cookieData.nonce]) throw 'COOKIE_EXPIRED';
fastify.log.info('Current user procedure succesfull.');
res.code(200).send(cookieData);
} catch (exception) {
fastify.log.error('Current user procedure failed with exception ' + exception);
switch (exception) {
case 'NO_COOKIE': case 'USER_NOT_AUTHENTICATED':
res.code(401).send({ error: 'USER_NOT_AUTHENTICATED' });
break;
case 'INVALID_SIGNATURE':
res.setCookie('token', 'INVALID_SIGNATURE_DELETING_COOKIE', { path: '/', secure: true, expires: Date.now() })
.code(401).send({ error: 'USER_NOT_AUTHENTICATED' });
break;
case 'COOKIE_EXPIRED':
res.setCookie('token', 'COOKIE_EXPIRED_DELETING_COOKIE', { path: '/', secure: true, expires: Date.now() })
.code(401).send({ error: 'USER_NOT_AUTHENTICATED' });
break;
default:
res.code(500).send({ error: exception });
}
}
})
//MANAGING USERS
fastify.put('/api/admin/users/add', async (req, res) => {
try {
fastify.log.info('Starting user add procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let user = req.body;
if (!user ||
!user.email ||
!user.username ||
!user.password ||
typeof (user.email) !== 'string' ||
typeof (user.username) !== 'string' ||
typeof (user.password) !== 'string'
) throw 'MISSING_FIELDS';
if (!String(user.email).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/))
throw 'INVALID_EMAIL_ADDRESS';
let salt = crypto.randomBytes(64).toString('base64');
let uuid = getUuid(crypto.randomBytes(64).toString('base64'));
let userHash = generateHash(user.password, salt + user.email + user.username + uuid);
let users = await conn.query('SELECT * FROM admins WHERE email=? OR name=?', [user.email, user.username]);
if (users.length > 0) throw 'USERNAME_OR_EMAIL_TAKEN';
sessions[uuid] = {};
try {
await conn.query('START TRANSACTION');
await conn.query('INSERT INTO admins (uuid, email, name, hash) VALUES (?, ?, ?, ?)', [uuid, user.email, user.username, salt + ':' + userHash]);
fastify.log.info('User add procedure succesfull');
await conn.query('COMMIT');
res.code(201).send();
} catch (exception) {
await conn.query('ROLLBACK');
throw exception
}
} catch (exception) {
fastify.log.error('User add procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'MISSING_FIELDS': case 'INVALID_EMAIL_ADDRESS': case 'USERNAME_OR_EMAIL_TAKEN':
res.code(400);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.get('/api/admin/users/get', async (req, res) => {
try {
fastify.log.info('Starting users get procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let users = await conn.query('SELECT uuid, name, email FROM admins');
fastify.log.info('Users get procedure succesfull');
res.code(200).send(users);
} catch (exception) {
fastify.log.error('Users get procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.delete('/api/admin/users/delete/*', async (req, res) => {
try {
fastify.log.info('Starting user delete procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let url = req.url + 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //Add padding if the user uuid is to short, so that it does not throw an exception.
let uuid = url.substring(24, 60);
let users = await conn.query('SELECT * FROM admins WHERE uuid=?', [uuid]);
if (users.length == 0) throw 'USER_DOES_NOT_EXIST';
await conn.query('DELETE FROM admins WHERE uuid=?', [uuid]);
if (sessions[uuid])
delete (sessions[uuid]);
fastify.log.info('User delete procedure succesfull');
if (JSON.parse(fastify.unsignCookie(req.cookies.token).value).uuid == uuid) res.clearCookie('token');
res.code(202).send();
} catch (exception) {
fastify.log.error('User delete procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'USER_DOES_NOT_EXIST':
res.code(404);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.patch('/api/admin/users/setpassword', async (req, res) => {
try {
fastify.log.info('Starting user password set procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let user = req.body;
if (!user ||
!user.uuid ||
!user.newPassword ||
typeof (user.uuid) !== 'string' ||
typeof (user.newPassword) !== 'string'
) throw 'MISSING_FIELDS';
let userResponse = await conn.query('SELECT * FROM admins WHERE uuid=?', [user.uuid]);
if (userResponse.length == 0) throw 'USER_DOES_NOT_EXIST';
let newSalt = crypto.randomBytes(64).toString('base64'); //Generate new salt, just for added security
let hash = generateHash(user.newPassword, newSalt + userResponse[0].email + userResponse[0].name + userResponse[0].uuid);
try {
await conn.query('START TRANSACTION');
await conn.query('UPDATE admins SET hash=? WHERE uuid=?', [newSalt + ':' + hash, user.uuid]);
sessions[user.uuid] = {};
fastify.log.info('User password set procedure succesfull');
await conn.query('COMMIT');
res.code(202).send();
} catch (exception) {
await conn.query('ROLLBACK');
throw exception
}
} catch (exception) {
fastify.log.error('User password set procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'USER_DOES_NOT_EXIST':
res.code(404);
break;
case 'MISSING_FIELDS':
res.code(400);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
//SETUP
fastify.delete('/api/admin/setup/resetall', async (req, res) => {
try {
fastify.log.info('Starting reset all procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
try {
await conn.query('START TRANSACTION');
await conn.query('UPDATE state SET value=0');
await conn.query('DELETE FROM classes');
await conn.query('DELETE FROM logos');
await conn.query('DELETE FROM tokens');
await conn.query('DELETE FROM batch');
await conn.query('ALTER TABLE logos AUTO_INCREMENT=1');
await conn.query('ALTER TABLE classes AUTO_INCREMENT=1');
let directory = config.pdfGeneration.pdfLocation;
fs.readdir(directory, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(directory, file), (err) => {
if (err) throw err;
});
}
});
await conn.query('COMMIT');
res.code(202).send();
} catch (exception) {
await conn.query('ROLLBACK');
throw exception;
}
} catch (exception) {
fastify.log.error('Reset all procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.post('/api/admin/setup/provision', async (req, res) => {
try {
fastify.log.info('Starting provision procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let provisioned = (await conn.query('SELECT value FROM state WHERE id=\'provisioned\''))[0].value == 1;
if (provisioned) throw 'ALREADY_PROVISIONED';
let list = req.body;
if (!list || !Array.isArray(list)) throw 'MISSING_FIELDS';
let numberSet = new Set();
for (let i = 0; i < list.length; i++) {
if (!list[i] || !list[i].class || !list[i].logos || typeof (list[i].class) !== 'string' || !Array.isArray(list[i].logos)) throw 'MISSING_FIELDS';
for (let j = 0; j < list[i].logos.length; j++)if (typeof (list[i].logos[j]) !== 'number') throw 'MISSING_FIELDS';
for (let j = 0; j < list[i].logos.length; j++) {
let num = list[i].logos[j];
if (numberSet.has(num)) throw 'NUMBER_REPEATS';
if (num > 1000 || num < 0) throw 'NUMBER_OUT_OF_RANGE';
numberSet.add(num);
}
}
let classes = new Set();
for (let i = 0; i < list.length; i++) {
if (classes.has(list[i].class)) throw 'CLASSES_SAME_NAME_ERROR';
classes.add(list[i].class);
}
try {
await conn.query('START TRANSACTION');
for (let i = 0; i < list.length; i++) {
const classObject = list[i];
let classUuid = getUuid(classObject.class + classObject.logos + crypto.randomBytes(32).toString());
await conn.query('INSERT INTO classes (uuid, name) VALUES (?, ?)', [classUuid, classObject.class]);
for (let j = 0; j < classObject.logos.length; j++) await conn.query('INSERT INTO logos (number, class) VALUES (?, ?)', [classObject.logos[j], classUuid]);
}
await conn.query('UPDATE state SET value=1 WHERE id=\'provisioned\'');
fastify.log.info('Provision procedure succesfull');
await conn.query('COMMIT');
res.code(201).send();
} catch (exception) {
fastify.log.error('Error provisioning ' + exception);
await conn.query('ROLLBACK');
throw exception;
}
} catch (exception) {
fastify.log.error('Provision procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'ALREADY_PROVISIONED': case 'CLASSES_SAME_NAME_ERROR': case 'MISSING_FIELDS': case 'NUMBER_REPEATS': case 'NUMBER_OUT_OF_RANGE':
res.code(400);
break;
default:
res.code(500);
}
res.send({ error: exception });
}
})
//MANAGING LOGOS
fastify.get('/api/admin/logos/get', async (req, res) => {
try {
fastify.log.info('Starting logos get procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let list = [];
let classes = await conn.query('SELECT uuid, name FROM classes ORDER BY number');
for (let i = 0; i < classes.length; i++) {
let classObject = classes[i];
let logosResponse = await conn.query('SELECT number FROM logos WHERE class=?', [classObject.uuid]);
let logos = [];
for (let j = 0; j < logosResponse.length; j++)
logos.push(logosResponse[j].number);
logos.sort(function (a, b) { return a - b });
list.push({
class: classObject.uuid,
name: classObject.name,
logos: logos
});
}
fastify.log.info('Logos get procedure succesfull');
res.code(200).send(list);
} catch (exception) {
fastify.log.error('Logos get procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
//MAGING TOKENS
fastify.post('/api/admin/tokens/generate', async (req, res) => {
try {
fastify.log.info('Starting generate tokens procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let provisioned = (await conn.query('SELECT value FROM state WHERE id=\'provisioned\''))[0].value == 1;
if (!provisioned) throw 'NOT_PROVISIONED';
let generateInfo = req.body;
if (!generateInfo || !generateInfo.class || typeof (generateInfo.class) !== 'string' || typeof (generateInfo.number) !== 'number') throw 'MISSING_FIELDS';
if (generateInfo.number <= 0 || generateInfo.number > config.pdfGeneration.maxTokensOneRequest) throw 'INVALID_NUMBER_OF_TOKENS';
// check if class uuid exists
let classResponse = await conn.query('SELECT uuid, name FROM classes WHERE uuid=?', [generateInfo.class]);
if (classResponse.length == 0 && generateInfo.class != '00000000-0000-0000-0000-000000000000') throw 'CLASS_UUID_UNKNOWN';
let className = (generateInfo.class != '00000000-0000-0000-0000-000000000000') ? classResponse[0].name : null;
//check if every class uuid exists and also compute how much tokens we have to create
//load current tokens to make sure we don't have any collisions while generating new ones.
let existingTokensList = await conn.query('SELECT token FROM tokens');
let existingTokens = new Set();
for (let i = 0; i < existingTokensList.length; i++)existingTokens.add(existingTokensList[i].token);
//load forbiddenTokens
let forbiddenTokens = config.forbiddenTokens;
for (let i = 0; i < forbiddenTokens.length; i++)
existingTokens.add(forbiddenTokens[i]);
const newToken = () => {
const allowedChars = config.allowedTokenChars;
const randomInt = () => {
var buf = new Uint8Array(1);
crypto.getRandomValues(buf);
return buf[0];
}
let t1 = "", t2 = "";
for (let i = 0; i < 4; i++)
t1 += allowedChars[randomInt() % allowedChars.length];
for (let i = 0; i < 4; i++)
t2 += allowedChars[randomInt() % allowedChars.length];
return t1 + "-" + t2;
}
let newTokens = [];
for (let i = 0; i < generateInfo.number; i++) {
let token = newToken();
while (existingTokens.has(token)) token = newToken();
existingTokens.add(token);
newTokens.push(token);
}
fastify.log.info(newTokens);
let currentTimeStamp = Math.round(Date.now() / 1000);
let batchUuid = getUuid(crypto.createHash('sha512').update(Date.now().toString()).digest('base64'));
//generate pdf file
const getQrSrc = (token) => `https://api.qrserver.com/v1/create-qr-code/?size=256&data=${encodeURIComponent(config.pdfGeneration.votingUrl.replace('{{token}}', token))
}&format=svg&margin=0&ecc=M`;
let tokenList = [];
const isTestingEnabled = (environment == '--test' && config.suggestedVoting);
for (let i = 0; i < newTokens.length; i++) {
let shuff = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map(value => ({ value, sort: Math.random() })).sort((a, b) => a.sort - b.sort).map(({ value }) => value);
tokenList.push({
token: newTokens[i],
qrSrc: getQrSrc(newTokens[i]),
test: isTestingEnabled ? {
points5: shuff[2],
points3: shuff[1],
points1: shuff[3],
pointsNeg1: shuff[7]
} : undefined,
blurQr: isTestingEnabled && (shuff[0] % 3) == 1,
blurToken: isTestingEnabled && (shuff[0] % 3) == 2
});
}
try {
let renderClass = [{
className: className,
tokens: tokenList
}];
let renderedHtml = renderHTML(renderClass);
const browser = await puppeteer.launch({ executablePath: config.pdfGeneration.chromiumPath, headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
fastify.log.info('Browser launched!')
await page.setContent(renderedHtml, { waitUntil: 'networkidle0' });
const pdf = await page.pdf({
path: path.join(config.pdfGeneration.pdfLocation, batchUuid + '.pdf'),
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
format: 'A4',
});
await browser.close();
fastify.log.info('PDF generated for ' + batchUuid);
}
catch (exception) {
fastify.log.error(exception);
throw 'PDF_GENERATION_ISSUE_CHECK_LOG'
}
try {
await conn.query('START TRANSACTION');
for (let it = 0; it < newTokens.length; it++)
await conn.query('INSERT INTO tokens (token, batchUuid, class) VALUES (?, ?, ?)', [newTokens[it], batchUuid, generateInfo.class])
await conn.query('INSERT INTO batch (batchUuid, timestamp, class, number) VALUES (?, ?, ?, ?)', [batchUuid, currentTimeStamp, generateInfo.class, newTokens.length]);
fastify.log.info('Tokens generate procedure succesfull');
await conn.query('COMMIT');
res.code(201).send({
batchUuid: batchUuid,
timestamp: currentTimeStamp,
class: generateInfo.class,
className: className,
pdfUrl: config.pdfGeneration.pdfLink.replace('{{uuid}}', batchUuid),
tokens: newTokens
});
} catch (exception) {
await conn.query('ROLLBACK');
throw exception
}
} catch (exception) {
fastify.log.error('Generate tokens procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'NOT_PROVISIONED': case 'INVALID_NUMBER_OF_TOKENS': case 'MISSING_FIELDS':
res.code(400);
break;
case 'CLASS_UUID_UNKNOWN':
res.code(404);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.get('/api/admin/tokens/get', async (req, res) => {
try {
fastify.log.info('Starting tokens get procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let batches = await conn.query('SELECT batchUuid, timestamp, class FROM batch');
let listToReturn = [];
for (let i = 0; i < batches.length; i++) {
let batchUuid = batches[i].batchUuid;
let tokensResponse = await conn.query('SELECT token, vote FROM tokens WHERE batchUuid=?', batchUuid);
let list = [];
for (let j = 0; j < tokensResponse.length; j++)
list.push({
token: tokensResponse[j].token,
used: tokensResponse[j].vote != null
});
let className = ((await conn.query('SELECT name FROM classes WHERE uuid=?', batches[i].class))[0] || { name: null }).name
listToReturn.push({
batchUuid: batchUuid,
timestamp: batches[i].timestamp,
class: batches[i].class,
className: className,
tokens: list
});
}
fastify.log.info('Tokens get procedure succesfull.')
res.code(200).send(listToReturn);
} catch (exception) {
fastify.log.error('Tokens get procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.delete('/api/admin/tokens/revoke/*', async (req, res) => {
try {
fastify.log.info('Starting tokens revoke procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let batchUuid = (req.url + 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx').substring(25, 61); //add padding if the uuid is too short
//check if uuid exists;
let batchResponse = await conn.query('SELECT * FROM batch WHERE batchUuid=?', batchUuid);
if (batchResponse.length == 0) throw 'BATCH_UUID_NOT_FOUND';
let tokensToRevoke = await conn.query('SELECT token, vote FROM tokens WHERE batchUuid=?', batchUuid);
await conn.query('DELETE FROM tokens WHERE batchUuid=?', batchUuid);
let votesToRevoke = [];
for (let i = 0; i < tokensToRevoke.length; i++)
if (tokensToRevoke[i].vote != null) {
let list = JSON.parse(tokensToRevoke[i].vote);
for (let j = 0; j < list.length; j++)votesToRevoke.push(list[j]);
}
fastify.log.info('Revoking tokens and reverting votes');
try {
await conn.query('START TRANSACTION');
for (let i = 0; i < votesToRevoke.length; i++)
await conn.query('UPDATE logos SET points=points+? WHERE number=?', [votesToRevoke[i].points * -1, votesToRevoke[i].logo]);
for (let i = 0; i < votesToRevoke.length; i++)
await conn.query('UPDATE logos SET pointsCounter' + Math.abs(votesToRevoke[i].points).toString() + (votesToRevoke[i].points > 0 ? 'pos' : 'neg') + '=pointsCounter' + Math.abs(votesToRevoke[i].points).toString() + (votesToRevoke[i].points > 0 ? 'pos' : 'neg') + '-1 WHERE number=?', [
votesToRevoke[i].logo]);
await conn.query('DELETE FROM batch WHERE batchUuid=?', batchUuid);
fs.unlink(path.join(config.pdfGeneration.pdfLocation, batchUuid + '.pdf'), (err) => {
if (err) throw err;
});
await conn.query('COMMIT');
res.code(202).send();
} catch (exception) {
fastify.log.error('Error revoking tokens ' + exception);
await conn.query('ROLLBACK');
throw exception;
}
} catch (exception) {
fastify.log.error('Tokens revoke procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'BATCH_UUID_NOT_FOUND':
res.code(404);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.get('/api/admin/tokens/pdf/*', async (req, res) => {
try {
fastify.log.info('Starting pdf get procedure')
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let fileName = req.url.substring(22);
let fullPath = path.join(config.pdfGeneration.pdfLocation, fileName);
if (fs.existsSync(fullPath)) {
const bufferIndexHtml = fs.readFileSync(fullPath);
fastify.log.info('Pdf get procedure succesfull');
res.type('application/pdf').code(200).send(bufferIndexHtml);
} else throw 'PDF_NOT_FOUND';
} catch (exception) {
fastify.log.error('Pdf get procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'PDF_NOT_FOUND':
res.code(404);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
//MANAGING VOTING
fastify.post('/api/admin/voting/start', async (req, res) => {
try {
fastify.log.info('Starting voting')
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let provisioned = (await conn.query('SELECT value FROM state WHERE id=\'provisioned\''))[0].value == 1;
if (!provisioned) throw 'NOT_PROVISIONED';
try {
await conn.query('START TRANSACTION');
await conn.query('UPDATE state SET value=1 WHERE id=\'voting\'');
fastify.log.info('Voting start procedure succesfull');
await conn.query('COMMIT');
res.code(202).send();
} catch (exception) {
fastify.log.error('Error starting voting ' + exception);
await conn.query('ROLLBACK');
}
} catch (exception) {
fastify.log.error('Starting voting failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'NOT_PROVISIONED':
res.code(400);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.post('/api/admin/voting/stop', async (req, res) => {
try {
fastify.log.info('Stopping voting')
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let provisioned = (await conn.query('SELECT value FROM state WHERE id=\'provisioned\''))[0].value == 1;
if (!provisioned) throw 'NOT_PROVISIONED';
try {
await conn.query('START TRANSACTION');
await conn.query('UPDATE state SET value=0 WHERE id=\'voting\'');
fastify.log.info('Voting stop procedure succesfull');
await conn.query('COMMIT');
res.code(202).send();
} catch (exception) {
fastify.log.error('Error stoping voting ' + exception);
await conn.query('ROLLBACK');
}
} catch (exception) {
fastify.log.error('Stopping voting failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
case 'NOT_PROVISIONED':
res.code(400);
break;
default:
res.code(500);
break;
}
res.send({ error: exception });
}
})
fastify.get('/api/admin/voting/results/get', async (req, res) => {
try {
fastify.log.info('Starting results get procedure');
if (!verifyToken(req.cookies.token)) throw 'USER_NOT_AUTHENTICATED';
let resultsResponse = await conn.query('SELECT * FROM logos ORDER BY points DESC, number');
let classesList = await conn.query('SELECT * FROM classes');
let classes = {};
for (let i = 0; i < classesList.length; i++)
classes[classesList[i].uuid] = classesList[i];
let pointsResponse = await conn.query('SELECT points FROM logos ORDER BY points DESC');
let cnt = {}, ranking = {}, count = 1;
for (let i = 0; i < pointsResponse.length; i++) {
cnt[pointsResponse[i].points] = (cnt[pointsResponse[i].points]) ? cnt[pointsResponse[i].points] + 1 : 1;
}
let pnts = await conn.query('SELECT points FROM logos GROUP BY points ORDER BY points DESC, number')
for (let i = 0; i < pnts.length; i++) {
ranking[pnts[i].points] = count;
count += cnt[pnts[i].points];
}
let results = [];
for (let i = 0; i < resultsResponse.length; i++) {
let obj = {
number: resultsResponse[i].number,
class: classes[resultsResponse[i].class],
totalPoints: resultsResponse[i].points,
detailedPoints: [],
ranking: ranking[resultsResponse[i].points]
};
for (const key in resultsResponse[i])
if (key.startsWith('pointsCounter')) {
let str = key.substring(13);
let num = str.substring(0, str.length - 3);
let sign = str.substring(str.length - 3, str.length) == 'pos' ? 1 : -1;
let points = num * sign;
obj.detailedPoints.push({
points: points,
count: resultsResponse[i][key]
})
}
results.push(obj);
}
fastify.log.info('Results get procedure succesfull');
res.code(200).send(results);
} catch (exception) {
fastify.log.error('Results get procedure failed with exception ' + exception);
switch (exception) {
case 'USER_NOT_AUTHENTICATED':
res.code(401);
break;
default:
res.code(500);
break;
}