-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
1688 lines (1604 loc) · 59 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
// Global directories and settings
const port = process.env.PORT || 8098;
const path = require('path');
const dir_libraries = path.join(__dirname, 'libraries'); // notifier.js, svcore.js, svuelib.js *REQUIRED to run*
const dir_svp = path.join(__dirname, 'secure'); // non open-sourced libraries (analytics, /admin, mobile StudentVUE server emulator, local SVUE server) *NOT REQUIRED; server will run fine without these*
const credentials = require(path.join(__dirname, 'secure', 'credentials.json')); // see credentials.info.md for more information
const cryptoHelper = require(path.join(dir_libraries, 'cryptoHelper'));
cryptoHelper.init(credentials.AESKey);
// Init variables and server
const fs = require('fs');
const colors = require('colors');
const schedule = require('node-schedule');
const moment = require('moment');
const request = require('request');
const cheerio = require('cheerio');
const minify = require('html-minifier').minify;
const app = require('express')();
const bcrypt = require('bcrypt');
// Used only for /export
const JSZip = require('jszip');
const tmp = require('tmp');
const svcore = require(path.join(dir_libraries, 'svcore.js'));
const fetchSVUE = svcore.fetchSVUE;
const svexport = require(path.join(dir_libraries, 'svexport.js'));
const session = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
const http = require('http').Server(app);
const winston = require('winston');
const winston_estf = winston.format(info => { // Error stack tracer format
if (info.meta && info.meta instanceof Error) {
info.message = `${info.message} ${info.meta.stack}`;
}
return info;
});
const logger_color = function(s) {
switch (s) {
case 'info':
return 'info'.cyan;
case 'warn':
return 'warn'.yellow;
case 'error':
return 'error'.magenta
case 'debug':
return 'debug'.green
default:
return s
}
}
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.printf(info => `${moment(new Date()).format('M/DD HH:mm:ss')}: ${logger_color(info.level)}: ${info.message}`)
}),
new winston.transports.File({
filename: path.join(__dirname, 'logs', 'error.log'),
level: 'error',
format: winston.format.combine(winston.format.timestamp(), winston.format.splat(), winston_estf(), winston.format.simple())
}),
new winston.transports.File({
filename: path.join(__dirname, 'logs', 'combined.log'),
format: winston.format.printf(info => `${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}: ${info.level}: ${info.message}`)
})
]
});
// Admin backend (not fully open source)
let localAdminCreds = false;
if (fs.existsSync(path.join(dir_svp, 'svue.admin.json'))) {
localAdminCreds = require(path.join(dir_svp, 'svue.admin.json'));
} else {
logger.info('svue.admin.json could not be found, disabling the /admin/signin endpoint')
}
// Database and session initialization
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;
const MongoURL = credentials.database;
const dbName = 'svueplus';
const dbClient = new MongoClient(MongoURL, {useNewUrlParser: true});
let mdb, userdb, logindb;
dbClient.connect((e) => {
if(e){logger.error('Failed to connect to local MongoDB server (localhost:27017)', e); require('process').exit()}
logger.info('Connected to local MongoDB server (localhost:27017).')
mdb = dbClient.db(dbName);
userdb = mdb.collection('users');
logindb = mdb.collection('loginHistory');
setupDB();
})
function setupDB(){
mdb.collection('pendingVerifications')
.createIndex({
'createdAt': 1
}, {
expireAfterSeconds: 7200 // 2 hours
}, function(indexErr) {
if (indexErr) {
logger.error('init: failed to create index', indexErr);
}
});
if(analytics){
analytics.init(mdb, logger);
analytics.appHook(app); // /admin/* routing for analytics
}
if (credentials.mailemail && credentials.mailpass) {
notifierCore.init({
user: credentials.mailemail,
pass: credentials.mailpass
}, userdb, logger);
} else {
logger.warn('Notifier: Email credentials not set up, notifier will not be active.')
}
webauthn.mongoHook(mdb);
}
let sess_MongoStore = require('connect-mongo')(session);
let sess = {
secret: credentials.sessionkey,
store: new sess_MongoStore({
url: credentials.database,
stringify: false
}),
saveUninitialized: false,
resave: false,
cookie: {}
}
if (app.get('env') === 'production' || fs.existsSync(path.join(__dirname, 'production.cfg'))) {
logger.info('Production environment detected.')
app.set('trust proxy', 1) // trust first proxy
// sess.cookie.secure = true // serve secure cookies (currently not working)
}
app.use(session(sess));
const rateLimit = require('express-rate-limit');
const rl_MongoStore = require('rate-limit-mongo');
let limiter = new rateLimit({
store: new rl_MongoStore({
uri: 'mongodb://localhost:27017/svueplus',
expireTimeMs: 36 * 1000
}),
max: 8, // 8 requests per 16 seconds max
windowMs: 16 * 1000,
statusCode: 200, // Prevent Zepto from freaking out
message: {type: 'error', error: 39, msg: 'Too many login attempts. Try again in a minute.'}
});
let gbLimiter = new rateLimit({
store: new rl_MongoStore({
uri: 'mongodb://localhost:27017/svueplus',
expireTimeMs: 36 * 1000
}),
max: 12,
windowMs: 12 * 1000,
statusCode: 429,
message: {type: 'error', error: 39, msg: 'Too many requests. Try again in a minute.'}
});
// Notification system setup
const rlib = require(path.join(dir_libraries, 'rlib.js'));
// End of init
// Begin: Statistics / Analytics module
let analytics = false;
fs.access(path.join(dir_svp, 'analytics.js'), fs.F_OK, (e) => {
if(!e){
analytics = require(path.join(dir_svp, 'analytics.js'));
logger.info('Loaded secure/analytics.js');
} else{
logger.warn('Module secure/analytics.js not found. No reports will be created.')
}
})
// Weather Module
require(path.join(dir_libraries, 'weather.js')).appHook(app, credentials.weather);
const webauthn = require(path.join(dir_libraries, 'webauthn.js'));
webauthn.appHook(app);
// End: Statistics / Analytics module
// Begin: Helper functions (svue libraries, etc.)
const svueLib = require(path.join(dir_libraries, 'svuelib.js'));
const dbf = { // Database Functions
createUser: (sessionAuth) => {
let usrn = sessionAuth.creds[0];
let pswd = cryptoHelper.decrypt(sessionAuth.creds[1]);
return new Promise((resolve, reject) => {
fetchSVUE('Gradebook', sessionAuth.domain, usrn, pswd, '<Parms><ChildIntID>0</ChildIntID></Parms>').catch(err => {
logger.error('dbf.createUser: failed to create user (requestSVUE failed)', err)
resolve({type: 'error', error: 'Internal server error'})
}).then(r => {
if(typeof r.Gradebook !== 'undefined'){ // All good
let assignments = svueLib.parseAssignments(r, true);
userdb.insertOne({
user: usrn,
domain: sessionAuth.domain,
created: new Date(),
profile: {
name: sessionAuth.name,
fullName: sessionAuth.fullName,
grade: sessionAuth.grade,
school: sessionAuth.school
},
notifier: {
enabled: false,
whitelisted: sessionAuth.whitelisted
},
version: 1,
items: assignments
}, (err, res) => {
if(err){
logger.error('dbf.createUser: failed to create user', err)
resolve({type: 'error', error: 'Internal server error'})}
else{
resolve({type: 'success', id: res.insertedId})}
});
}
else if(typeof r.RT_ERROR !== 'undefined'){
resolve({type: 'error', error: 42, msg: r.RT_ERROR.$.ERROR_MESSAGE})
}
else{
console.warn(`Gradebook data is missing for user ${req.session.auth.fullName} (${req.session.auth.user}).`)
resolve({type: 'error', error: 43, msg: 'Unable to fetch Gradebook. Did you change your password?'})
}
});
})
},
update: async (input, sessionAuth) => {
userdb.findOne(input).then(r => {
if (!r) {
logger.warn('Bad dbf.update request: ' + JSON.stringify(input));
}
else if(!r.version){
logger.info('db: updated user '+input.user+' to v1');
userdb.updateOne(input, {
'$set': {
profile: {
name: sessionAuth.name,
fullName: sessionAuth.fullName,
grade: sessionAuth.grade,
school: sessionAuth.school
},
'notifier.enabled': (r.notifier?(r.notifier.enabled):false),
version: 1
}
})
}
});
},
query: async (input) => {
let res = await userdb.findOne(input);
if(!res){return false}
return res
},
addItems: async (session, course, items, isNew) => {
let res = await userdb.updateOne({
domain: session.domain,
user: session.user
}, {
$addToSet: {
['items.' + course + '.items']: {
$each: items
}
},
$pull: {
['notifier.sent']: {
$in: items
}
}
});
if(isNew){
userdb.updateOne({
domain: session.domain,
user: session.user
}, {
$set: {
['items.'+course+'.timestamp']: new Date()
}
});
}
return res;
},
remItems: async (session, course, items) => {
let res = await userdb.updateOne({
domain: session.domain,
user: session.user
}, {
$pull: {
['items.' + course + '.items']: {
$in: items
}
},
$addToSet: { // Prevent notifier from sending out a notification for an item manually marked as "unseen"
['notifier.sent']: {
$each: items
}
}
});
return res;
},
logLogin: (user, domain, req) => {
return new Promise((res) => {
let ip = req.ip;
let ua = req.header('User-Agent');
userdb.updateOne({
domain: domain,
user: user
}, {
'$set': {
lastLogin: new Date()
}
}).then(r => {
logindb.insertOne({
time: new Date(),
user: user,
domain: domain,
ip: ip,
ua: ua
}).then(r => {
res(r);
})
})
});
}
}
// End of db functions
if(credentials.zipLookup) {
svcore.init(logger, credentials.zipLookup)
logger.info('Set zip code lookup key to *-'+credentials.zipLookup.slice(-4))
} else{
svcore.init(logger)
logger.warn('Missing zip code lookup key. Users will not be able to find districts by zip code.')
}
function auditRequest(auth, req, method, success, data){
if(analytics) {
analytics.audit(auth, req, method, success, data)}
}
// End of other template / helper functions
// Begin: Scheduled functions
const notifierCore = require(path.join(dir_libraries, 'notifier.js'));
let ntScheduling = {
// 24 checks on weekdays, 18 on weekends, total of 156 checks/week
weekdaySide: schedule.scheduleJob('15,45 12,15-17 * * 1-5', notifierCore.runNotifierCheck), // 2x/hr, 8 times total per day (weekdays)
weekdayMain: schedule.scheduleJob('30 6,7-11,13-14,18-23,0,2 * * 1-5', notifierCore.runNotifierCheck), // 1x/hr, 16 times total (weekdays)
weekend: schedule.scheduleJob('20 7-14,16-23,0,1 * * 0,6', notifierCore.runNotifierCheck), // 18 times / day total on weekends
}
function computePercentiles() {
let raw = {};
let out = [];
mdb.collection('accessHistory').find({
ts: {
$gte: moment().subtract('7', 'days').toDate()
},
method: 'gradebook'
}).toArray((e, r) => {
for(let i of r){
if(!raw[i.domain+'\\'+i.user]){raw[i.domain+'\\'+i.user] = 0}
raw[i.domain+'\\'+i.user] ++;
}
for(let i in raw){
out.push(raw[i]);
}
out = out.sort((a, b) => {return a-b});
landingStats.percentiles = out;
});
}
// End of scheduled functions
// Rest: Web server component
// Authentication middleware
app.use('/data/*', function (req, res, next) {
if (!req.session.auth) {
res.status(403).json({type: 'error', msg: 'Not authenticated'});
}
else {
next();
}
})
app.use('/data/secure/*', function (req, res, next) {
if (!req.session.sudo) {
res.status(200).json({type: 'auth', msg: 'Elevation Required'});
}
else if(req.session.sudo < Date.now()){
res.status(200).json({type: 'auth', msg: 'Elevation Required'});
}
else {
next();
}
})
// Rate limiting middleware
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/stats', function(req, res){
if(!req.header('Referer')){
res.status(403).json({error: 'Forbidden'});
return;
}
res.status(200).json({
ok: true
});
});
app.get('/dashboard', function(req, res){
if(req.session.auth || req.query.app === '1'){
res.sendFile(path.join(__dirname, 'protected', 'dashboard.html'));
}
else{
let reqPath = req.path.slice(1).split('/');
if(reqPath.slice(-1)[0] === '/'){
res.status(302).redirect(req.path.slice(0, -1))}
res.status(302).redirect('../signin?from=dashboard')
}
});
app.get('/signout', function(req, res){
delete req.session.auth;
res.sendFile(path.join(__dirname, 'public', 'signout.html'));
});
app.get('/signout/admin', function(req, res){
delete req.session.admAuth;
res.status(302).redirect('/?signout=true');
});
app.get('/signout/status', function(req, res){
req.session.destroy((err) => {
if(err){
logger.error('Failed to destroy session (/signout/status)!', err);
res.json({status: 'error', error: err.message})}
else{
setTimeout(() => {res.json({status: 'success'})}, 600);
}
})
})
app.post('/auth/setConsent', function(req, res){
if(!req.session.auth){
res.status(403).json({type: 'error', error: 'Not authorized'})
}
else{
if(!req.session.auth.pending){
res.status(403).json({type: 'error', error: 'No pending consent'})
}
else{
req.session.auth.pending = false; // prevent duplicate requests, disable pending flag
dbf.createUser(req.session.auth).then((r) => {
if(r.type === 'success'){
req.session.auth.id = r.id;
res.json({type: 'success'})}
else{
req.session.auth.pending = true; // allow user to retry
res.json({type: 'error', error: r.error})}
})
}
}
})
app.post('/signin', limiter, async function(req, res){
// Signin module for SVUE
let user, pass, domain, waOutput, type=0; // type 0 = standard (user/pass/domain), 1 = webauth (wa)
if (req.body.wa) {
// Signin w/ WA
// Return in format {type: (string)("success"|"error"), [error]: (number), [msg]: (string)}
type = 1;
waOutput = await webauthn.validateWASignin(req);
if (waOutput.ok) {
let account = await userdb.findOne({_id: new ObjectId(waOutput.uuid)});
if (!account) {
res.status(400).json({
code: 30,
error: 'The account tied to this credential no longer exists.'
})
return false;
}
if (typeof waOutput.encPass === 'string') {
user = account.user;
pass = cryptoHelper.decrypt(waOutput.encPass);
domain = account.domain;
}
else {
req.session.cookie.maxAge = 300000;
req.session.waTempAuth = {
uuid: waOutput.uuid,
keyId: waOutput.keyId
}
res.status(400).json({code: 33, error: 'Password missing; please re-enter your password.'});
return;
}
} else {
res.status(400).json(waOutput);
return false;
}
}
else {
// Standard signin (username, password, and domain)
if(typeof req.body.user !== 'string' || typeof req.body.pass !== 'string' || typeof req.body.domain !== 'string'){
// Signin with username, password, and domain
res.json({type: 'error', error: 30, msg: 'Malformed request / invalid data, try again.'});
return;
}
else if(!svcore.checkURL(req.body.domain)){
res.json({type: 'error', error: 31, msg: 'The domain provided is invalid.'});
return;
}
// Set credentials
user = req.body.user;
pass = req.body.pass;
domain = svcore.checkURL(req.body.domain);
}
let svResponse = await fetchSVUE('ChildList', domain, user, pass).catch((err) => {
if(err.code === 'ECONNRESET'){
res.json({type: 'error', error: 48, msg:'Synergy Server Down', msgExt: 'Your school\'s Synergy (Gradebook) server is down.'});
}
else{
logger.error('fetchSVUE request failed: ', err);
res.json({type: 'error', error: 49, msg: 'Req. Failed ('+err.code+')', msgExt: 'Your school\'s Synergy (Gradebook) server could not be reached ('+err.code+').'});
}
return false;
});
if (!svResponse) {
return; // request already failed, and a response has already been sent in the catch loop
}
else if(svResponse.RT_ERROR){
// request succeeded, but the Synergy server gave a bad response
if(svResponse.RT_ERROR.$.ERROR_MESSAGE === 'Invalid user id or password'){
res.json({type: 'error', error: 32, msg: 'The user name provided is invalid.'})
}
else if(svResponse.RT_ERROR.$.ERROR_MESSAGE === 'The user name or password is incorrect.\r\n'){
if (type === 1) {
req.session.cookie.maxAge = 300000;
req.session.waTempAuth = {
uuid: waOutput.uuid,
keyId: waOutput.keyId,
expectedUser: user
}
res.json({type: 'error', error: 'Please re-enter your password to continue.'})
} else {
res.json({type: 'error', error: 33, msg: 'The password provided is incorrect.'})
}
}
else{
logger.error('Unable to parse district StudentVUE login message.', svResponse.RT_ERROR);
console.log(svResponse.RT_ERROR);
res.json({type: 'error', error: 40, msg: 'An unknown error has occured on the district endpoint.'})
}
return;
}
// credentials are good
try {
let child = svResponse.ChildList.Child[0];
let firstName = child.$.ChildFirstName;
let fullName = child.ChildName[0];
let school = child.OrganizationName[0];
let grade = child.Grade[0];
// let photo = child.photo[0];
if (req.session.waTempAuth && req.session.waTempAuth.expectedUser === user) {
// update the password tied to this public key credential
webauthn.updateWACreds(req.session.waTempAuth.keyId, pass);
}
req.session.regenerate((err) => {
if(err){
logger.error('Unable to regenerate session (/signin)', err)
res.json({type: 'error', error: 'Unable to create session due to an internal server error.'})}
else{
dbf.query({user, domain}).then((r) => {
if(req.body.rem && req.body.rem !== 'false'){
if (type === 0) {
req.session.cookie.maxAge = 604800000; // 7 days
req.session.preserve = true;
}
else if (type === 1) {
req.session.wa = Math.floor(Date.now()/1000);
req.session.waKey = waOutput.keyId;
req.session.cookie.maxAge = 1209600000; // 14 days, but require PK authentication after 15 minutes
req.session.preserve = true;
}
}
else{
req.session.cookie.maxAge = 3600000
} // 1 hour
req.session.loginIP = req.ip;
req.session.lastAccessed = new Date();
req.session.ua = req.header('User-Agent');
req.session.ip = req.ip;
req.session.auth = {
id: r._id,
user: user,
domain: domain,
creds: [user, cryptoHelper.encrypt(pass)],
name: firstName,
fullName: fullName,
grade: grade,
school: school
};
if (child.ConcurrentSchools) {
// user is part of one or more concurrent schools
req.session.auth.concurrent = svcore.formatConcurrent(child.ConcurrentSchools);
}
if(!!r){
res.json({type: 'success', data: {
firstName: firstName,
fullName: fullName,
school: school,
expires: Date.now() + req.session.cookie.maxAge
}});
dbf.update({user, domain}, req.session.auth);
dbf.logLogin(user, domain, req);
}
else{
req.session.auth.pending = true;
res.json({type: 'success', data: {
firstName: firstName,
fullName: fullName,
school: school,
expires: Date.now() + req.session.cookie.maxAge,
new: true
}})
}
});
}
})
}
catch (err) {
logger.error('Unable to parse ChildList results -- the API may have changed.', err)
res.json({type: 'error', error: 41, msg: 'An internal server error occured.'})
}
})
app.post('/admin/signin', limiter, function(req, res){ // Admin signin
if (!localAdminCreds) {
res.json({type: 'error', error: 'This endpoint is currently disabled.'})
}
else if(typeof req.body.user !== 'string' || typeof req.body.pass !== 'string'){
res.json({type: 'error', error: 30, msg: 'Malformed request / invalid data, try again.'});
return;
}
else if(!localAdminCreds[req.body.user]){
setTimeout(() => {
res.json({type: 'error', error: 'Invalid credentials.'});
}, Math.round(Math.random() * 500 + 500));
return;
}
bcrypt.compare(req.body.pass, localAdminCreds[req.body.user]).then(valid => {
if(!valid){
res.json({type: 'error', error: 'Invalid credentials.'});
return;
}
req.session.regenerate((err) => {
if(err){
logger.error('Unable to regenerate session (/signin)', err)
res.json({type: 'error', error: 'Unable to create session due to an internal server error.'})}
else{
req.session.cookie.maxAge = 7200000;
req.session.admAuth = true;
res.json({type: 'success', data: {
expires: Date.now() + req.session.cookie.maxAge
}});
}
})
});
})
app.post('/signin/sudo', gbLimiter, function(req, res){
if(!req.session.auth){
res.status(403).json({type: 'error', error: 39, msg: 'Not Authenticated'})
}
else{
setTimeout(() => {
if(req.body.pass === cryptoHelper.decrypt(req.session.auth.creds[1])){
req.session.sudo = moment().add(30, 'minutes').toDate();
res.json({type: 'success'});
}
else{
res.json({type: 'error', error: 33, msg: 'The password provided is incorrect.'})
}
}, 500 + Math.round(Math.random() * 750));
}
})
app.post('/signin/lookup', limiter, function(req, res){
let inp = req.body.input;
if(typeof inp !== 'string'){
res.json({type: 'error', error: 30, msg: 'Malformed Request'});
return;
} else if (inp.length > 64 || inp.length < 3) {
res.json({type: 'error', error: 37, msg: 'Invalid URL / Zip Code'});
return;
}
if(inp.length <= 5){
svcore.getMatchingDistrictList(inp).then(r=>{
if(r.type === 'error'){
res.json({type: 'error', error: 37, msg: r.error});
} else{
res.json({type: 'success', list: r.list})
}
})
} else{
let url = svcore.checkURL(inp);
if(!url){
res.json({type: 'error', error: 37, msg: 'Invalid District URL'});
return;
}
svcore.validateDistrictURL(url).then(r => {
if(r){
res.json({type: 'success', url: url, name: r});
} else{
res.json({type: 'error', error: 37, msg: 'Invalid District URL'});
}
})
}
})
app.post('/signin/demo/auth', limiter, function(req, res){ // Signin module for SVUE
if (!credentials.demouser) {
res.json({type: 'error', code: 50, error: 'The demo account is not set up.'});
return;
}
let firstName = 'Student';
let fullName = 'Demo Student';
let school = 'Fossil Ridge HS';
req.session.regenerate((err) => {
if(err){
logger.error('Unable to regenerate session (/signin)', err)
res.json({type: 'error', error: 'Unable to create session due to an internal server error.'})}
else{
req.session.cookie.maxAge = 3600000; // demo account is signed out after an hour
req.session.auth = {
demo: true,
user: 'demo',
domain: 'svue.itsryan.org',
creds: ['demo', cryptoHelper.encrypt(credentials.demouser)],
name: 'Student',
fullName: 'Demo Student',
grade: '10',
school: 'Fossil Ridge HS'
};
res.json({type: 'success', data: {
firstName: firstName,
fullName: fullName,
school: school,
expires: Date.now() + req.session.cookie.maxAge
}});
}
})
})
app.get('/admin/notifier', function(req, res){
if(!req.session.admAuth){
res.status(403).json({type: 'error', error: 39, msg: 'Forbidden'});
return;
}
res.json({
type: 'success',
notifier: notifierCore.getStatus()
})
});
app.post('/admin/notifier', function(req, res){
if(!req.session.admAuth){
res.status(403).json({type: 'error', error: 39, msg: 'Forbidden'});
return;
}
let mode = req.body.enabled; // 0 = pull, 1 = push
mode = parseInt(mode);
if(mode !== 0 && mode !== 1){ // Missing component
res.status(400).json({type: 'error', error: 30, msg: 'Bad Request (0)'}); return}
else if(mode){
notifierCore.setStatus(true);
res.status(200).json({type: 'success'});
}
else{
notifierCore.setStatus(false);
res.status(200).json({type: 'success'});
}
})
app.post('/data/updateHistory', function(req, res){
if(req.session.auth.demo){ // don't modify demo account
res.json({type: 'success'});
}
else{
let course = req.body.course; // Course name
let data = req.body.data; // Array of item IDs
let mode = req.body.mode; // 0 = pull, 1 = push
mode = parseInt(mode);
if(typeof data !== 'string' || typeof course !== 'string' || (mode !== 0 && mode !== 1)){ // Missing component
res.status(400).json({type: 'error', error: 30, msg: 'Bad Request (0)'}); return}
if(data.indexOf(',') !== -1) {data = data.split(',')}
else{data = [data]}
if(data.length > 72 || JSON.stringify(data).length > 512){ // Data too big / long
res.status(400).json({type: 'error', error: 30, msg: 'Bad Request (1)'})
return}
dbf.query({user: req.session.auth.user, domain: req.session.auth.domain}).then((r) => {
if(!r){
res.status(500).json({type: 'error', error: 19, msg: 'Your Remchi account is missing. Contact us for assistance.'}); return}
if(r.items[course]){
dbf[mode?'addItems':'remItems'](req.session.auth, course, data).then((r, e) => {
res.json({type: 'success', response: r, error: e});
});
}
else if(req.session.courseList && req.session.courseList.indexOf(course) !== -1){ // course currently exists in the user's gradebook
if(mode){
dbf['addItems'](req.session.auth, course, data, true).then((r, e) => {
res.json({type: 'success', response: r, error: e});
});
}
else{
res.status(400).json({type: 'error', error: 30, msg: 'Bad Request - Empty Course', desc: 'Contact devs for assistance.'})
}
}
else{
res.status(400).json({type: 'error', error: 30, msg: 'Bad Request - Course Not Available', desc: 'Signing out and back in usually resolves this.'})
}
});
}
})
app.get('/data/gradebook', gbLimiter, function(req, res){
req.session.ip = req.ip;
req.session.lastAccessed = new Date();
if (req.query.reportingPeriod && req.query.reportingPeriod.match(/[^A-Za-z0-9\-]/) || req.query.school && req.query.school.match(/[^A-Za-z0-9\-]/)) {
// exclude bad characters
res.status(400).json({type: 'error', error: 28, msg: 'Bad Request'})
return;
}
fetchSVUE('Gradebook', req.session.auth.domain, req.session.auth.creds[0], cryptoHelper.decrypt(req.session.auth.creds[1]), `<Parms><ChildIntID>0</ChildIntID>${req.query.reportingPeriod?`<ReportPeriod>${req.query.reportingPeriod}</ReportPeriod>`:''}${req.query.school?`<ConcurrentSchOrgYearGU>${req.query.school}</ConcurrentSchOrgYearGU>`:''}</Parms>`).then(r => {
if(typeof r.Gradebook !== 'undefined'){ // All good
auditRequest(req.session.auth, req, 'gradebook', true, req.query.reportingPeriod?{reportingPeriod: req.query.reportingPeriod}:!1);
dbf.query({user: req.session.auth.user, domain: req.session.auth.domain}).then((acc) => {
if(!acc){res.status(500).json({type: 'error', error: 50, msg: 'Your Remchi account is missing (19).', desc: 'Signing out and signing back in may fix this problem. If that doesn\'t fix the problem, contact us for assistance.'}); return}
userdb.findOneAndUpdate({
domain: req.session.auth.domain,
user: req.session.auth.user
}, {
'$set': {
lastAccessed: new Date()
}
}).then (r2 => {
if (!req.session.courseList || !Array.isArray(req.session.courseList)) {
req.session.courseList = [];
}
let courseNames = Object.keys(svueLib.parseAssignments(r, true));
for (let i of courseNames) {
if (req.session.courseList.indexOf(i) === -1) {
req.session.courseList.push(i);
}
}
if(req.session.preserve) req.session.cookie.maxAge = 604800000;
res.json({
type: 'success',
sessionExpire: new Date(req.session.cookie.expires).getTime(),
user: {name: req.session.auth.name, fullName: req.session.auth.fullName, school: req.session.auth.school, concurrent: req.session.auth.concurrent},
courses: r.Gradebook.Courses[0].Course,
rp: (r.Gradebook.ReportingPeriod&&r.Gradebook.ReportingPeriods)?svcore.formatRP(r.Gradebook.ReportingPeriod,r.Gradebook.ReportingPeriods):null,
itemHist: acc.items,
svUUID: acc._id // unique user identifier for ga's user-id
// lastAccessed: r2.lastAccessed // Doesn't appear to currently work, not implemented
});
})
})
}
else if(typeof r.RT_ERROR !== 'undefined'){
auditRequest(req.session.auth, req, 'gradebook', false, r.RT_ERROR.$.ERROR_MESSAGE);
res.status(502).json({type: 'error', error: 42, msg: r.RT_ERROR.$.ERROR_MESSAGE})
}
else{
console.warn(`Gradebook data is missing for user ${req.session.auth.fullName} (${req.session.auth.user}).`)
auditRequest(req.session.auth, req, 'gradebook', false);
res.status(502).json({type: 'error', error: 43, msg: 'Unable to fetch Gradebook. Did you change your password?'})
}
}, err => {
if(err.code === 'ECONNRESET'){
auditRequest(req.session.auth, req, 'gradebook', false, 'ECONNRESET');
res.json({type: 'error', error: 48, msg: 'Your school\'s Synergy (Gradebook) server is down.'});
}
else{
auditRequest(req.session.auth, req, 'gradebook', false, err.code);
res.json({type: 'error', error: 49, msg: 'Your school\'s Synergy (Gradebook) server could not be reached ('+err.code+').'});
}
});
})
app.get('/data/secure/export/info', function(req, res) {
if(req.session.auth.user && req.session.auth.concurrent) {
res.json({
type: 'success',
user: req.session.auth.user,
domain: req.session.auth.domain,
school: req.session.auth.school,
name: req.session.auth.fullName,
concurrent: req.session.auth.concurrent
})
} else if(req.session.auth.user) {
res.json({
type: 'success',
user: req.session.auth.user,
domain: req.session.auth.domain,
school: req.session.auth.school,
name: req.session.auth.fullName
})
} else {
res.json({
type: 'error',
error: 'Missing user data - try signing in again'
})
}
})
app.post('/data/secure/export/createSession', async (req, res) => {
if(['xlsx', 'xml', 'json'].indexOf(req.body.format) === -1) {
res.status(400).json({
type: 'error',
msg: 'Bad request - invalid format'
});
return;
}
let gb = await fetchSVUE('Gradebook', req.session.auth.domain, req.session.auth.creds[0], cryptoHelper.decrypt(req.session.auth.creds[1]), `<Parms><ChildIntID>0</ChildIntID>${req.body.school=='h'?'':`<ConcurrentSchOrgYearGU>${req.body.school}</ConcurrentSchOrgYearGU>`}</Parms>`).catch(err => {
auditRequest(req.session.auth, req, 'export', false, err.code);
res.status(502).json({type: 'error', error: 49, msg: 'Your school\'s Synergy (Gradebook) server could not be reached ('+err.code+').'});
return;
});
if (gb.RT_ERROR) {
auditRequest(req.session.auth, req, 'export', false, gb.RT_ERROR.$.ERROR_MESSAGE);
res.status(502).json({type: 'error', error: 42, msg: gb.RT_ERROR.$.ERROR_MESSAGE});
return;
}
auditRequest(req.session.auth, req, 'export', true);
req.session.exportSession = {
exp: req.session.sudo,
school: req.body.school,
format: req.body.format,
rp: gb.Gradebook.ReportingPeriods?svcore.formatRP_partial(gb.Gradebook.ReportingPeriods):null
}
res.json({
type: 'success',
rp: req.session.exportSession.rp
})
return;
})
app.post('/data/secure/export/complete', async (req, res) => {
if (!req.session.exportSession || req.session.exportSession.exp < Date.now()) {
res.status(403).json({
type: 'error',
msg: 'Export session expired - create a new one by reloading the page'
});
return;
} else if (!req.body.rp) {
res.status(400).json({
type: 'error',
msg: 'Bad request'
});
return;
} else if (req.session.exportSession.complete) {
res.status(403).json({
type: 'error',
msg: 'User\'s export request has already been fulfilled - create a new one by reloading the page'
});
return;
}