-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
527 lines (482 loc) · 14.1 KB
/
server.mjs
File metadata and controls
527 lines (482 loc) · 14.1 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
import "dotenv/config";
import logger from "./logger.mjs";
import models from "./models.mjs";
const { User, Trip, TripSignUp } = models;
import errors from "./errors.mjs";
const {
AuthError,
NonexistenceError,
InvalidDataError,
IllegalOperationError
} = errors;
import { Sequelize } from "sequelize";
import queries from "./queries.mjs";
const {
getTrips,
getLeaders,
getBasicUserData,
getUserData,
getTripData,
createUser,
addPhone,
createTrip,
getTripParticipants,
getPossibleParticipantEmails,
taskUpdate,
tripUpdate,
openTrip,
addParticipant,
removeParticipant,
runLottery,
doAttendance,
tripSignup,
isSignedUp,
confirmSignup,
cancelSignup,
reportPaid,
listervAdd
} = queries;
import cron from "node-cron";
import jobs from "./server_jobs.mjs";
import https from "https";
import fs from "fs";
import axios from "axios";
//
//MIDDLEWARE
//
//Logs method and origin of incoming requests
async function logRequest(req, _res, next) {
logger.log(
`${req.method} request for ${req.path} received from ${req.connection.remoteAddress}:${req.connection.remotePort}`
);
next();
}
//Checks authentication of incoming requests
async function authenticate(req, res, next) {
try {
// Use the token to fetch data from an external API
const token = req.headers.authorization?.split(" ")[1];
// If the token is not a valid google token (or was not supplied), this axios request will fail
const response = await axios.get(
"https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
// If the token is valid but the user hasn't been seen, user will be Null
let user = await User.findOne({
where: {
email: response.data.email
}
});
if (user == null) {
if (response.data.email.endsWith("@brown.edu") || response.data.email.endsWith("@risd.edu")) {
user = await createUser(
response.data.given_name,
response.data.family_name ? response.data.family_name : "",
response.data.email
);
logger.log(`Created new user with email ${response.data.email}`);
} else {
throw Error("User does not have a Brown or RISD email address.");
}
}
//If no error occurs, we attach the user's id and continue
req.userId = user.id;
next();
} catch (error) {
// Continue as if the user is not authenticated
// Reasons we might have gotten here:
// - User did not send a token (ie. was looking for content on an unprotected route (standard practice!) OR sent a malformed request to a protected route)
// - User sent an invalid token (shouldn't happen under usual circumstances)
// - User sent a valid token that was associated with a non Brown or RISD account (frontend shouldn't let people complete login without a Brown or RISD account, so this shouldn't happen)
//logger.log("Authentication for user failed: " + error);
next();
}
}
//Replacement authentication for testing; Change TESTID to take actions on differing accounts
const TESTID = 1;
function phonyAuth(req, _res, next) {
req.userId = TESTID;
next();
}
//Throws an error if user isn't logged in
function loggedIn(req, _res, next) {
if (!req.userId) throw new AuthError();
next();
}
//Sanitizes tripId param and adds it as req.tripId
async function parseTripId(req, _res, next) {
let tripId = parseInt(req.params.tripId);
if (Number.isNaN(tripId))
throw new NonexistenceError("Trip signature improperly formed");
req.tripId = tripId;
next();
}
//Assuming req.tripId, adds the Trip object with that ID as req.Trip
async function grabTrip(req, _res, next) {
const trip = await Trip.findByPk(req.tripId);
if (!trip)
throw new NonexistenceError("Trip at specified tripId doesn't exist");
req.Trip = trip;
next();
}
//Assuming req.userId and req.tripId, adds the TripSignUp object with those as ids as req.TripSignUp
async function grabSignup(req, _res, next) {
const signup = await TripSignUp.findOne({
where: {
userId: req.userId,
tripId: req.tripId
}
});
if (!signup)
throw new NonexistenceError("User not signed up for specified trip");
if (signup.tripRole !== "Participant")
throw new NonexistenceError("User not a participant on specified trip");
req.Signup = signup;
next();
}
//Assuming req.userId, adds the User object with that id as req.User
async function grabUser(req, _res, next) {
const user = await User.findByPk(req.userId);
if (!user) throw new AuthError();
req.User = user;
next();
}
//Assuming req.userId and req.tripId, checks that associated user is a leader on the associated trip
async function tripLeaderCheck(req, _res, next) {
if (!(await isTripLeader(req.userId, req.tripId)))
throw new AuthError("Must be a trip leader to post to this route");
next();
}
async function isTripLeader(userId, tripId) {
//Has benefit of certifying tripId's validity
const signup = await TripSignUp.findOne({
where: {
userId: userId,
tripId: tripId
}
});
return signup && signup.tripRole == "Leader";
}
//Assuming req.User, checks to make sure the user is a Leader or an Admin
async function leaderPlusCheck(req, _res, next) {
if (!["Admin", "Leader"].includes(req.User.role))
throw new AuthError("Must be a leader (or admin) to post to this route");
next();
}
//Error handling utilities
const asyncHandler = (handler) => {
//Ugly wrapper to aid with error/rejected promise propogation
return async (req, res, next) => {
try {
await handler(req, res, next);
} catch (err) {
next(err);
}
};
};
const invalidRecast = (middleware) => {
return async (req, res, next) => {
try {
await middleware(req, res, next);
} catch (err) {
next(new InvalidDataError(err.message));
}
};
};
//Express app setup
import express from "express";
import { json, urlencoded } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
const app = express();
//
//REQUEST RESOLUTION PATH
//
//Configuration middleware
const ACCEPTED_ORIGIN = process.env.ACCEPTED_ORIGIN; //IP of static files server for production
const corsOptions = {
origin: [`${ACCEPTED_ORIGIN}`, "http://localhost:3000"],
credentials: true
};
app.use(cors(corsOptions)); //CORS options specifications
app.use(invalidRecast(json())); //Parse requests of content-type application/json so req.body is a JS object parsed from the original JSON
app.use(urlencoded({ extended: true })); //*huh* : Parse requests of content-type - application/x-www-form-urlencoded
app.use(cookieParser());
//General middleware
app.use(logRequest);
app.use(authenticate);
//app.use(phonyAuth);
let protectedRoutes = [
"/profile",
"/add-phone",
"/create-trip",
"/signup",
"trip/:tripId/*"
]; //Does not include trip/:tripId itself
app.use(protectedRoutes, loggedIn);
//Trip leader route handlers
const tripRouter = express.Router({ mergeParams: true });
tripRouter.use(asyncHandler(parseTripId));
tripRouter.use("/:subpath", loggedIn); //All routes except "/" itself require user to be logged in
tripRouter.use("/lead", asyncHandler(tripLeaderCheck));
tripRouter.use("/lead", asyncHandler(grabTrip)); //Go ahead and grab trip instance here
tripRouter.use("/participate", asyncHandler(grabSignup));
tripRouter.get(
"/",
asyncHandler(async (req, res) => {
res.status(200).json(await getTripData(req.tripId, req.userId));
})
);
tripRouter.get(
"/is-signed-up",
asyncHandler(async (req, res) => {
res.status(200).json(await isSignedUp(req.userId, req.tripId));
})
);
tripRouter.post(
"/signup",
asyncHandler(async (req, res) => {
await tripSignup(req.userId, req.tripId);
res.sendStatus(200);
})
);
tripRouter.get(
"/lead/participants",
asyncHandler(async (req, res) => {
res.status(200).json(await getTripParticipants(req.Trip));
})
);
tripRouter.get(
"/lead/all-possible-participants",
asyncHandler(async (req, res) => {
res.status(200).json(await getPossibleParticipantEmails(req.Trip));
})
);
tripRouter.post(
"/lead/task",
asyncHandler(async (req, res) => {
await taskUpdate(req.Trip, req.body);
res.sendStatus(200);
})
);
tripRouter.post(
"/lead/alter",
asyncHandler(async (req, res) => {
await tripUpdate(req.Trip, req.body);
res.sendStatus(200);
})
);
tripRouter.post(
"/lead/open",
asyncHandler(async (req, res) => {
await openTrip(req.Trip);
res.sendStatus(200);
})
);
tripRouter.post(
"/lead/lottery",
asyncHandler(async (req, res) => {
res.status(200).json(await runLottery(req.Trip));
})
);
tripRouter.post(
"/lead/add-participant",
asyncHandler(async (req, res) => {
res.status(200).json(await addParticipant(req.Trip));
})
);
tripRouter.post(
"/lead/remove-participant",
asyncHandler(async (req, res) => {
res.status(200).json(await removeParticipant(req.Trip, req.body));
})
);
tripRouter.post(
"/lead/attendance",
asyncHandler(async (req, res) => {
await doAttendance(req.Trip, req.body);
res.sendStatus(200);
})
);
tripRouter.post(
"/participate/confirm",
asyncHandler(async (req, res) => {
await confirmSignup(req.Signup);
res.sendStatus(200);
})
);
tripRouter.post(
"/participate/cancel",
asyncHandler(async (req, res) => {
await cancelSignup(req.Signup);
res.sendStatus(200);
})
);
tripRouter.post(
"/participate/pay",
asyncHandler(async (req, res) => {
await reportPaid(req.Signup);
res.sendStatus(200);
})
);
app.use("/trip/:tripId", tripRouter);
//User action route handlers
const userRouter = express.Router();
userRouter.use(loggedIn);
userRouter.use(asyncHandler(grabUser));
userRouter.get(
"/",
asyncHandler(async (req, res) => {
res.status(200).json(await getBasicUserData(req.User));
})
);
userRouter.get(
"/profile",
asyncHandler(async (req, res) => {
res.status(200).json(await getUserData(req.User));
})
);
userRouter.post(
"/add-phone",
asyncHandler(async (req, res) => {
if (!req.body.hasOwnProperty("phoneNum"))
throw new InvalidDataError("Request body lacking phoneNum field");
await addPhone(req.User, req.body.phoneNum);
res.sendStatus(200);
})
);
userRouter.post(
"/listserv-add",
asyncHandler(async (req, res) => {
await listervAdd(req.User);
res.sendStatus(200);
})
);
app.use("/user", userRouter);
//Leader action route handlers
const leaderRouter = express.Router();
leaderRouter.use(loggedIn);
leaderRouter.use(asyncHandler(grabUser));
leaderRouter.use(asyncHandler(leaderPlusCheck));
leaderRouter.post(
"/create-trip",
asyncHandler(async (req, res) => {
res.status(200).json(await createTrip(req.User, req.body));
})
);
app.use("/leader", leaderRouter);
//General route handlers
app.get(
"/trips",
asyncHandler(async (_req, res) => {
res.status(200).json(await getTrips());
})
);
app.get(
"/leaders",
asyncHandler(async (_req, res) => {
res.status(200).json(await getLeaders());
})
);
app.get(
"/public/leader-stats/:firstName/:lastName",
asyncHandler(async (req, res) => {
const { firstName, lastName } = req.params;
const count = await TripSignUp.count({
where: { tripRole: "Leader" },
include: [{
model: User,
where: { firstName, lastName }
}]
});
res.status(200).json({ totalTrips: count });
})
);
app.get(
"/public/leader-trips/:firstName/:lastName",
asyncHandler(async (req, res) => {
const { firstName, lastName } = req.params;
const trips = await TripSignUp.findAll({
where: { tripRole: "Leader" },
include: [{
model: User,
where: { firstName, lastName }
}, {
model: Trip // Ensure the Trip model is associated in your models.mjs
}]
});
// Format the data to match your frontend Trip interface
const formattedTrips = trips.map(signup => ({
tripId: signup.Trip.id,
tripName: signup.Trip.tripName,
date: signup.Trip.plannedDate,
sentenceDesc: signup.Trip.sentenceDesc,
lotteryInfo: "Hosted Trip"
}));
res.status(200).json(formattedTrips);
})
);
//Default route handler
app.use(
asyncHandler(async (_req, res) => {
throw new NonexistenceError(
"Welcome to the BOC's data server! You are receiving this message because the route you requested did not match any of our defined ones."
);
})
);
//Error handlers
app.use(async (err, _req, res, _next) => {
if (err instanceof Sequelize.BaseError) {
logger.log(err.message);
res.status(422).json({
errMessage:
"SQL operation failure. Possible sources: broken unique constraint, data too long, or data of wrong type"
});
} else if (err instanceof AuthError) {
res.status(401).json({ errMesssage: `${err}` });
} else if (err instanceof NonexistenceError) {
res.status(404).json({ errMessage: `${err}` });
} else if (err instanceof InvalidDataError) {
res.status(422).json({ errMessage: `${err}` });
} else if (err instanceof IllegalOperationError) {
res.status(403).json({ errMessage: `${err}` });
} else {
let msg;
if (err instanceof Error) {
msg = `${err} - stack: ${err.stack}`;
} else {
msg = `${err}`;
}
logger.log(`INTERNAL ERROR: ${msg}`);
res.status(500).json({ errMessage: `Internal Server Error: ${err}` });
}
});
//Handle global errors without shutting the whole program down
/*
process.on("unhandledRejection", (reason, promise) => {
let trace = '';
if (reason instanceof Error) { trace = reason.stack }
let err_msg = `FAILED PROMISE: ${promise} occurred because ${reason}\n${trace}`;
console.error(err_msg);
logger.log(err_msg);
});
process.on("uncaughtException", (reason, exception_origin) => {
let trace = '';
if (reason instanceof Error) { trace = reason.stack }
let err_msg = `EXCEPTION THROWN: ${exception_origin} occurred because ${reason}\n${trace}`;
console.error(err_msg);
logger.log(err_msg);
});
*/
//Initialize all server jobs
jobs.forEach((job) => cron.schedule(job.cronString, job.job));
//Set port, listen for requests
const PORT = process.env.PORT || 8080; // should be proxied behind nginx
app.listen(PORT, async () => {
await logger.start();
logger.log(`STARTUP: Running on port ${PORT}.`);
});