-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.ts
497 lines (452 loc) · 15.5 KB
/
api.ts
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
import express, { RequestHandler, Request, Response } from 'express';
import serverless from 'serverless-http';
import cors from 'cors';
import admin from 'firebase-admin';
import * as winston from 'winston';
import * as expressWinston from 'express-winston';
import { app as adminApp, env } from './firebase';
import PermissionsManager from './utils/permissionsManager';
import { HandlerError } from './utils/errors';
import {
acceptIDOLChanges,
getIDOLChangesPR,
rejectIDOLChanges,
requestIDOLPullDispatch
} from './API/siteIntegrationAPI';
import MembersDao from './dao/MembersDao';
import {
allMembers,
allApprovedMembers,
setMember,
deleteMember,
updateMember,
getUserInformationDifference,
reviewUserInformationChange,
generateMemberArchive
} from './API/memberAPI';
import { allTeams, setTeam, deleteTeam } from './API/teamAPI';
import {
getAllShoutouts,
getShoutouts,
giveShoutout,
hideShoutout,
deleteShoutout
} from './API/shoutoutAPI';
import {
createCoffeeChat,
getAllCoffeeChats,
updateCoffeeChat,
getCoffeeChatsByUser,
deleteCoffeeChat,
clearAllCoffeeChats,
getCoffeeChatBingoBoard,
checkMemberMeetsCategory,
runAutoChecker,
notifyMemberCoffeeChat,
getCoffeeChatSuggestions
} from './API/coffeeChatAPI';
import {
allSignInForms,
createSignInForm,
deleteSignInForm,
signIn,
signInFormExists,
signInFormExpired,
getSignInPrompt
} from './API/signInFormAPI';
import {
createTeamEvent,
deleteTeamEvent,
getAllTeamEventInfo,
getAllTeamEvents,
getTeamEvent,
updateTeamEvent,
clearAllTeamEvents,
requestTeamEventCredit,
getTeamEventAttendanceByUser,
updateTeamEventAttendance,
deleteTeamEventAttendance,
notifyMemberTeamEvents
} from './API/teamEventsAPI';
import {
getAllCandidateDeciderInstances,
createNewCandidateDeciderInstance,
deleteCandidateDeciderInstance,
getCandidateDeciderInstance,
updateCandidateDeciderRatingAndComment,
updateCandidateDeciderInstance,
getCandidateDeciderReviews
} from './API/candidateDeciderAPI';
import {
getAllDevPortfolios,
createNewDevPortfolio,
updateDevPortfolio,
deleteDevPortfolio,
makeDevPortfolioSubmission,
getDevPortfolio,
getAllDevPortfolioInfo,
getDevPortfolioInfo,
getUsersDevPortfolioSubmissions,
regradeSubmissions,
updateSubmissions
} from './API/devPortfolioAPI';
import { getWriteSignedURL, getReadSignedURL, deleteImage } from './API/imageAPI';
import DPSubmissionRequestLogDao from './dao/DPSubmissionRequestLogDao';
import AdminsDao from './dao/AdminsDao';
import { sendMail } from './API/mailAPI';
// Constants and configurations
const app = express();
const router = express.Router();
const PORT = process.env.PORT || 9000;
const allowAllOrigins = false;
export const isProd: boolean = env === 'staging' || env === 'prod';
export const enforceSession = true;
// eslint-disable-next-line no-nested-ternary
const allowedOrigins = allowAllOrigins
? [/.*/]
: isProd
? [/https:\/\/idol\.cornelldti\.org/, /.*--cornelldti-idol\.netlify\.app/]
: [/http:\/\/localhost:3000/];
// Middleware
app.use(
cors({
origin: allowedOrigins,
credentials: true
})
);
app.use(express.json({ limit: '50mb' }));
app.use(
expressWinston.logger({
transports: [new winston.transports.Console()],
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp(),
winston.format.align(),
winston.format.printf(
(info) =>
`${info.timestamp} ${info.level} - ${info.meta.req.method} ${info.meta.req.originalUrl} ${
info.meta.res.statusCode
} -- ${JSON.stringify(info.meta.req.body)}`
)
),
requestWhitelist: ['body', 'method', 'originalUrl'],
responseWhitelist: ['body', 'statusCode']
})
);
const getUserEmailFromRequest = async (request: Request): Promise<string | undefined> => {
const idToken = request.headers['auth-token'];
if (typeof idToken !== 'string') return undefined;
const decodedToken = await admin.auth(adminApp).verifyIdToken(idToken);
return decodedToken.email;
};
const loginCheckedHandler =
(handler: (req: Request, user: IdolMember) => Promise<Record<string, unknown>>): RequestHandler =>
async (req: Request, res: Response): Promise<void> => {
const userEmail = await getUserEmailFromRequest(req);
if (userEmail == null) {
res.status(440).json({ error: 'Not logged in!' });
return;
}
const user = await MembersDao.getCurrentOrPastMemberByEmail(userEmail);
if (!user) {
res.status(401).send({ error: `No user with email: ${userEmail}` });
return;
}
if (env === 'staging' && !(await PermissionsManager.isAdmin(user))) {
res.status(401).json({ error: 'Only admins users have permissions to the staging API!' });
}
try {
res.status(200).send(await handler(req, user));
} catch (error) {
if (error instanceof HandlerError) {
res.status(error.errorCode).send({ error: error.reason });
return;
}
res.status(500).send({ error: `Failed to handle the request due to ${error}.` });
}
};
const loginCheckedGet = (
path: string,
handler: (req: Request, user: IdolMember) => Promise<Record<string, unknown>>
) => router.get(path, loginCheckedHandler(handler));
const loginCheckedPost = (
path: string,
handler: (req: Request, user: IdolMember) => Promise<Record<string, unknown>>
) => router.post(path, loginCheckedHandler(handler));
const loginCheckedDelete = (
path: string,
handler: (req: Request, user: IdolMember) => Promise<Record<string, unknown>>
) => router.delete(path, loginCheckedHandler(handler));
const loginCheckedPut = (
path: string,
handler: (req: Request, user: IdolMember) => Promise<Record<string, unknown>>
) => router.put(path, loginCheckedHandler(handler));
// Members
router.get('/member', async (req, res) => {
const type = req.query.type as string | undefined;
let members;
switch (type) {
case 'all-semesters':
members = await MembersDao.getMembersFromAllSemesters();
break;
case 'approved':
members = await allApprovedMembers();
break;
default:
members = await allMembers();
}
res.status(200).json({ members });
});
router.get('/hasIDOLAccess/:email', async (req, res) => {
const member = await MembersDao.getCurrentOrPastMemberByEmail(req.params.email);
const adminEmails = await AdminsDao.getAllAdminEmails();
if (env === 'staging' && !adminEmails.includes(req.params.email)) {
res.status(200).json({ hasIDOLAccess: false });
}
res.status(200).json({
hasIDOLAccess: member !== undefined
});
});
loginCheckedPost('/member', async (req, user) => ({
member: await setMember(req.body, user)
}));
loginCheckedDelete('/member/:email', async (req, user) => {
await deleteMember(req.params.email, user);
return {};
});
loginCheckedPut('/member', async (req, user) => ({
member: await updateMember(req.body, user)
}));
loginCheckedGet('/memberDiffs', async (_, user) => ({
diffs: await getUserInformationDifference(user)
}));
loginCheckedPut('/memberDiffs', async (req, user) => ({
member: await reviewUserInformationChange(req.body.approved, req.body.rejected, user)
}));
loginCheckedPost('/member-archive', async (req, user) => ({
archive: await generateMemberArchive(req.body, user, req.query.semesters as number | undefined)
}));
// Teams
loginCheckedGet('/team', async () => ({ teams: await allTeams() }));
loginCheckedPut('/team', async (req, user) => ({
team: await setTeam(req.body, user)
}));
// should eventually make DELETE
loginCheckedPost('/team', async (req, user) => ({
team: await deleteTeam(req.body, user)
}));
// Images
loginCheckedGet('/image/:name(*)', async (req) => ({
url: await getReadSignedURL(req.params.name)
}));
loginCheckedGet('/image-signed-url/:name(*)', async (req) => ({
url: await getWriteSignedURL(req.params.name)
}));
loginCheckedDelete('/image/:name(*)', async (req) => {
await deleteImage(req.params.name);
return {};
});
// Shoutouts
loginCheckedGet('/shoutout/:email', async (req, user) => ({
shoutouts: await getShoutouts(req.params.email, req.query.type as 'given' | 'received', user)
}));
loginCheckedGet('/shoutout', async () => ({
shoutouts: await getAllShoutouts()
}));
loginCheckedPost('/shoutout', async (req, user) => ({
shoutout: await giveShoutout(req.body, user)
}));
loginCheckedPut('/shoutout', async (req, user) => {
await hideShoutout(req.body.uuid, req.body.hide, user);
return {};
});
loginCheckedDelete('/shoutout/:uuid', async (req, user) => {
await deleteShoutout(req.params.uuid, user);
return {};
});
// Coffee Chats
loginCheckedGet('/coffee-chat', async () => ({
coffeeChats: await getAllCoffeeChats()
}));
loginCheckedPost('/coffee-chat', async (req, user) => ({
coffeeChat: await createCoffeeChat(req.body, user)
}));
loginCheckedDelete('/coffee-chat', async (_, user) => {
await clearAllCoffeeChats(user);
return {};
});
loginCheckedDelete('/coffee-chat/:uuid', async (req, user) => {
await deleteCoffeeChat(req.params.uuid, user);
return {};
});
loginCheckedGet('/coffee-chat/:email', async (req, user) => {
const coffeeChats = await getCoffeeChatsByUser(user, req.params.email);
return { coffeeChats };
});
loginCheckedPut('/coffee-chat', async (req, user) => ({
coffeeChat: await updateCoffeeChat(req.body, user)
}));
loginCheckedGet('/coffee-chat-bingo-board', async () => {
const board = await getCoffeeChatBingoBoard();
return { board };
});
loginCheckedGet('/coffee-chat/:otherMemberEmail/:submitterEmail/:category', async (req) => {
const result = await checkMemberMeetsCategory(
req.params.otherMemberEmail,
req.params.submitterEmail,
decodeURIComponent(req.params.category)
);
return { result };
});
loginCheckedPut('/coffee-chat/autocheck/:uuid/', async (req, user) => ({
coffeeChat: await runAutoChecker(req.params.uuid, user)
}));
loginCheckedPost('/coffee-chat-reminder', async (req, user) => ({
info: await notifyMemberCoffeeChat(req, req.body, user)
}));
loginCheckedGet('/coffee-chat-suggestions/:email', async (req) => {
const suggestions = await getCoffeeChatSuggestions(req.params.email);
return { suggestions };
});
// Pull from IDOL
loginCheckedPost('/pullIDOLChanges', (_, user) => requestIDOLPullDispatch(user));
loginCheckedGet('/getIDOLChangesPR', (_, user) => getIDOLChangesPR(user));
loginCheckedPost('/acceptIDOLChanges', (_, user) => acceptIDOLChanges(user));
loginCheckedPost('/rejectIDOLChanges', (_, user) => rejectIDOLChanges(user));
// Sign In Form
loginCheckedPost('/signInExists', async (req, _) => ({
exists: await signInFormExists(req.body.id)
}));
loginCheckedPost('/signInExpired', async (req, _) => ({
expired: await signInFormExpired(req.body.id)
}));
loginCheckedPost('/signInCreate', async (req, user) =>
createSignInForm(req.body.id, req.body.expireAt, req.body.prompt, user)
);
loginCheckedPost('/signInDelete', async (req, user) => {
await deleteSignInForm(req.body.id, user);
return {};
});
loginCheckedPost('/signIn', async (req, user) => signIn(req.body.id, req.body.response, user));
loginCheckedPost('/signInAll', async (_, user) => allSignInForms(user));
loginCheckedGet('/signInPrompt/:id', async (req, _) => ({
prompt: await getSignInPrompt(req.params.id)
}));
// Team Events
loginCheckedPost('/team-event', async (req, user) => {
await createTeamEvent(req.body, user);
return {};
});
loginCheckedGet('/team-event/:uuid', async (req, user) => ({
event: await getTeamEvent(req.params.uuid, user)
}));
loginCheckedGet('/team-event', async (req, user) => ({
events: !req.query.meta_only ? await getAllTeamEvents(user) : await getAllTeamEventInfo()
}));
loginCheckedPut('/team-event', async (req, user) => ({
event: await updateTeamEvent(req.body, user)
}));
loginCheckedDelete('/team-event/:uuid', async (req, user) => {
await deleteTeamEvent(req.params.uuid, user);
return {};
});
loginCheckedDelete('/team-event', async (_, user) => {
await clearAllTeamEvents(user);
return {};
});
loginCheckedPost('/team-event-attendance', async (req, user) => ({
teamEventAttendance: await requestTeamEventCredit(req.body.request, user)
}));
loginCheckedGet('/team-event-attendance', async (_, user) => ({
teamEventAttendance: await getTeamEventAttendanceByUser(user)
}));
loginCheckedPut('/team-event-attendance', async (req, user) => ({
teamEventAttendance: await updateTeamEventAttendance(req.body, user)
}));
loginCheckedDelete('/team-event-attendance/:uuid', async (req, user) => {
await deleteTeamEventAttendance(req.params.uuid, user);
return {};
});
loginCheckedPost('/team-event-reminder', async (req, user) => ({
info: await notifyMemberTeamEvents(
req,
req.query.end_of_semester_reminder !== undefined,
req.body,
user
)
}));
// Candidate Decider
loginCheckedGet('/candidate-decider', async (_, user) => ({
instances: await getAllCandidateDeciderInstances(user)
}));
loginCheckedGet('/candidate-decider/:uuid', async (req, user) => ({
instance: await getCandidateDeciderInstance(req.params.uuid, user)
}));
loginCheckedGet('/candidate-decider/:uuid/review', async (req, user) => ({
reviews: await getCandidateDeciderReviews(req.params.uuid, user)
}));
loginCheckedPost('/candidate-decider', async (req, user) => ({
instance: await createNewCandidateDeciderInstance(req.body, user)
}));
loginCheckedPut('/candidate-decider', async (req, user) => ({
instance: await updateCandidateDeciderInstance(req.body, user)
}));
loginCheckedDelete('/candidate-decider/:uuid', async (req, user) =>
deleteCandidateDeciderInstance(req.params.uuid, user).then(() => ({}))
);
loginCheckedPut('/candidate-decider/rating-and-comment', (req, user) =>
updateCandidateDeciderRatingAndComment(
user,
req.body.uuid,
req.body.id,
req.body.rating,
req.body.comment
).then(() => ({}))
);
loginCheckedPost('/sendMail', async (req, user) => ({
info: await sendMail(req.body.to, req.body.subject, req.body.text, user)
}));
// Dev Portfolios
loginCheckedGet('/dev-portfolio', async (req, user) => ({
portfolios: !req.query.meta_only
? await getAllDevPortfolios(user)
: await getAllDevPortfolioInfo()
}));
loginCheckedGet('/dev-portfolio/:uuid', async (req, user) => ({
portfolioInfo: !req.query.meta_only
? await getDevPortfolio(req.params.uuid, user)
: await getDevPortfolioInfo(req.params.uuid)
}));
loginCheckedGet('/dev-portfolio/:uuid/submission', async (req, user) => ({
submissions: await getUsersDevPortfolioSubmissions(req.params.uuid, user)
}));
loginCheckedPost('/dev-portfolio', async (req, user) => ({
portfolio: await createNewDevPortfolio(req.body, user)
}));
loginCheckedPut('/dev-portfolio', async (req, user) => ({
portfolio: await updateDevPortfolio(req.body, user)
}));
loginCheckedDelete('/dev-portfolio/:uuid', async (req, user) =>
deleteDevPortfolio(req.params.uuid, user).then(() => ({}))
);
loginCheckedPost('/dev-portfolio/submission', async (req, user) => {
await DPSubmissionRequestLogDao.logRequest(user.email, req.body.uuid, req.body.submission);
return {
submission: await makeDevPortfolioSubmission(req.body.uuid, req.body.submission)
};
});
loginCheckedPut('/dev-portfolio/:uuid/submission/regrade', async (req, user) => ({
portfolio: await regradeSubmissions(req.params.uuid, user)
}));
loginCheckedPut('/dev-portfolio/:uuid/submission', async (req, user) => ({
portfolio: await updateSubmissions(req.params.uuid, req.body.updatedSubmissions, user)
}));
app.use('/.netlify/functions/api', router);
// Startup local server if not production (prod is serverless)
if (!isProd) {
app.listen(PORT, () => {
// eslint-disable-next-line no-console
console.log(`IDOL backend listening on port: ${PORT}`);
});
}
export const handler = serverless(app);