-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
2257 lines (2108 loc) · 81.5 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
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
// IMPORTANT: this must come first so that it can properly instrument our
// dependencies like `pg` and `express`.
const opentelemetry = require('@prairielearn/opentelemetry');
const Sentry = require('@prairielearn/sentry');
// `@sentry/tracing` must be imported before `@sentry/profiling-node`.
require('@sentry/tracing');
const { ProfilingIntegration } = require('@sentry/profiling-node');
const ERR = require('async-stacktrace');
const fs = require('fs');
const util = require('util');
const path = require('path');
const debug = require('debug')('prairielearn:' + path.basename(__filename, '.js'));
const favicon = require('serve-favicon');
const async = require('async');
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const Bowser = require('bowser');
const http = require('http');
const https = require('https');
const blocked = require('blocked');
const blockedAt = require('blocked-at');
const onFinished = require('on-finished');
const { v4: uuidv4 } = require('uuid');
const argv = require('yargs-parser')(process.argv.slice(2));
const multer = require('multer');
const { filesize } = require('filesize');
const url = require('url');
const { createProxyMiddleware } = require('http-proxy-middleware');
const compiledAssets = require('@prairielearn/compiled-assets');
const {
SCHEMA_MIGRATIONS_PATH,
initBatchedMigrations,
startBatchedMigrations,
stopBatchedMigrations,
} = require('@prairielearn/migrations');
const { logger, addFileLogging } = require('@prairielearn/logger');
const { config, loadConfig, setLocalsFromConfig } = require('./lib/config');
const load = require('./lib/load');
const awsHelper = require('./lib/aws.js');
const externalGrader = require('./lib/externalGrader');
const externalGraderResults = require('./lib/externalGraderResults');
const externalGradingSocket = require('./lib/externalGradingSocket');
const workspace = require('./lib/workspace');
const sqldb = require('@prairielearn/postgres');
const migrations = require('@prairielearn/migrations');
const error = require('@prairielearn/error');
const sprocs = require('./sprocs');
const news_items = require('./news_items');
const cron = require('./cron');
const socketServer = require('./lib/socket-server');
const serverJobs = require('./lib/server-jobs');
const freeformServer = require('./question-servers/freeform.js');
const cache = require('./lib/cache');
const { LocalCache } = require('./lib/local-cache');
const codeCaller = require('./lib/code-caller');
const assets = require('./lib/assets');
const namedLocks = require('@prairielearn/named-locks');
const nodeMetrics = require('./lib/node-metrics');
const { isEnterprise } = require('./lib/license');
const { enrichSentryScope } = require('./lib/sentry');
const lifecycleHooks = require('./lib/lifecycle-hooks');
process.on('warning', (e) => console.warn(e));
// If there is only one argument, legacy it into the config option
if (argv['_'].length === 1) {
argv['config'] = argv['_'][0];
argv['_'] = [];
}
if ('h' in argv || 'help' in argv) {
var msg = `PrairieLearn command line options:
-h, --help Display this help and exit
--config <filename>
<filename> and no other args Load an alternative config filename
--migrate-and-exit Run the DB initialization parts and exit
--exit Run all the initialization and exit
`;
console.log(msg);
process.exit(0);
}
/**
* Creates the express application and sets up all PrairieLearn routes.
* @return {import('express').Application} The express "app" object that was created.
*/
module.exports.initExpress = function () {
const app = express();
app.set('views', path.join(__dirname, 'pages'));
app.set('view engine', 'ejs');
app.set('trust proxy', config.trustProxy);
// These should come first so that we get instrumentation on all our requests.
if (config.sentryDsn) {
app.use(Sentry.Handlers.requestHandler());
if (config.sentryTracesSampleRate) {
app.use(Sentry.Handlers.tracingHandler());
}
}
// Set res.locals variables first, so they will be available on
// all pages including the error page (which we could jump to at
// any point.
app.use((req, res, next) => {
res.locals.asset_path = assets.assetPath;
res.locals.node_modules_asset_path = assets.nodeModulesAssetPath;
res.locals.compiled_script_tag = compiledAssets.compiledScriptTag;
next();
});
app.use(function (req, res, next) {
res.locals.config = config;
next();
});
app.use(function (req, res, next) {
setLocalsFromConfig(res.locals);
next();
});
// browser detection - data format is https://lancedikson.github.io/bowser/docs/global.html#ParsedResult
app.use(function (req, res, next) {
if (req.headers['user-agent']) {
res.locals.userAgent = Bowser.parse(req.headers['user-agent']);
} else {
res.locals.userAgent = null;
}
next();
});
// special parsing of file upload paths -- this is inelegant having it
// separate from the route handlers but it seems to be necessary
// Special handling of file-upload routes so that we can parse multipart/form-data
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fieldSize: config.fileUploadMaxBytes,
fileSize: config.fileUploadMaxBytes,
parts: config.fileUploadMaxParts,
},
});
config.fileUploadMaxBytesFormatted = filesize(config.fileUploadMaxBytes, {
base: 10,
round: 0,
});
app.post(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/uploads',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instance_question/:instance_question_id',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/assessment_instance/:assessment_instance_id',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/question/:question_id',
upload.single('file')
);
app.post('/pl/course/:course_id/question/:question_id', upload.single('file'));
app.post('/pl/course/:course_id/question/:question_id/file_view', upload.single('file'));
app.post('/pl/course/:course_id/question/:question_id/file_view/*', upload.single('file'));
app.post(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/settings',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/instance_admin/settings',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/course_admin/settings',
upload.single('file')
);
app.post('/pl/course/:course_id/course_admin/settings', upload.single('file'));
app.post('/pl/course/:course_id/course_admin/file_view', upload.single('file'));
app.post('/pl/course/:course_id/course_admin/file_view/*', upload.single('file'));
app.post(
'/pl/course_instance/:course_instance_id/instructor/course_admin/file_view',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/course_admin/file_view/*',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/instance_admin/file_view',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/instance_admin/file_view/*',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/file_view',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/file_view/*',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/question/:question_id/file_view',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/question/:question_id/file_view/*',
upload.single('file')
);
app.post(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/groups',
upload.single('file')
);
/**
* Function to strip "sensitive" cookies from requests that will be proxied
* to workspace hosts.
*/
function stripSensitiveCookies(proxyReq) {
const cookies = proxyReq.getHeader('cookie');
if (!cookies) return;
const items = cookies.split(';');
const filteredItems = items.filter((item) => {
const name = item.split('=')[0].trim();
return (
name !== 'pl_authn' &&
name !== 'pl_assessmentpw' &&
// The workspace authz cookies use a prefix plus the workspace ID, so
// we need to check for that prefix instead of an exact name match.
!name.startsWith('pl_authz_workspace_')
);
});
proxyReq.setHeader('cookie', filteredItems.join(';'));
}
// proxy workspaces to remote machines
let workspaceUrlRewriteCache = new LocalCache(config.workspaceUrlRewriteCacheMaxAgeSec);
const workspaceProxyOptions = {
target: 'invalid',
ws: true,
pathRewrite: async (path) => {
try {
const match = path.match('/pl/workspace/([0-9]+)/container/(.*)');
if (!match) throw new Error(`Could not match path: ${path}`);
const workspace_id = parseInt(match[1]);
let workspace_url_rewrite = workspaceUrlRewriteCache.get(workspace_id);
if (workspace_url_rewrite == null) {
debug(`pathRewrite: querying workspace_url_rewrite for workspace_id=${workspace_id}`);
const sql =
'SELECT q.workspace_url_rewrite' +
' FROM questions AS q' +
' JOIN variants AS v ON (v.question_id = q.id)' +
' WHERE v.workspace_id = $workspace_id;';
const result = await sqldb.queryOneRowAsync(sql, { workspace_id });
workspace_url_rewrite = result.rows[0].workspace_url_rewrite;
if (workspace_url_rewrite == null) workspace_url_rewrite = true;
workspaceUrlRewriteCache.set(workspace_id, workspace_url_rewrite);
}
debug(
`pathRewrite: found workspace_url_rewrite=${workspace_url_rewrite} for workspace_id=${workspace_id}`
);
if (!workspace_url_rewrite) {
return path;
}
var pathSuffix = match[2];
const newPath = '/' + pathSuffix;
return newPath;
} catch (err) {
logger.error(`Error in pathRewrite for path=${path}: ${err}`);
return path;
}
},
logLevel: 'silent',
logProvider: (_provider) => logger,
router: async (req) => {
const match = req.url.match(/^\/pl\/workspace\/([0-9]+)\/container\//);
if (!match) throw new Error(`Could not match URL: ${req.url}`);
const workspace_id = match[1];
const result = await sqldb.queryZeroOrOneRowAsync(
"SELECT hostname FROM workspaces WHERE id = $workspace_id AND state = 'running';",
{ workspace_id }
);
if (result.rows.length === 0) {
// If updating this message, also update the message our Sentry
// `beforeSend` handler.
throw error.make(404, 'Workspace is not running');
}
return `http://${result.rows[0].hostname}/`;
},
onProxyReq: (proxyReq) => {
stripSensitiveCookies(proxyReq);
},
onProxyReqWs: (proxyReq) => {
stripSensitiveCookies(proxyReq);
},
onError: (err, req, res) => {
logger.error(`Error proxying workspace request: ${err}`, {
err,
url: req.url,
originalUrl: req.originalUrl,
});
// Check to make sure we weren't already in the middle of sending a
// response before replying with an error 500
if (res && !res.headersSent) {
if (res.status && res.send) {
res.status(err.status ?? 500).send('Error proxying workspace request');
}
}
},
};
const workspaceProxy = createProxyMiddleware((pathname) => {
return pathname.match('/pl/workspace/([0-9])+/container/');
}, workspaceProxyOptions);
const workspaceAuthRouter = express.Router();
workspaceAuthRouter.use([
// We use a short-lived cookie to cache a successful
// authn/authz for a specific workspace. We run the following
// middlewares in this separate sub-router so that we can
// short-circuit out of authzWorkspaceCookieCheck if we find
// the workspace-authz cookie. Short-circuiting will exit this
// sub-router immediately, so we can either exit this
// sub-router by finding the cookie, or by running regular
// authn/authz.
require('./middlewares/authzWorkspaceCookieCheck'), // short-circuits if we have the workspace-authz cookie
require('./middlewares/date'),
require('./middlewares/authn'), // jumps to error handler if authn fails
require('./middlewares/authzWorkspace'), // jumps to error handler if authz fails
require('./middlewares/authzWorkspaceCookieSet'), // sets the workspace-authz cookie
]);
app.use('/pl/workspace/:workspace_id/container', [
cookieParser(),
(req, res, next) => {
// Needed for workspaceAuthRouter.
res.locals.workspace_id = req.params.workspace_id;
next();
},
workspaceAuthRouter,
workspaceProxy,
]);
// Limit to 5MB of JSON
app.use(bodyParser.json({ limit: 5 * 1024 * 1024 }));
app.use(bodyParser.urlencoded({ extended: false, limit: 5 * 1536 * 1024 }));
app.use(cookieParser());
app.use(passport.initialize());
if (config.devMode) app.use(favicon(path.join(__dirname, 'public', 'favicon-dev.ico')));
else app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
if ('localRootFilesDir' in config) {
logger.info(`localRootFilesDir: Mapping ${config.localRootFilesDir} into /`);
app.use(express.static(config.localRootFilesDir));
}
// To allow for more aggressive caching of static files served from public/,
// we use an `assets/` path that includes a cachebuster in the path.
// In requests for resources, the cachebuster will be a hash of the contents
// of `/public`, which we will compute at startup. See `lib/assets.js` for
// implementation details.
app.use(
'/assets/:cachebuster',
express.static(path.join(__dirname, 'public'), {
// In dev mode, assets are likely to change while the server is running,
// so we'll prevent them from being cached.
maxAge: config.devMode ? 0 : '31536000s',
immutable: true,
})
);
// This route is kept around for legacy reasons - new code should prefer the
// "cacheable" route above.
app.use(express.static(path.join(__dirname, 'public')));
app.use('/build/', compiledAssets.handler());
// To allow for more aggressive caching of files served from node_modules/,
// we insert a hash of the module version into the resource path. This allows
// us to treat those files as immutable and cache them essentially forever.
app.use(
'/cacheable_node_modules/:cachebuster',
express.static(path.join(__dirname, 'node_modules'), {
maxAge: '31536000s',
immutable: true,
})
);
// This is included for backwards-compatibility with pages that might still
// expect to be able to load files from the `/node_modules` route.
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
// Included for backwards-compatibility; new code should load MathJax from
// `/cacheable_node_modules` instead.
app.use('/MathJax', express.static(path.join(__dirname, 'node_modules', 'mathjax', 'es5')));
// Support legacy use of ace by v2 questions
app.use(
'/localscripts/calculationQuestion/ace',
express.static(path.join(__dirname, 'node_modules/ace-builds/src-min-noconflict'))
);
app.use(
'/javascripts/ace',
express.static(path.join(__dirname, 'node_modules/ace-builds/src-min-noconflict'))
);
// Middleware for all requests
// response_id is logged on request, response, and error to link them together
app.use(function (req, res, next) {
res.locals.response_id = uuidv4();
next();
});
// load accounting for requests
app.use(function (req, res, next) {
load.startJob('request', res.locals.response_id);
next();
});
app.use(function (req, res, next) {
onFinished(res, function (err, res) {
if (ERR(err, () => {})) {
logger.verbose('request on-response-finished error', {
err,
response_id: res.locals.response_id,
});
}
load.endJob('request', res.locals.response_id);
});
next();
});
// More middlewares
app.use(require('./middlewares/logResponse')); // defers to end of response
app.use(require('./middlewares/cors'));
app.use(require('./middlewares/date'));
app.use(require('./middlewares/effectiveRequestChanged'));
app.use('/pl/oauth2login', require('./pages/authLoginOAuth2/authLoginOAuth2'));
app.use('/pl/oauth2callback', require('./pages/authCallbackOAuth2/authCallbackOAuth2'));
app.use(/\/pl\/shibcallback/, require('./pages/authCallbackShib/authCallbackShib'));
if (isEnterprise()) {
if (config.hasAzure) {
app.use('/pl/azure_login', require('./ee/auth/azure/login'));
app.use('/pl/azure_callback', require('./ee/auth/azure/callback'));
}
app.use('/pl/auth/institution/:institution_id/saml', require('./ee/auth/saml/router'));
}
app.use('/pl/lti', require('./pages/authCallbackLti/authCallbackLti'));
app.use('/pl/login', require('./pages/authLogin/authLogin'));
if (config.devMode) {
app.use('/pl/dev_login', require('./pages/authLoginDev/authLoginDev'));
}
// disable SEB until we can fix the mcrypt issues
// app.use('/pl/downloadSEBConfig', require('./pages/studentSEBConfig/studentSEBConfig'));
app.use(require('./middlewares/authn')); // authentication, set res.locals.authn_user
app.use('/pl/api', require('./middlewares/authnToken')); // authn for the API, set res.locals.authn_user
if (isEnterprise()) {
app.use('/pl/prairietest/auth', require('./ee/auth/prairietest'));
}
// Must come before CSRF middleware; we do our own signature verification here.
app.use('/pl/webhooks/terminate', require('./webhooks/terminate'));
app.use(require('./middlewares/csrfToken')); // sets and checks res.locals.__csrf_token
app.use(require('./middlewares/logRequest'));
// load accounting for authenticated accesses
app.use(function (req, res, next) {
load.startJob('authed_request', res.locals.response_id);
next();
});
app.use(function (req, res, next) {
onFinished(res, function (err, res) {
if (ERR(err, () => {})) {
logger.verbose('authed_request on-response-finished error', {
err,
response_id: res.locals.response_id,
});
}
load.endJob('authed_request', res.locals.response_id);
});
next();
});
// clear all cached course code in dev mode (no authorization needed)
if (config.devMode) {
app.use(require('./middlewares/undefCourseCode'));
}
// clear cookies on the homepage to reset any stale session state
app.use(/^(\/?)$|^(\/pl\/?)$/, require('./middlewares/clearCookies'));
// some pages don't need authorization
app.use('/', [
function (req, res, next) {
res.locals.navPage = 'home';
next();
},
require('./pages/home/home'),
]);
app.use('/pl', [
function (req, res, next) {
res.locals.navPage = 'home';
next();
},
require('./pages/home/home'),
]);
app.use('/pl/settings', [
function (req, res, next) {
res.locals.navPage = 'user_settings';
next();
},
require('./pages/userSettings/userSettings'),
]);
app.use('/pl/enroll', [
function (req, res, next) {
res.locals.navPage = 'enroll';
next();
},
require('./pages/enroll/enroll'),
]);
app.use('/pl/logout', [
function (req, res, next) {
res.locals.navPage = 'logout';
next();
},
require('./pages/authLogout/authLogout'),
]);
app.use('/pl/password', [
function (req, res, next) {
res.locals.navPage = 'password';
next();
},
require('./pages/authPassword/authPassword'),
]);
app.use('/pl/news_items', [
function (req, res, next) {
res.locals.navPage = 'news';
next();
},
require('./pages/news_items/news_items.js'),
]);
app.use('/pl/news_item', [
function (req, res, next) {
res.locals.navPage = 'news';
next();
},
function (req, res, next) {
res.locals.navSubPage = 'news_item';
next();
},
require('./pages/news_item/news_item.js'),
]);
app.use('/pl/request_course', [
function (req, res, next) {
res.locals.navPage = 'request_course';
next();
},
require('./pages/instructorRequestCourse/instructorRequestCourse.js'),
]);
app.use('/pl/workspace/:workspace_id', [
(req, res, next) => {
res.locals.workspace_id = req.params.workspace_id;
next();
},
require('./middlewares/authzWorkspace'),
]);
app.use('/pl/workspace/:workspace_id', require('./pages/workspace/workspace'));
app.use('/pl/workspace/:workspace_id/logs', require('./pages/workspaceLogs/workspaceLogs'));
// dev-mode pages are mounted for both out-of-course access (here) and within-course access (see below)
if (config.devMode) {
app.use('/pl/loadFromDisk', [
function (req, res, next) {
res.locals.navPage = 'load_from_disk';
next();
},
require('./pages/instructorLoadFromDisk/instructorLoadFromDisk'),
]);
app.use('/pl/jobSequence', [
function (req, res, next) {
res.locals.navPage = 'job_sequence';
next();
},
require('./pages/instructorJobSequence/instructorJobSequence'),
]);
}
// Redirect plain course instance page either to student or instructor assessments page
app.use(/^(\/pl\/course_instance\/[0-9]+)\/?$/, (req, res, _next) => {
res.redirect(`${req.params[0]}/assessments`);
});
app.use(/^(\/pl\/course_instance\/[0-9]+\/instructor)\/?$/, (req, res, _next) => {
res.redirect(`${req.params[0]}/instance_admin/assessments`);
});
// is the course instance being accessed through the student or instructor page route
app.use('/pl/course_instance/:course_instance_id', function (req, res, next) {
res.locals.viewType = 'student';
next();
});
app.use('/pl/course_instance/:course_instance_id/instructor', function (req, res, next) {
res.locals.viewType = 'instructor';
next();
});
// all pages under /pl/course_instance require authorization
app.use('/pl/course_instance/:course_instance_id', [
require('./middlewares/authzCourseOrInstance'), // sets res.locals.course and res.locals.courseInstance
function (req, res, next) {
res.locals.urlPrefix = '/pl/course_instance/' + req.params.course_instance_id;
next();
},
function (req, res, next) {
res.locals.navbarType = 'student';
next();
},
require('./middlewares/ansifySyncErrorsAndWarnings.js'),
]);
// Some course instance student pages only require course instance authorization (already checked)
app.use(
'/pl/course_instance/:course_instance_id/news_items',
require('./pages/news_items/news_items.js')
);
app.use(
'/pl/course_instance/:course_instance_id/news_item',
require('./pages/news_item/news_item.js')
);
// Some course instance student pages only require the authn user to have permissions
app.use('/pl/course_instance/:course_instance_id/effectiveUser', [
require('./middlewares/authzAuthnHasCoursePreviewOrInstanceView'),
require('./pages/instructorEffectiveUser/instructorEffectiveUser'),
]);
// All course instance instructor pages require the authn user to have permissions
app.use('/pl/course_instance/:course_instance_id/instructor', [
require('./middlewares/authzAuthnHasCoursePreviewOrInstanceView'),
require('./middlewares/selectOpenIssueCount'),
function (req, res, next) {
res.locals.navbarType = 'instructor';
next();
},
function (req, res, next) {
res.locals.urlPrefix = '/pl/course_instance/' + req.params.course_instance_id + '/instructor';
next();
},
]);
// Some course instance instructor pages only require the authn user to have permissions (already checked)
app.use(
'/pl/course_instance/:course_instance_id/instructor/effectiveUser',
require('./pages/instructorEffectiveUser/instructorEffectiveUser')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/news_items',
require('./pages/news_items/news_items.js')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/news_item',
require('./pages/news_item/news_item.js')
);
// All other course instance student pages require the effective user to have permissions
app.use(
'/pl/course_instance/:course_instance_id',
require('./middlewares/authzHasCourseInstanceAccess')
);
// All other course instance instructor pages require the effective user to have permissions
app.use(
'/pl/course_instance/:course_instance_id/instructor',
require('./middlewares/authzHasCoursePreviewOrInstanceView')
);
// all pages under /pl/course require authorization
app.use('/pl/course/:course_id', [
require('./middlewares/authzCourseOrInstance'), // set res.locals.course
require('./middlewares/ansifySyncErrorsAndWarnings.js'),
require('./middlewares/selectOpenIssueCount'),
function (req, res, next) {
res.locals.navbarType = 'instructor';
next();
},
function (req, res, next) {
res.locals.urlPrefix = '/pl/course/' + req.params.course_id;
next();
},
]);
// Serve element statics. As with core PrairieLearn assets and files served
// from `node_modules`, we include a cachebuster in the URL. This allows
// files to be treated as immutable in production and cached aggressively.
app.use(
'/pl/static/cacheableElements/:cachebuster',
require('./pages/elementFiles/elementFiles')
);
app.use(
'/pl/course_instance/:course_instance_id/cacheableElements/:cachebuster',
require('./pages/elementFiles/elementFiles')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/cacheableElements/:cachebuster',
require('./pages/elementFiles/elementFiles')
);
app.use(
'/pl/course/:course_id/cacheableElements/:cachebuster',
require('./pages/elementFiles/elementFiles')
);
app.use(
'/pl/course_instance/:course_instance_id/cacheableElementExtensions/:cachebuster',
require('./pages/elementExtensionFiles/elementExtensionFiles')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/cacheableElementExtensions/:cachebuster',
require('./pages/elementExtensionFiles/elementExtensionFiles')
);
app.use(
'/pl/course/:course_id/cacheableElementExtensions/:cachebuster',
require('./pages/elementExtensionFiles/elementExtensionFiles')
);
// For backwards compatibility, we continue to serve the non-cached element
// files.
// TODO: if we can determine that these routes are no longer receiving
// traffic in the future, we can delete these.
app.use('/pl/static/elements', require('./pages/elementFiles/elementFiles'));
app.use(
'/pl/course_instance/:course_instance_id/elements',
require('./pages/elementFiles/elementFiles')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/elements',
require('./pages/elementFiles/elementFiles')
);
app.use('/pl/course/:course_id/elements', require('./pages/elementFiles/elementFiles'));
app.use(
'/pl/course_instance/:course_instance_id/elementExtensions',
require('./pages/elementExtensionFiles/elementExtensionFiles')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/elementExtensions',
require('./pages/elementExtensionFiles/elementExtensionFiles')
);
app.use(
'/pl/course/:course_id/elementExtensions',
require('./pages/elementExtensionFiles/elementExtensionFiles')
);
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// API ///////////////////////////////////////////////////////////////
app.use('/pl/api/v1', require('./api/v1'));
if (isEnterprise()) {
app.use('/pl/institution/:institution_id/admin', require('./ee/institution/admin'));
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Instructor pages //////////////////////////////////////////////////
// single assessment
app.use('/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id', [
require('./middlewares/selectAndAuthzAssessment'),
require('./middlewares/ansifySyncErrorsAndWarnings.js'),
require('./middlewares/selectAssessments'),
]);
app.use(
/^(\/pl\/course_instance\/[0-9]+\/instructor\/assessment\/[0-9]+)\/?$/,
(req, res, _next) => {
res.redirect(`${req.params[0]}/questions`);
}
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id',
function (req, res, next) {
res.locals.navPage = 'assessment';
next();
}
);
app.use('/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/settings', [
function (req, res, next) {
res.locals.navSubPage = 'settings';
next();
},
require('./pages/instructorAssessmentSettings/instructorAssessmentSettings'),
]);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/questions',
[
function (req, res, next) {
res.locals.navSubPage = 'questions';
next();
},
require('./pages/instructorAssessmentQuestions/instructorAssessmentQuestions'),
]
);
app.use('/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/groups', [
function (req, res, next) {
res.locals.navSubPage = 'groups';
next();
},
require('./pages/instructorAssessmentGroups/instructorAssessmentGroups'),
]);
app.use('/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/access', [
function (req, res, next) {
res.locals.navSubPage = 'access';
next();
},
require('./pages/instructorAssessmentAccess/instructorAssessmentAccess'),
]);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/assessment_statistics',
[
function (req, res, next) {
res.locals.navSubPage = 'assessment_statistics';
next();
},
require('./pages/instructorAssessmentStatistics/instructorAssessmentStatistics'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/question_statistics',
[
function (req, res, next) {
res.locals.navSubPage = 'question_statistics';
next();
},
require('./pages/shared/assessmentStatDescriptions'),
require('./pages/shared/floatFormatters'),
require('./pages/instructorAssessmentQuestionStatistics/instructorAssessmentQuestionStatistics'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/downloads',
[
function (req, res, next) {
res.locals.navSubPage = 'downloads';
next();
},
require('./pages/instructorAssessmentDownloads/instructorAssessmentDownloads'),
]
);
app.use('/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/uploads', [
function (req, res, next) {
res.locals.navSubPage = 'uploads';
next();
},
require('./pages/instructorAssessmentUploads/instructorAssessmentUploads'),
]);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/regrading',
[
function (req, res, next) {
res.locals.navSubPage = 'regrading';
next();
},
require('./pages/instructorAssessmentRegrading/instructorAssessmentRegrading'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/instances',
[
function (req, res, next) {
res.locals.navSubPage = 'instances';
next();
},
require('./pages/instructorAssessmentInstances/instructorAssessmentInstances'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/file_edit',
[
function (req, res, next) {
res.locals.navSubPage = 'file_edit';
next();
},
require('./pages/instructorFileEditor/instructorFileEditor'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/file_view',
[
function (req, res, next) {
res.locals.navSubPage = 'file_view';
next();
},
require('./pages/instructorFileBrowser/instructorFileBrowser'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/file_download',
require('./pages/instructorFileDownload/instructorFileDownload')
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/manual_grading/assessment_question/:assessment_question_id',
[
function (req, res, next) {
res.locals.navSubPage = 'manual_grading';
next();
},
require('./middlewares/selectAndAuthzAssessmentQuestion'),
require('./pages/instructorAssessmentManualGrading/assessmentQuestion/assessmentQuestion'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/manual_grading/instance_question/:instance_question_id',
[
function (req, res, next) {
res.locals.navSubPage = 'manual_grading';
next();
},
require('./middlewares/selectAndAuthzInstanceQuestion'),
require('./pages/instructorAssessmentManualGrading/instanceQuestion/instanceQuestion'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/instance_question/:instance_question_id/clientFilesQuestion',
[
require('./middlewares/selectAndAuthzInstanceQuestion'),
require('./pages/clientFilesQuestion/clientFilesQuestion'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/instance_question/:instance_question_id/generatedFilesQuestion',
[
require('./middlewares/selectAndAuthzInstanceQuestion'),
require('./pages/generatedFilesQuestion/generatedFilesQuestion'),
]
);
// Submission files
app.use(
'/pl/course_instance/:course_instance_id/instructor/instance_question/:instance_question_id/submission/:submission_id/file',
[
require('./middlewares/selectAndAuthzInstanceQuestion'),
require('./pages/submissionFile/submissionFile'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment/:assessment_id/manual_grading',
[
function (req, res, next) {
res.locals.navSubPage = 'manual_grading';
next();
},
require('./pages/instructorAssessmentManualGrading/assessment/assessment'),
]
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/assessment_instance/:assessment_instance_id',
[
require('./middlewares/selectAndAuthzAssessmentInstance'),
require('./pages/shared/floatFormatters'),
require('./pages/instructorAssessmentInstance/instructorAssessmentInstance'),
]
);
// single question
app.use('/pl/course_instance/:course_instance_id/instructor/question/:question_id', [
require('./middlewares/selectAndAuthzInstructorQuestion'),
require('./middlewares/ansifySyncErrorsAndWarnings.js'),
]);
app.use(
/^(\/pl\/course_instance\/[0-9]+\/instructor\/question\/[0-9]+)\/?$/,
(req, res, _next) => {
// Redirect legacy question URLs to their preview page.
// We need to maintain query parameters like `variant_id` so that the
// preview page can render the correct variant.
const newUrl = `${req.params[0]}/preview`;
const newUrlParts = url.parse(newUrl);
newUrlParts.query = req.query;
res.redirect(url.format(newUrlParts));
}
);
app.use(
'/pl/course_instance/:course_instance_id/instructor/question/:question_id',
function (req, res, next) {
res.locals.navPage = 'question';