-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
349 lines (282 loc) · 9.73 KB
/
app.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
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import rateLimiter from 'express-rate-limit';
import pkg from 'uuid';
import expressWinston from 'express-winston';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import { initialize } from 'express-openapi';
import swaggerUI from 'swagger-ui-express';
import config from './config/config.js';
import { barfPlease, systemStatus } from './api/controllers/public/status.js';
import errorHandler from './api/helpers/error.js';
import apiDoc from './api/routes/api-doc.js';
import coachPaths from './api/routes/paths/coach/index.js';
import extPaths from './api/routes/paths/ext/index.js';
import glpPaths from './api/routes/paths/glp/index.js';
import localPaths from './api/routes/paths/local/index.js';
import publicPaths from './api/routes/paths/public/index.js';
import tabPaths from './api/routes/paths/tab/index.js';
import userPaths from './api/routes/paths/user/index.js';
import {
auth,
keyAuth,
tabAuth,
coachAuth,
localAuth,
} from './api/helpers/auth.js';
import db from './api/helpers/db.js';
import { debugLogger, requestLogger, errorLogger } from './api/helpers/logger.js';
const { v4: uuid } = pkg;
const app = express();
// Startup log message
debugLogger.info('Initializing API...');
// Enable Helmet security
app.use(helmet());
// Add a unique UUID to every request, and add the configuration for easy
// transport
//
// Database handle volleyball; don't have to call it in every last route. For I
// am lazy, and apologize not.
app.use((req, res, next) => {
req.uuid = uuid();
req.config = config;
req.db = db;
return next();
});
// Enable getting forwarded client IP from proxy
app.enable('trust proxy', 1);
app.get('/v1/ip', (request, response) => response.send(request.ip));
// Rate limit all requests
const limiter = rateLimiter({
windowMs : config.RATE_WINDOW || 15 * 60 * 1000 , // 15 minutes
max : config.RATE_MAX || 10000 , // limit each IP to 100000 requests per windowMs
});
app.use(limiter);
const messageLimiter = rateLimiter({
windowMs : config.MESSAGE_RATE_WINDOW || 15 * 1000 , // 30 seconds
max : config.MESSAGE_RATE_MAX || 1 , // limit each to 2 blasts requests per 30 seconds
message : `
You have reached your rate limit on messages which is ${config.MESSAGE_RATE_MAX} .
Please do not blast people that persistently.
`,
});
// Can we find a way to match these on the last verb? -- CLP, dreaming instead of googling.
app.use('/v1/tab/:tournId/round/:roundId/message', messageLimiter);
app.use('/v1/tab/:tournId/round/:roundId/blast', messageLimiter);
app.use('/v1/tab/:tournId/round/:roundId/poke', messageLimiter);
app.use('/v1/tab/:tournId/timeslot/:timeslotId/message', messageLimiter);
app.use('/v1/tab/:tournId/timeslot/:timeslotId/blast', messageLimiter);
app.use('/v1/tab/:tournId/timeslot/:timeslotId/poke', messageLimiter);
app.use('/v1/tab/:tournId/section/:sectionId/blastMessage', messageLimiter);
app.use('/v1/tab/:tournId/section/:sectionId/blastPairing', messageLimiter);
app.use('/v1/tab/:tournId/section/:sectionId/poke', messageLimiter);
const searchLimiter = rateLimiter({
windowMs : config.SEARCH_RATE_WINDOW || 30 * 1000 , // 30 seconds
max : config.SEARCH_RATE_MAX || 5 , // limit each to 5 search requests per 30 seconds
});
app.use('/v1/public/search', searchLimiter);
// Enable CORS Access, hopefully in a way that means I don't
// have to fight with it ever again.
const corsOptions = {
methods : ['GET', 'POST', 'DELETE', 'PUT'],
optionsSuccessStatus : 204,
credentials : true,
origin : config.CORS_ORIGINS,
};
app.use('/v1', cors(corsOptions));
// Parse body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: ['json', 'application/*json'], limit: '10mb' }));
app.use(bodyParser.text({ type: '*/*', limit: '10mb' }));
debugLogger.info(`Loading environment ${process.env?.NODE_ENV}`);
if (process.env.NODE_ENV === 'development') {
// Pretty print JSON in the dev environment
app.use(bodyParser.json());
app.set('json spaces', 4);
}
// Parse cookies and add them to the session
app.use(cookieParser());
// Authentication. Context depends on the sub-branch so that secondary
// functions do not have to handle it in every call.
app.all(['/v1/user/*', '/v1/user/:dataType/:id', '/v1/user/:dataType/:id/*'], async (req, res, next) => {
try {
// Everything under /user should be a logged in user; and all functions there
// apply only to the logged in user; no parameters allowed.
// For /user/judge/ID, /user/student/ID, /user/entry/ID, /user/checker/ID,
// /user/prefs/ID, check the perms against additional data
req.session = await auth(req, res);
if (!req.session) {
return res.status(401).json('User: You are not logged in');
}
} catch (err) {
next(err);
}
next();
});
const tabRoutes = [
'/v1/tab/:tournId',
'/v1/tab/:tournId/:subType',
'/v1/tab/:tournId/:subType/:typeId',
'/v1/tab/:tournId/:subType/:typeId/*',
'/v1/tab/:tournId/:subType/:typeId/*/*',
'/v1/tab/:tournId/:subType/:typeId/*/*/*',
];
app.all(tabRoutes, async (req, res, next) => {
try {
// Functions that require tabber or owner permissions to a tournament overall
req.session = await auth(req, res);
if (!req.session) {
return res.status(401).json('Tab: You are not logged in');
}
req.session = await tabAuth(req, res);
if (typeof req.session?.perms !== 'object') {
return res.status(401).json('You do not have access to that tournament area');
}
} catch (err) {
next(err);
}
next();
});
const coachRoutes = [
'/v1/coach/:chapterId',
'/v1/coach/:chapterId/*',
];
app.all(coachRoutes, async (req, res, next) => {
// apis related to the coach or directors of a program. Prefs only
// access is in the /user/prefs directory because it's such a bizarre
// one off
req.session = await auth(req, res);
if (req.session) {
const chapter = await coachAuth(req, res);
if (typeof chapter === 'object' && chapter.id === parseInt(req.params.chapterId)) {
req.chapter = chapter;
} else {
return res.status(401).json(`You do not have access to that institution`);
}
} else {
return res.status(401).json('Coach: You are not currently logged in to Tabroom');
}
next();
});
const localRoutes = [
'/v1/local/:localType/:localId',
'/v1/local/:localType/:localId/*',
];
app.all(localRoutes, async (req, res, next) => {
// apis related to administrators of districts (the committee), or a
// region, or an NCFL diocese, or a circuit.
try {
req.session = await auth(req, res);
if (req.session) {
const response = await localAuth(req, res);
if (typeof answer === 'object') {
req[req.params.localType] = response.local;
req.session.perms = { ...req.session.perms, ...response.perms };
next();
}
} else {
return res.status(401).json('Local: You are not currently logged in to Tabroom');
}
} catch (err) {
next(err);
}
next();
});
app.all(['/v1/ext/:area', '/v1/ext/:area/*', '/v1/ext/:area/:tournId/*'], async (req, res, next) => {
// All EXT requests are from external services and sources that do not
// necessarily hook into the Tabroom authentication methods. They must
// have instead a basic authentication header with a Tabroom ID and
// corresponding api_key setting for an account in person_settings.
// Certain endpoints might be authorized to only some person accounts, such
// as site admins for internal NSDA purposes, or Hardy because that guy is
// super shady and I need to keep a specific eye on him.
try {
req.session = await keyAuth(req, res);
if (!req.session?.person) {
req.session = await auth(req, res);
if (!req.session?.settings[`api_auth_${req.params.area}`]) {
return res.status(401).json(`That function is not accessible to your API credentials. Key ${req.params.area} required`);
}
}
if (!req.session?.person) {
return res.status(401).json(`That function is not accessible to your API credentials. Key ${req.params.area} required`);
}
} catch (err) {
return next(err);
}
next();
});
app.all('/v1/glp/*', async (req, res, next) => {
// GLP are Godlike Powers; aka site administrators
try {
req.session = await auth(req, res);
if (!req.session) {
return res.status(401).json('GLP: You are not logged in');
}
if (!req.session?.site_admin) {
return res.status(401).json('That function is accessible to Tabroom site administrators only');
}
} catch (err) {
next(err);
}
next();
});
const systemPaths = [
{ path : '/status', module : systemStatus },
{ path : '/barf', module : barfPlease },
];
// Combine the various paths into one
const paths = [
...systemPaths,
...coachPaths,
...extPaths,
...glpPaths,
...localPaths,
...publicPaths,
...tabPaths,
...userPaths,
];
// Initialize OpenAPI middleware
const apiDocConfig = initialize({
app,
apiDoc,
paths,
promiseMode : true,
docsPath : '/docs',
errorMiddleware : errorHandler,
});
// Log global errors with Winston
app.use(expressWinston.errorLogger({
winstonInstance : errorLogger,
meta : true,
dynamicMeta: (req, res, next) => {
return {
logCorrelationId: req.uuid,
};
},
}));
// Log all requests
app.use(expressWinston.logger({
winstonInstance : requestLogger,
meta : true,
env : process.env.NODE_ENV,
dynamicMeta: (req, res) => {
return {
logCorrelationId: req.uuid,
};
},
}));
// Final fallback error handling
app.use(errorHandler);
// Swagger UI interface for the API
app.use('/v1/apidoc', swaggerUI.serve, swaggerUI.setup(apiDocConfig.apiDoc));
// Start server
const port = process.env.PORT || config.PORT || 3000;
if (process.env.NODE_ENV !== 'test') {
app.listen(port, () => {
debugLogger.info(`Server started. Listening on port ${port}`);
});
}
export default app;