Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
634 lines (563 loc) · 22.4 KB
/
Copy pathserver.js
File metadata and controls
634 lines (563 loc) · 22.4 KB
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
const express = require("express");
const cookieParser = require("cookie-parser");
const favicon = require("serve-favicon");
const axios = require("axios");
const mongoose = require("mongoose");
const { OAuth2Client } = require("google-auth-library");
const path = require("path");
const config = require("./config/config");
const klasses = require("./data/klasses");
const problems = require("./data/problems");
const introMessage = require("./data/intro-message");
const outroMessage = require("./data/outro-message");
const tours = require("./data/tours");
const User = require("./models/user");
const Klass = require("./models/klass");
const Student = require("./models/student");
const Session = require("./models/session");
const Log = require("./models/log");
const asyncHandler = require("./middlewares/async-handler");
const googleAuth = require("./middlewares/google-auth");
const upgradeAuth = require("./middlewares/upgrade-auth");
const loggedInUser = require("./middlewares/logged-in-user");
const {
createAppAuth: createProblemAuthoringToolAuth,
createAuthRouter: createProblemAuthoringToolAuthRouter
} = require("./external-server/problem-authoring-tool/auth.js");
const { createProblemAuthoringToolRouter } = require("./external-server/problem-authoring-tool/routes");
const {
createAppAuth: createAiConsultantAuth,
createAuthRouter: createAiConsultantAuthRouter
} = require("./external-server/ai-consultant/src/lib/auth.js");
const { createAiConsultantRouter } = require("./external-server/ai-consultant/src/routes/index.js");
const { initUploadsDir } = require("./external-server/ai-consultant/src/lib/uploads.js");
const app = express();
// Config Settings
const PORT = config.PORT;
const MODE = config.MODE;
const MONGODB_URI = config.MONGODB_URI;
const GOOGLE_CLIENT_ID = config.GOOGLE_CLIENT_ID;
const client = new OAuth2Client(GOOGLE_CLIENT_ID);
const UPGRADE_HOST_URL = config.UPGRADE_HOST_URL;
const UPGRADE_BASE_URL = config.UPGRADE_BASE_URL;
const UPGRADE_CONTEXT = config.UPGRADE_CONTEXT;
const AI_CONSULTANT_PAPER_PDF = "ai-experiment-consultant-pele-2026.pdf";
const problemAuthoringToolAuth = createProblemAuthoringToolAuth({
googleClientId: GOOGLE_CLIENT_ID,
sessionSecret: config.SESSION_SECRET,
mode: MODE,
label: "problem-authoring-tool"
});
const aiConsultantAuth = createAiConsultantAuth({
googleClientId: GOOGLE_CLIENT_ID,
sessionSecret: config.SESSION_SECRET,
mode: MODE,
label: "ai-consultant"
});
initUploadsDir();
// DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
mongoose.set("strictQuery", false);
// Database connection
const connectDatabase = async () => {
mongoose.Promise = global.Promise;
await mongoose.connect(MONGODB_URI);
console.log("Database is connected");
}
// Connect database
(async () => {
await connectDatabase();
})().catch((err) => {
console.error(`${err.name}: ${err.message}`);
process.exit();
});
// Set view engine
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
// This has to do with "proxy_set_header X-Forwarded-For $remote_addr;" in nginx config file (/etc/nginx/sites-available/default)
app.set("trust proxy", true);
// Set middleware
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(favicon(path.join(__dirname, "public/asset/favicon/favicon.ico")));
// External app auth gates — these must run before express.static("public") so
// files under public/problem-authoring-tool/ and public/ai-consultant/ are not
// served without a valid shared external-app session.
const EXTERNAL_APP_PUBLIC_PATHS = ["/login", "/api/login", "/api/session", "/api/logout"];
const AI_CONSULTANT_PUBLIC_PATHS = [
...EXTERNAL_APP_PUBLIC_PATHS,
`/paper/${AI_CONSULTANT_PAPER_PDF}`
];
app.use("/problem-authoring-tool", (req, res, next) => {
problemAuthoringToolAuth.gatePath({
loginPath: "/problem-authoring-tool/login",
publicPaths: EXTERNAL_APP_PUBLIC_PATHS
})(req, res, next);
});
app.use("/ai-consultant", (req, res, next) => {
aiConsultantAuth.gatePath({
loginPath: "/ai-consultant/login",
publicPaths: AI_CONSULTANT_PUBLIC_PATHS
})(req, res, next);
});
// Set static server
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "views")));
// Create an axios instance for Upgrade API requests
const upgradeApiClient = axios.create({
baseURL: process.env.IS_DOCKER && UPGRADE_HOST_URL.includes("localhost")
? UPGRADE_HOST_URL.replace("localhost", "host.docker.internal")
: UPGRADE_HOST_URL,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
});
/* ==================== Health Check ==================== */
// Health check endpoint
app.get("/health", (req, res) => {
res.status(200).json({
status: "healthy",
timestamp: new Date().toISOString(),
service: "upgrade-demo-app"
});
});
/* ==================== Login/Home ==================== */
// Root Page
app.get("/", asyncHandler(async (req, res) => {
res.redirect("/home");
}));
// Root redirect (for backwards compatibility)
app.get("/", asyncHandler(async (req, res) => {
res.redirect("/home");
}));
// Login Page
app.get("/login", asyncHandler(async (req, res) => {
res.render("login", { googleClientId: GOOGLE_CLIENT_ID, upgradeContext: UPGRADE_CONTEXT });
}));
// Home Page
app.get("/home", googleAuth, asyncHandler(async (req, res) => {
res.render("home", { upgradeHostUrl: UPGRADE_HOST_URL, upgradeBaseUrl: UPGRADE_BASE_URL, upgradeContext: UPGRADE_CONTEXT, tours });
}));
// Download experiment file
app.get("/file/experiment/:filename", googleAuth, asyncHandler(async (req, res) => {
res.download(path.join(__dirname, `public/asset/experiment/${req.params.filename}`));
}));
/* ==================== External Apps ==================== */
app.use("/problem-authoring-tool", createProblemAuthoringToolAuthRouter({
auth: problemAuthoringToolAuth,
basePath: "/problem-authoring-tool",
googleClientId: GOOGLE_CLIENT_ID
}));
app.use("/ai-consultant", createAiConsultantAuthRouter({
auth: aiConsultantAuth,
basePath: "/ai-consultant",
googleClientId: GOOGLE_CLIENT_ID
}));
app.get(`/ai-consultant/paper/${AI_CONSULTANT_PAPER_PDF}`, (req, res, next) => {
res.sendFile(
path.join(__dirname, "external-server/ai-consultant/paper", AI_CONSULTANT_PAPER_PDF),
(err) => {
if (err) next(err);
}
);
});
app.get("/problem-authoring-tool", (req, res) => {
res.redirect("/problem-authoring-tool/");
});
app.get("/ai-consultant", (req, res) => {
res.redirect("/ai-consultant/");
});
app.get("/problem-authoring-tool/*", problemAuthoringToolAuth.guard({ loginPath: "/problem-authoring-tool/login" }), (req, res) => {
res.sendFile(path.join(__dirname, "public/problem-authoring-tool/index.html"));
});
app.get("/ai-consultant/*", aiConsultantAuth.guard({ loginPath: "/ai-consultant/login" }), (req, res) => {
res.sendFile(path.join(__dirname, "public/ai-consultant/index.html"));
});
/* ==================== QuizApp ==================== */
// Login Page
app.get("/quiz-app/student/login", googleAuth, asyncHandler(async (req, res) => {
const populatedUser = await req.user.populate({ path: "klasses", populate: { path: "students" } });
res.render("quiz-app/login", { klasses: populatedUser.klasses, upgradeHostUrl: UPGRADE_HOST_URL, upgradeContext: UPGRADE_CONTEXT });
}));
// Intro Page
app.get("/quiz-app/session/:id/intro", googleAuth, asyncHandler(async (req, res) => {
const foundSession = await Session.findById(req.params.id);
if (!foundSession) {
return res.redirect("/quiz-app/student/login");
}
const populatedSession = await foundSession.populate({ path: "student" });
const message = introMessage(populatedSession.student.name);
res.render("quiz-app/intro", { message, session: populatedSession, upgradeHostUrl: UPGRADE_HOST_URL });
}));
// Problem Page
app.get("/quiz-app/session/:id/problem", googleAuth, asyncHandler(async (req, res) => {
const foundSession = await Session.findById(req.params.id);
if (!foundSession) {
return res.redirect("/quiz-app/student/login");
}
if (foundSession.numAnswered >= problems.length) {
return res.redirect(`/quiz-app/session/${req.params.id}/outro`);
}
res.render("quiz-app/problem", { problem: problems[foundSession.numAnswered], session: foundSession, upgradeHostUrl: UPGRADE_HOST_URL, upgradeContext: UPGRADE_CONTEXT });
}));
// Outro Page
app.get("/quiz-app/session/:id/outro", googleAuth, asyncHandler(async (req, res) => {
const foundSession = await Session.findById(req.params.id);
if (!foundSession) {
return res.redirect("/quiz-app/student/login");
}
const populatedSession = await foundSession.populate({ path: "student" });
const message = outroMessage(populatedSession.student.name, foundSession.numCorrect);
res.render("quiz-app/outro", { message, session: populatedSession, upgradeHostUrl: UPGRADE_HOST_URL, upgradeContext: UPGRADE_CONTEXT });
}));
/* ==================== Admin Tool ==================== */
// Summary Page
app.get("/admin-tool/summary", googleAuth, asyncHandler(async (req, res) => {
const populatedUser = await req.user.populate({ path: "klasses", populate: { path: "students" } });
res.render("admin-tool/summary", { klasses: populatedUser.klasses });
}));
/* ==================== Dev Console ==================== */
// Console Page
app.get("/dev-console/console", googleAuth, asyncHandler(async (req, res) => {
res.render("dev-console/console");
}));
/* ==================== API ==================== */
// Login the user
app.post("/api/v1/login", asyncHandler(async (req, res) => {
// Verify the token
const { credential } = req.body;
let payload = null;
try {
const ticket = await client.verifyIdToken({
idToken: credential,
audience: GOOGLE_CLIENT_ID
});
payload = ticket.getPayload();
}
catch (err) {
throw { status: 401, message: "Failed to authorize the user, please log in" };
}
// Log in the user if the app is not being used by someone else
const loginUser = () => {
if (loggedInUser.exists && loggedInUser.email !== payload.email) {
const currentDate = new Date();
const loginDurationSeconds = Math.round((currentDate - loggedInUser.loggedInDate) / 1000);
const inactiveDurationSeconds = Math.round((currentDate - loggedInUser.lastActiveDate) / 1000);
if (loginDurationSeconds <= loggedInUser.maxLoginDurationSeconds &&
inactiveDurationSeconds <= loggedInUser.maxInactiveDurationSeconds) {
throw { status: 403, message: "Sorry, the app is currently being used by someone, please try again later." };
}
}
loggedInUser.email = payload.email;
loggedInUser.name = payload.name;
loggedInUser.loggedInDate = new Date();
loggedInUser.lastActiveDate = loggedInUser.loggedInDate;
loggedInUser.exists = true;
}
// Check if the user has signed up
const foundUser = await User.findOne({ email: payload.email });
if (foundUser) {
loginUser();
return res.cookie("session-token", credential).json({
message: "Successfully logged in the user"
});
}
// If the user has not signed up, create a new user
const newKlasses = [];
const newKlassIds = [];
for (const klass of klasses) {
const newKlass = new Klass({ period: klass.period, students: [] });
for (const studentName of klass.studentNames) {
const newStudent = new Student({ name: studentName, parentKlass: newKlass._id });
await newStudent.save();
newKlass.students.push(newStudent._id);
}
newKlasses.push(newKlass);
newKlassIds.push(newKlass._id);
}
const newUser = new User({ email: payload.email, name: payload.name, klasses: newKlassIds });
await newUser.save();
for (const newKlass of newKlasses) {
newKlass.parentUser = newUser._id;
await newKlass.save();
}
loginUser();
res.cookie("session-token", credential).json({
message: "Successfully signed up and logged in the user"
});
}));
// Logout the user
app.get("/api/v1/logout", googleAuth, asyncHandler(async (req, res) => {
if (loggedInUser.exists && loggedInUser.email === req.user.email) {
loggedInUser.exists = false;
}
res.clearCookie("session-token");
res.status(200).json({
message: "Successfully logged out the user"
});
}));
// Get students
app.get("/api/v1/students", googleAuth, asyncHandler(async (req, res) => {
const populatedUser = await req.user.populate({ path: "klasses", populate: { path: "students" } });
let students = [];
for (const klass of populatedUser.klasses) {
students.push.apply(students, klass.students);
}
res.status(200).json({
message: "Successfully got students",
students
});
}));
// Get sessions
app.get("/api/v1/sessions", googleAuth, asyncHandler(async (req, res) => {
const populatedSessions = await Session.find({ user: req.user._id }).populate({ path: "klass" }).populate({ path: "student" });
res.status(200).json({
message: "Successfully got sessions",
sessions: populatedSessions
});
}));
// Create a new session
app.post("/api/v1/session", googleAuth, asyncHandler(async (req, res) => {
const { studentId, startDate } = req.body;
const foundStudent = await Student.findById(studentId);
const newSession = new Session({ user: req.user._id, klass: foundStudent.parentKlass, student: foundStudent._id, startDate, durationSeconds: 0, numAnswered: 0, numCorrect: 0 });
await newSession.save();
res.status(200).json({
message: "Successfully created a new session",
session: newSession
});
}));
// Update a session by ID
app.put("/api/v1/session/:id", googleAuth, asyncHandler(async (req, res) => {
const { currentDate, answer } = req.body;
const foundSession = await Session.findById(req.params.id);
if (!foundSession) {
throw { status: 404, message: "Session not found" };
}
foundSession.durationSeconds = Math.round((new Date(currentDate) - new Date(foundSession.startDate)) / 1000);
if (answer === problems[foundSession.numAnswered].correctAnswer) {
foundSession.numCorrect++;
}
foundSession.numAnswered++;
const updatedSession = await Session.findByIdAndUpdate(foundSession._id, foundSession);
res.status(200).json({
message: "Successfully updated the session",
session: updatedSession
});
}));
// Delete a session by ID
app.delete("/api/v1/session/:id", googleAuth, asyncHandler(async (req, res) => {
const deletedSession = await Session.findByIdAndDelete(req.params.id);
res.status(200).json({
message: "Successfully deleted the session",
session: deletedSession
});
}));
// Clear sessions
app.delete("/api/v1/sessions", googleAuth, asyncHandler(async (req, res) => {
const result = await Session.deleteMany({ user: req.user._id });
res.status(200).json({
message: "Successfully cleared sessions",
result
});
}));
// Delete sessions by class
app.delete("/api/v1/sessions/class/:id", googleAuth, asyncHandler(async (req, res) => {
const foundKlass = await Klass.findById(req.params.id);
const result = await Session.deleteMany({ klass: foundKlass._id });
res.status(200).json({
message: "Successfully deleted sessions",
result
});
}));
// Delete sessions by student
app.delete("/api/v1/sessions/student/:id", googleAuth, asyncHandler(async (req, res) => {
const foundStudent = await Student.findById(req.params.id);
const result = await Session.deleteMany({ student: foundStudent._id });
res.status(200).json({
message: "Successfully deleted sessions",
result
});
}));
// Get logs
app.get("/api/v1/logs", googleAuth, asyncHandler(async (req, res) => {
const foundLogs = await Log.find({ user: req.user._id });
res.status(200).json({
message: "Successfully got logs",
logs: foundLogs
});
}));
// Create a new log
app.post("/api/v1/log", googleAuth, asyncHandler(async (req, res) => {
const { level, date, message } = req.body;
const newLog = new Log({ user: req.user._id, level, date, message });
await newLog.save();
res.status(200).json({
message: "Successfully created a new log",
log: newLog
});
}));
// Clear logs
app.delete("/api/v1/logs", googleAuth, asyncHandler(async (req, res) => {
const result = await Log.deleteMany({ user: req.user._id });
res.status(200).json({
message: "Successfully cleared logs",
result
});
}));
// Reset the database (only for development)
app.get("/api/v1/reset", googleAuth, asyncHandler(async (req, res, next) => {
if (MODE !== "DEV") {
return next();
}
console.log("Resetting the database...");
await User.deleteMany({});
await Klass.deleteMany({});
await Student.deleteMany({});
await Session.deleteMany({});
await Log.deleteMany({});
res.status(200).json({
message: "Successfully reset the database"
});
}));
// Get tours
app.get("/api/v1/tours", googleAuth, asyncHandler(async (req, res) => {
res.status(200).json({
message: "Successfully got tours",
tours
});
}));
/* ==================== UpGrade proxy endpoints ==================== */
// Get experiments
app.get("/api/v1/upgrade/experiments", googleAuth, upgradeAuth, asyncHandler(async (req, res) => {
try {
const response = await upgradeApiClient.get("/api/experiments", {
headers: { "Authorization": `Bearer ${req.upgradeToken}` }
});
res.status(response.status).json(response.data);
} catch (error) {
throw { status: error.response?.status || 500, message: error.message };
}
}));
// Create a new experiment
app.post("/api/v1/upgrade/experiments", googleAuth, upgradeAuth, asyncHandler(async (req, res) => {
try {
const response = await upgradeApiClient.post("/api/experiments", req.body, {
headers: {
"Authorization": `Bearer ${req.upgradeToken}`,
"Content-Type": "application/json"
}
});
res.status(response.status).json(response.data);
} catch (error) {
throw { status: error.response?.status || 500, message: error.message };
}
}));
// Delete an experiment by ID
app.delete("/api/v1/upgrade/experiments/:experimentId", googleAuth, upgradeAuth, asyncHandler(async (req, res) => {
try {
const response = await upgradeApiClient.delete(`/api/experiments/${req.params.experimentId}`, {
headers: { "Authorization": `Bearer ${req.upgradeToken}` }
});
res.status(response.status).json(response.data);
} catch (error) {
throw { status: error.response?.status || 500, message: error.message };
}
}));
// Save the metrics data
app.post("/api/v1/upgrade/metric/save", googleAuth, upgradeAuth, asyncHandler(async (req, res) => {
try {
const response = await upgradeApiClient.post("/api/metric/save", req.body, {
headers: {
"Authorization": `Bearer ${req.upgradeToken}`,
"Content-Type": "application/json"
}
});
res.status(response.status).json(response.data);
} catch (error) {
throw { status: error.response?.status || 500, message: error.message };
}
}));
// Clear the database
app.delete("/api/v1/upgrade/clearDB", googleAuth, upgradeAuth, asyncHandler(async (req, res) => {
try {
const response = await upgradeApiClient.delete("/api/v5/clearDB", {
headers: { "Authorization": `Bearer ${req.upgradeToken}` }
});
res.status(response.status).json(response.data);
} catch (error) {
throw { status: error.response?.status || 500, message: error.message };
}
}));
/* ==================== External App APIs ==================== */
app.use(
"/api/v1/problem-authoring-tool",
createProblemAuthoringToolRouter({ auth: problemAuthoringToolAuth.apiGuard })
);
app.use(
"/api/v1/ai-consultant",
aiConsultantAuth.apiGuard,
createAiConsultantRouter()
);
app.use("/api/v1/ai-consultant", (req, res) => {
res.status(404).json({
error: { code: "not_found", message: `No route for ${req.method} ${req.originalUrl}` }
});
});
app.use("/api/v1/ai-consultant", (err, req, res, next) => {
console.error("[ai-consultant] unhandled error:", err);
const status = err.status || 500;
res.status(status).json({
error: {
code: err.code || "internal_error",
message: err.expose ? err.message : "Internal server error"
}
});
});
/* ==================== Errors ==================== */
// API not found
app.get("/api/v1/*", (req, res) => {
throw { status: 404, message: "API not found" };
});
// Legacy API redirect (for backwards compatibility)
app.get("/api/v1/*", (req, res) => {
throw { status: 404, message: "API not found" };
});
// Page not found
app.get("*", (req, res) => {
throw { status: 404, message: "Page not found" };
});
// Handle errors
app.use((err, req, res, next) => {
const error = {
status: err.status || 500,
message: err.message || "Internal Server Error",
stack: err.stack
};
// Set status
res.status(error.status);
// Print the error to the console
if (MODE === "DEV") {
console.error(`Error: ${JSON.stringify(error, null, 2)}`);
}
// Respond with HTML page
if (req.accepts("html")) {
// Redirect to login if failed to authorize the user or the session has expired
if (error.status === 401 || error.status === 403) {
return res.redirect("/login");
}
return res.render("error", { error });
}
// Respond with JSON
if (req.accepts("json")) {
return res.json({ error });
}
// Default to plain text
res.type("txt").send(JSON.stringify({ error }, null, 2));
});
/* ==================== Listen ==================== */
// Listening port
app.listen(PORT, () => {
console.log(`Server is running localhost on port: ${PORT}`);
});