forked from csmith1188/Formbar.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
3211 lines (2721 loc) · 99 KB
/
app.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
// Imported modules
const express = require('express')
const session = require('express-session') //For storing client login data
const { encrypt, decrypt } = require('./static/js/crypto.js') //For encrypting passwords
const sqlite3 = require('sqlite3').verbose()
const jwt = require('jsonwebtoken') //For authentication system between Plugins and Formbar
const excelToJson = require('convert-excel-to-json')
const multer = require('multer')//Used to upload files
const upload = multer({ dest: 'uploads/' }) //Selects a file destination for uploaded files to go to, will create folder when file is submitted(?)
const crypto = require('crypto')
const winston = require('winston')
var app = express()
const http = require('http').createServer(app)
const io = require('socket.io')(http)
// Set EJS as our view engine
app.set('view engine', 'ejs')
// Create session for user information to be transferred from page to page
var sessionMiddleware = session({
secret: crypto.randomBytes(256).toString('hex'), //Used to sign into the session via cookies
resave: false, //Used to prevent resaving back to the session store, even if it wasn't modified
saveUninitialized: false //Forces a session that is new, but not modified, or "uninitialized" to be saved to the session store
})
// Sets up middleware for the server by calling sessionMiddleware
// adds session middleware to express
app.use(sessionMiddleware)
// For further uses on this use this link: https://socket.io/how-to/use-with-express-session
// Uses a middleware function to successfully transmit data between the user and server
// adds session middle ware to socket.io
io.use((socket, next) => {
sessionMiddleware(socket.request, socket.request.res || {}, next)
})
// Allows express to parse requests
app.use(express.urlencoded({ extended: true }))
// Use a static folder for web page assets
app.use(express.static(__dirname + '/static'))
app.use('/js/chart.js', express.static(__dirname + '/node_modules/chart.js/dist/chart.umd.js'))
app.use('/js/iro.js', express.static(__dirname + '/node_modules/@jaames/iro/dist/iro.min.js'))
app.use('/js/floating-ui-core.js', express.static(__dirname + '/node_modules/@floating-ui/core/dist/floating-ui.core.umd.min.js'))
app.use('/js/floating-ui-dom.js', express.static(__dirname + '/node_modules/@floating-ui/dom/dist/floating-ui.dom.umd.min.js'))
// Establishes the connection to the database file
var db = new sqlite3.Database('database/database.db')
const logger = winston.createLogger({
levels: {
critical: 0,
error: 1,
warning: 2,
info: 3,
verbose: 4
},
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level}: ${message}`
})
),
transports: [
new winston.transports.File({ filename: 'logs/critical.log', level: 'critical' }),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/info.log', level: 'info' }),
new winston.transports.File({ filename: 'logs/verbose.log', level: 'verbose' }),
new winston.transports.Console({ level: 'error' })
],
})
//cD is the class dictionary, it stores all of the information on classes and students
var cD = {
noClass: { students: {} }
}
// Constants
// permissions levels
const MANAGER_PERMISSIONS = 5
const TEACHER_PERMISSIONS = 4
const MOD_PERMISSIONS = 3
const STUDENT_PERMISSIONS = 2
const GUEST_PERMISSIONS = 1
const BANNED_PERMISSIONS = 0
const MAX_CLASS_PERMISSIONS = TEACHER_PERMISSIONS
// Permission level needed to access each page
const PAGE_PERMISSIONS = {
controlPanel: { permissions: TEACHER_PERMISSIONS, classPage: true },
previousLessons: { permissions: TEACHER_PERMISSIONS, classPage: true },
chat: { permissions: STUDENT_PERMISSIONS, classPage: true },
poll: { permissions: STUDENT_PERMISSIONS, classPage: true },
student: { permissions: STUDENT_PERMISSIONS, classPage: true },
virtualbar: { permissions: GUEST_PERMISSIONS, classPage: true },
makeQuiz: { permissions: TEACHER_PERMISSIONS, classPage: true },
help: { permissions: STUDENT_PERMISSIONS, classPage: true },
bgm: { permissions: MOD_PERMISSIONS, classPage: true },
sfx: { permissions: MOD_PERMISSIONS, classPage: true },
plugins: { permissions: STUDENT_PERMISSIONS, classPage: true },
manageClass: { permissions: TEACHER_PERMISSIONS, classPage: false },
createClass: { permissions: TEACHER_PERMISSIONS, classPage: false },
selectClass: { permissions: GUEST_PERMISSIONS, classPage: false },
}
// This class is used to create a student to be stored in the sessions data
class Student {
// Needs username, id from the database, and if permissions established already pass the updated value
// These will need to be put into the constructor in order to allow the creation of the object
constructor(
username,
id,
permissions = STUDENT_PERMISSIONS,
API,
ownedPolls = [],
sharedPolls = []
) {
this.username = username
this.id = id
this.permissions = permissions
this.classPermissions = null
this.ownedPolls = ownedPolls || []
this.sharedPolls = sharedPolls || []
this.pollRes = {
buttonRes: '',
textRes: ''
}
this.help = ''
this.break = ''
this.quizScore = ''
this.API = API
this.pogMeter = 0
}
}
// This class is used to add a new classroom to the session data
// The classroom will be used to add lessons, do lessons, and for the teacher to operate them
class Classroom {
// Needs the name of the class you want to create
constructor(id, className, key, sharedPolls = []) {
this.id = id
this.className = className
this.students = {}
this.sharedPolls = sharedPolls || []
this.poll = {
status: false,
responses: {},
textRes: false,
prompt: '',
weight: 1,
blind: false
}
this.key = key
this.lesson = {}
this.activeLesson = false
this.steps
this.currentStep = 0
this.quiz = false
this.mode = 'poll'
}
}
//allows quizzes to be made
class Quiz {
constructor(numOfQuestions, maxScore) {
this.questions = []
this.totalScore = maxScore
this.numOfQuestions = numOfQuestions
this.pointsPerQuestion = this.totalScore / numOfQuestions
}
}
//allows lessons to be made
class Lesson {
constructor(date, content) {
this.date = date
this.content = content
}
}
// Functions
// Global functions
function convertHSLToHex(hue, saturation, lightness) {
try {
logger.log('info', `[convertHSLToHex] hue=${hue}, saturation=${saturation}, lightness=${lightness}`)
// Normalize lightness to range 0-1
lightness /= 100;
// Calculate chroma
const chroma = saturation * Math.min(lightness, 1 - lightness) / 100;
// Function to get color component
function getColorComponent(colorIndex) {
try {
const colorPosition = (colorIndex + hue / 30) % 12;
const colorValue = lightness - chroma * Math.max(Math.min(colorPosition - 3, 9 - colorPosition, 1), -1);
// Return color component in hexadecimal format
return Math.round(255 * colorValue).toString(16).padStart(2, '0');
} catch (err) {
return err
}
}
// Return the hex color
logger.log('verbose', `[convertHSLToHex] color=(${getColorComponent(0)}${getColorComponent(8)}${getColorComponent(4)})`)
let red = getColorComponent(0)
let green = getColorComponent(8)
let blue = getColorComponent(4)
if (red instanceof Error) throw red
if (green instanceof Error) throw green
if (blue instanceof Error) throw blue
return `#${red}${green}${blue}`;
} catch (err) {
return err
}
}
function generateColors(amount) {
try {
logger.log('info', `[generateColors] amount=(${amount})`)
// Initialize colors array
let colors = []
// Initialize hue
let hue = 0
// Generate colors
for (let i = 0; i < amount; i++) {
// Add color to the colors array
let color = convertHSLToHex(hue, 100, 50)
if (color instanceof Error) throw color
colors.push(color);
// Increment hue
hue += 360 / amount
}
// Return the colors array
logger.log('verbose', `[generateColors] colors=(${colors})`)
return colors
} catch (err) {
return err
}
}
function getUserClass(username) {
try {
logger.log('info', `[getUserClass] username=(${username})`)
for (let classCode of Object.keys(cD)) {
if (cD[classCode].students[username]) {
logger.log('verbose', `[getUserClass] classCode=(${classCode})`)
return classCode
}
}
logger.log('verbose', `[getUserClass] classCode=(${null})`)
return null
} catch (err) {
return err
}
}
function joinClass(username, code) {
return new Promise((resolve, reject) => {
try {
logger.log('info', `[joinClass] username=(${username}) classCode=(${code})`)
// Find the id of the class from the database
db.get('SELECT id FROM classroom WHERE key=?', [code], (err, classroom) => {
try {
if (err) {
reject(err)
return
}
// Check to make sure there was a class with that code
if (!classroom || !cD[code]) {
logger.log('info', '[joinClass] No open class with that code')
resolve('no open class with that code')
return
}
// Find the id of the user who is trying to join the class
db.get('SELECT id FROM users WHERE username=?', [username], (err, user) => {
try {
if (err) {
reject(err)
return
}
if (!user) {
logger.log('critical', '[joinClass] User is not in database')
resolve('user is not in database')
}
// Add the two id's to the junction table to link the user and class
db.get('SELECT * FROM classusers WHERE classId = ? AND studentId = ?',
[classroom.id, user.id],
(err, classUser) => {
try {
if (err) {
reject(err)
return
}
if (classUser) {
// Get the student's session data ready to transport into new class
let user = cD.noClass.students[username]
if (classUser.permissions <= BANNED_PERMISSIONS) {
logger.log('info', '[joinClass] User is banned')
resolve('you are banned from that class')
}
user.classPermissions = classUser.permissions
// Remove student from old class
delete cD.noClass.students[username]
// Add the student to the newly created class
cD[code].students[username] = user
logger.log('verbose', `[joinClass] cD=(${cD})`)
resolve(true)
} else {
db.run('INSERT INTO classusers(classId, studentId, permissions, digiPogs) VALUES(?, ?, ?, ?)',
[classroom.id, user.id, GUEST_PERMISSIONS, 0], (err) => {
try {
if (err) {
reject(err)
return
}
logger.log('info', '[joinClass] Added user to classusers')
let user = cD.noClass.students[username]
user.classPermissions = GUEST_PERMISSIONS
// Remove student from old class
delete cD.noClass.students[username]
// Add the student to the newly created class
cD[code].students[username] = user
logger.log('verbose', `[joinClass] cD=(${cD})`)
resolve(true)
} catch (err) {
reject(err)
}
}
)
}
} catch (err) {
reject(err)
}
}
)
} catch (err) {
reject(err)
}
})
} catch (err) {
reject(err)
}
})
} catch (err) {
reject(err)
}
})
}
// Express functions
/*
Check if user has logged in
Place at the start of any page that needs to verify if a user is logged in or not
This allows websites to check on their own if the user is logged in
This also allows for the website to check for permissions
*/
function isAuthenticated(req, res, next) {
try {
logger.log('info', `[isAuthenticated] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
if (req.session.username) {
if (cD.noClass.students[req.session.username]) {
if (cD.noClass.students[req.session.username].permissions >= TEACHER_PERMISSIONS) {
res.redirect('/manageClass')
} else {
res.redirect('/selectClass')
}
} else {
next()
}
} else {
res.redirect('/login')
}
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
}
// Check if user is logged in. Only used for create and select class pages
// Use isAuthenticated function for any other pages
// Created for the first page since there is no check before this
// This allows for a first check in where the user gets checked by the webpage
function isLoggedIn(req, res, next) {
try {
logger.log('info', `[isLoggedIn] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
if (req.session.username) {
next()
} else {
res.redirect('/login')
}
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
}
// Check if user has the permission levels to enter that page
function permCheck(req, res, next) {
try {
let username = req.session.username
let classCode = req.session.class
logger.log('info', `[permCheck] ip=(${req.ip}) session=(${JSON.stringify(req.session)}) url=(${req.url})`)
if (req.url) {
// Defines users desired endpoint
let urlPath = req.url
// Checks if url has a / in it and removes it from the string
if (urlPath.indexOf('/') != -1) {
urlPath = urlPath.slice(urlPath.indexOf('/') + 1)
}
// Check for ?(urlParams) and removes it from the string
if (urlPath.indexOf('?') != -1) {
urlPath = urlPath.slice(0, urlPath.indexOf('?'))
}
if (!cD[classCode].students[username]) {
req.session.class = 'noClass'
classCode = 'noClass'
}
logger.log('verbose', `[permCheck] urlPath=(${urlPath})`)
if (!PAGE_PERMISSIONS[urlPath]) {
logger.log('info', `[permCheck] ${urlPath} is not in the page permissions`)
res.render('pages/message', {
message: `Error: ${urlPath} is not in the page permissions`,
title: 'Error'
})
}
// Checks if users permissions are high enough
if (
PAGE_PERMISSIONS[urlPath].classPage &&
cD[classCode].students[username].classPermissions >= PAGE_PERMISSIONS[urlPath].permissions
) next()
else if (
!PAGE_PERMISSIONS[urlPath].classPage &&
cD[classCode].students[username].permissions >= PAGE_PERMISSIONS[urlPath].permissions
) {
next()
}
else {
logger.log('info', '[permCheck] Not enough permissions')
res.render('pages/message', {
message: `Error: you don't have high enough permissions to access ${urlPath}`,
title: 'Error'
})
}
}
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
}
//import routes
const apiRoutes = require('./routes/api.js')(cD)
//add routes to express
app.use('/api', apiRoutes)
// This is the root page, it is where the users first get checked by the home page
// It is used to redirect to the home page
// This allows it to check if the user is logged in along with the home page
// It also allows for redirection to any other page if needed
app.get('/', isAuthenticated, (req, res) => {
try {
logger.log('info', `[get /] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
res.redirect('/student')
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// A
//The page displaying the API key used when handling oauth2 requests from outside programs such as formPix
app.get('/apikey', isAuthenticated, (req, res) => {
try {
logger.log('info', `[get /apikey] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
res.render('pages/apiKey', {
title: 'API Key',
API: cD[req.session.class].students[req.session.username].API
})
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// B
// C
// An endpoint for the teacher to control the formbar
// Used to update students permissions, handle polls and their corresponsing responses
// On render it will send all students in that class to the page
app.get('/controlPanel', isAuthenticated, permCheck, (req, res) => {
try {
logger.log('info', `[get /controlPanel] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
let students = cD[req.session.class].students
let keys = Object.keys(students)
let allStuds = []
for (var i = 0; i < keys.length; i++) {
var val = { name: keys[i], perms: students[keys[i]].permissions, pollRes: { lettRes: students[keys[i]].pollRes.buttonRes, textRes: students[keys[i]].pollRes.textRes }, help: students[keys[i]].help }
allStuds.push(val)
}
/* Uses EJS to render the template and display the information for the class.
This includes the class list of students, poll responses, and the class code - Riley R., May 22, 2023
*/
res.render('pages/controlPanel', {
title: 'Control Panel',
pollStatus: cD[req.session.class].poll.status,
currentUser: JSON.stringify(cD[req.session.class].students[req.session.username])
})
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// C
/*
Manages the use of excell spreadsheets in order to create progressive lessons.
It uses Excel To JSON to create an object containing all the data needed for a progressive lesson.
Could use a switch if need be, but for now it's all broken up by if statements.
Use the provided template when testing things. - Riley R., May 22, 2023
*/
app.post('/controlPanel', upload.single('spreadsheet'), isAuthenticated, permCheck, (req, res) => {
try {
//Initialze a list to push each step to - Riley R., May 22, 2023
let steps = []
logger.log('info', `[post /controlPanel] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
/*
Uses Excel to JSON to read the sent excel spreadsheet.
Each main column has been assigned a label in order to differentiate them.
It loops through the whole object - Riley R., May 22, 2023
*/
if (req.file) {
cD[req.session.class].currentStep = 0
const result = excelToJson({
sourceFile: req.file.path,
sheets: [{
name: 'Steps',
columnToKey: {
A: 'index',
B: 'type',
C: 'prompt',
D: 'response',
E: 'labels'
}
}]
})
/* For In Loop that iterates through the created object.
Allows for the use of steps inside of a progressive lesson.
Checks the object's type using a conditional - Riley R., May 22, 2023
*/
for (const key in result['Steps']) {
let step = {}
// Creates an object with all the data required to start a poll - Riley R., May 22, 2023
if (result['Steps'][key].type == 'Poll') {
step.type = 'poll'
step.labels = result['Steps'][key].labels.split(', ')
step.responses = result['Steps'][key].response
step.prompt = result['Steps'][key].prompt
steps.push(step)
// Creates an object with all the data required to start a quiz
} else if (result['Steps'][key].type == 'Quiz') {
let nameQ = result['Steps'][key].prompt
let letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
let colToKeyObj = {
A: 'index',
B: 'question',
C: 'key'
}
let i = 0
/*
Names the cells of the sheet after C to A-Z for the use of them in Quizzes (A, B, and C in the spreadsheet are the index, question, and key, not the answers)
Creates a way to have multiple responses to quizzes- Riley R., May 22, 2023
*/
for (const letterI in letters) {
if (letters.charAt(letterI) != 'A' && letters.charAt(letterI) != 'B' && letters.charAt(letterI) != 'C') {
colToKeyObj[letters.charAt(letterI)] = letters.charAt(i)
i++
}
}
let quizLoad = excelToJson({
sourceFile: req.file.path,
sheets: [{
name: nameQ,
columnToKey: colToKeyObj
}]
})
let questionList = []
for (let i = 1; i < quizLoad[nameQ].length; i++) {
let questionMaker = []
questionMaker.push(quizLoad[nameQ][i].question)
questionMaker.push(quizLoad[nameQ][i].key)
for (const letterI in letters) {
if (quizLoad[nameQ][i][letters.charAt(letterI)] != undefined) {
questionMaker.push(quizLoad[nameQ][i][letters.charAt(letterI)])
}
}
questionList.push(questionMaker)
}
step.type = 'quiz'
step.questions = questionList
steps.push(step)
} else if (result['Steps'][key].type == 'Lesson') {
/*
Creates an object with all necessary data in order to make a lesson.
The data is stored on a page in an excel spreadsheet.
the name of this page is defined in the main page of the excel spreadsheet. - Riley R., May 22, 2023
*/
nameL = result['Steps'][key].prompt
let lessonLoad = excelToJson({
sourceFile: req.file.path,
sheets: [{
name: nameL,
columnToKey: {
A: 'header',
B: 'data'
}
}]
})
let lessonArr = []
for (let i = 1; i < lessonLoad[nameL].length; i++) {
let lessonMaker = [lessonLoad[nameL][i].header]
let lessonContent = lessonLoad[nameL][i].data.split(', ')
for (let u = 0; u < lessonContent.length; u++) {
lessonMaker.push(lessonContent[u])
}
lessonArr.push(lessonMaker)
}
let dateConfig = new Date()
step.type = 'lesson'
step.date = `${dateConfig.getMonth() + 1}/${dateConfig.getDate()}/${dateConfig.getFullYear()}`
step.lesson = lessonArr
steps.push(step)
}
}
cD[req.session.class].steps = steps
res.redirect('/controlPanel')
}
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// Allow teacher to create class
// Allowing the teacher to create classes is vital to whether the lesson actually works or not, because they have to be allowed to create a teacher class
// This will allow the teacher to give students student perms, and guests student perms as well
// Plus they can ban and kick as long as they can create classes
app.post('/createClass', isLoggedIn, permCheck, (req, res) => {
try {
let submittionType = req.body.submittionType
let className = req.body.name
let classId = req.body.id
logger.log('info', `[post /createClass] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
logger.log('verbose', `[post /createClass] submittionType=(${submittionType}) className=(${className}) classId=(${classId})`)
function makeClass(id, className, key, sharedPolls = []) {
try {
// Get the teachers session data ready to transport into new class
var user = cD.noClass.students[req.session.username]
logger.log('verbose', `[makeClass] id=(${id}) name=(${className}) key=(${key}) sharedPolls=(${JSON.stringify(sharedPolls)})`)
// Remove teacher from old class
delete cD.noClass.students[req.session.username]
// Add class into the session data
cD[key] = new Classroom(id, className, key, sharedPolls)
// Add the teacher to the newly created class
cD[key].students[req.session.username] = user
cD[key].students[req.session.username].classPermissions = MANAGER_PERMISSIONS
req.session.class = key
return true
} catch (err) {
return err
}
}
// Checks if teacher is creating a new class or joining an old class
//generates a 4 character key
//this is used for students who want to enter a class
if (submittionType == 'create') {
let key = ''
for (let i = 0; i < 4; i++) {
let keygen = 'abcdefghijklmnopqrstuvwxyz123456789'
let letter = keygen[Math.floor(Math.random() * keygen.length)]
key += letter
}
// Add classroom to the database
db.run('INSERT INTO classroom(name, owner, key) VALUES(?, ?, ?)', [className, req.session.userId, key], (err) => {
try {
if (err) throw err
logger.log('verbose', `[post /createClass] Added classroom to database`)
db.get('SELECT classroom.id, classroom.name, classroom.key, NULLIF(json_group_array(DISTINCT class_polls.pollId), "[null]") as sharedPolls FROM classroom LEFT JOIN class_polls ON class_polls.classId = classroom.id WHERE classroom.name = ? AND classroom.owner = ?', [className, req.session.userId], (err, classroom) => {
try {
if (err) throw err
if (!classroom.id) {
logger.log('critical', `Class does not exist`)
res.render('pages/message', {
message: 'Class does not exist (please contact the programmer)',
title: 'Login'
})
return
}
let makeClassStatus = makeClass(
classroom.id,
classroom.name,
classroom.key,
JSON.parse(classroom.sharedPolls)
)
if (makeClassStatus instanceof Error) throw makeClassStatus
res.redirect('/')
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
} else {
db.get('SELECT id, name, key FROM classroom WHERE id = ?', [classId], (err, classroom) => {
try {
if (err) throw err
if (!classroom) {
logger.log('critical', `Class does not exist`)
res.render('pages/message', {
message: 'Class does not exist (please contact the programmer)',
title: 'Login'
})
return
}
let makeClassStatus = makeClass(
classroom.id,
classroom.name,
classroom.key,
)
if (makeClassStatus instanceof Error) throw makeClassStatus
res.redirect('/')
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
}
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// D
// E
// F
// G
// H
app.get('/help', isAuthenticated, permCheck, (req, res) => {
try {
logger.log('info', `[post /help] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
res.render('pages/help', {
title: 'Help'
})
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// I
// J
// K
// L
// This renders the login page
// It displays the title and the color of the login page of the formbar js
// It allows for the login to check if the user wants to login to the server
// This makes sure the lesson can see the students and work with them
app.get('/login', (req, res) => {
try {
logger.log('info', `[get /login] ip=(${req.ip}) session=(${JSON.stringify(req.session)})`)
res.render('pages/login', {
title: 'Login'
})
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
// This lets the user log into the server, it uses each element from the database to allow the server to do so
// This lets users actually log in instead of not being able to log in at all
// It uses the usernames, passwords, etc. to verify that it is the user that wants to log in logging in
// This also encrypts passwords to make sure people's accounts don't get hacked
app.post('/login', async (req, res) => {
try {
var user = {
username: req.body.username,
password: req.body.password,
loginType: req.body.loginType,
userType: req.body.userType
}
var passwordCrypt = encrypt(user.password)
logger.log('info', `[post /login] ip=(${req.ip}) session=(${JSON.stringify(req.session)}`)
logger.log('verbose', `[post /login] username=(${user.username}) password=(${Boolean(user.password)}) loginType=(${user.loginType}) userType=(${user.userType})`)
// Check whether user is logging in or signing up
if (user.loginType == 'login') {
logger.log('verbose', `[post /login] User is logging in`)
// Get the users login in data to verify password
db.get('SELECT users.*, CASE WHEN shared_polls.pollId IS NULL THEN json_array() ELSE json_group_array(DISTINCT shared_polls.pollId) END as sharedPolls, CASE WHEN custom_polls.id IS NULL THEN json_array() ELSE json_group_array(DISTINCT custom_polls.id) END as ownedPolls FROM users LEFT JOIN shared_polls ON shared_polls.userId = users.id LEFT JOIN custom_polls ON custom_polls.owner = users.id WHERE users.username = ?', [user.username], async (err, userData) => {
try {
// Check if a user with that name was not found in the database
if (!userData.username) {
logger.log('verbose', `[post /login] User does not exist`)
res.render('pages/message', {
message: 'No user found with that username.',
title: 'Login'
})
return
}
// Decrypt users password
let tempPassword = decrypt(JSON.parse(userData.password))
if (tempPassword != user.password) {
logger.log('verbose', `[post /login] Incorrect password`)
res.render('pages/message', {
message: 'Incorrect password',
title: 'Login'
})
return
}
let loggedIn = false
let classKey = ''
for (let classData of Object.values(cD)) {
if (classData.key) {
for (let username of Object.keys(classData.students)) {
if (username == userData.username) {
loggedIn = true
classKey = classData.key
break
}
}
}
}
if (loggedIn) {
logger.log('verbose', `[post /login] User is already logged in`)
req.session.class = classKey
} else {
// Add user to the session
cD.noClass.students[userData.username] = new Student(
userData.username,
userData.id,
userData.permissions,
userData.API,
JSON.parse(userData.ownedPolls),
JSON.parse(userData.sharedPolls)
)
req.session.class = 'noClass'
}
// Add a cookie to transfer user credentials across site
req.session.userId = userData.id
req.session.username = userData.username
logger.log('verbose', `[post /login] session=(${JSON.stringify(req.session)})`)
logger.log('verbose', `[post /login] cD=(${JSON.stringify(cD)})`)
res.redirect('/')
} catch (err) {
logger.log('error', err.stack)
res.render('pages/message', {
message: `Error: There was a server error try again.`,
title: 'Error'
})
}
})
} else if (user.loginType == 'new') {