-
Notifications
You must be signed in to change notification settings - Fork 120
/
app.js
247 lines (217 loc) · 6.46 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
// Load Environment Variables
require('dotenv').config();
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const http = require('http');
const fileUpload = require('express-fileupload');
const compression = require('compression');
const uuid = require('uuid');
const schedule = require('node-schedule');
const rateLimit = require('express-rate-limit');
const socketio = require('socket.io');
const DynamoDBStore = require('dynamodb-store');
const cloudwatch = require('./serverjs/cloudwatch');
const { updateCardbase } = require('./serverjs/updatecards');
const carddb = require('./serverjs/carddb');
const { render } = require('./serverjs/render');
const { setup } = require('./serverjs/socketio');
// global listeners for promise rejections
process.on('unhandledRejection', (reason) => {
cloudwatch.error('Unhandled Rejection at: Promise ', reason, reason.stack);
});
// Init app
const app = express();
// gzip middleware
app.use(compression());
// request timeout middleware
app.use((req, res, next) => {
req.setTimeout(60 * 1000, () => {
const err = new Error('Request Timeout');
err.status = 408;
next(err);
});
res.setTimeout(60 * 1000, () => {
const err = new Error('Service Unavailable');
err.status = 503;
next(err);
});
next();
});
// upload file middleware
app.use(fileUpload());
// body parser middleware
app.use(
bodyParser.urlencoded({
limit: '200mb',
extended: true,
}),
);
app.use(
bodyParser.json({
limit: '200mb',
extended: true,
}),
);
// Load view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Set Public Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/js', express.static(path.join(__dirname, 'dist')));
app.use('/jquery-ui', express.static(`${__dirname}/node_modules/jquery-ui-dist/`));
// Express session middleware
app.use(
session({
secret: process.env.SESSION,
store: new DynamoDBStore({
table: {
name: `${process.env.DYNAMO_PREFIX}_SESSIONS`,
hashKey: `id`,
hashPrefix: ``,
readCapacityUnits: 10,
writeCapacityUnits: 10,
},
dynamoConfig: {
endpoint: process.env.AWS_ENDPOINT || undefined,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION || 'us-east-2',
},
keepExpired: false,
touchInterval: 30000,
ttl: 1000 * 60 * 60 * 24 * 7 * 52, // 1 year
}),
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 * 52, // 1 year
},
}),
);
// Express messages middleware
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
res.locals.node_env = app.get('env');
next();
});
// Passport config and middleware
require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
// set CORS header for cube json requests (needs to be here to be included in rate limiter response)
const publicCORS = (req, res, next) => {
res.set('Access-Control-Allow-Origin', '*');
next();
};
// apply a rate limiter to the public api endpoints
const apiLimiter = rateLimit({
windowMs: 60 * 1000,
max: 100,
message: '429: Too Many Requests',
});
app.use('/cube/api/cubeJSON', publicCORS);
app.use('/cube/api/cubeJSON', apiLimiter);
app.use('/cube/api/history', publicCORS);
app.use('/cube/api/history', apiLimiter);
// per-request logging configuration
app.use((req, res, next) => {
req.uuid = uuid.v4();
cloudwatch.info(
JSON.stringify(
{
id: req.uuid,
method: req.method,
path: req.originalUrl,
user_id: req.user ? req.user.id : null,
username: req.user ? req.user.username : null,
remoteAddr: req.ip,
body: req.body,
},
null,
2,
),
);
req.logger = {
error: (...messages) => {
cloudwatch.error(
...messages,
JSON.stringify(
{
id: req.uuid,
method: req.method,
path: req.path,
query: req.query,
originalUrl: req.originalUrl,
user: req.user
? {
id: req.user.id,
username: req.user.username,
}
: null,
},
null,
2,
),
);
},
};
res.locals.requestId = req.uuid;
next();
});
// check for downtime
if (process.env.DOWNTIME_ACTIVE === 'true') {
app.use((req, res) =>
render(req, res, 'DownTimePage', {
title: 'Down for Maintenance',
}),
);
}
// Route files; they manage their own CSRF protection
app.use('/patreon', require('./routes/patreon_routes'));
app.use('/cache', require('./routes/cache_routes'));
app.use('/dev', require('./routes/dev_routes'));
app.use('/cube', require('./routes/cube/index'));
app.use('/public', require('./routes/cube/api_public'));
app.use('/user', require('./routes/users_routes'));
app.use('/tool', require('./routes/tools_routes'));
app.use('/comment', require('./routes/comment_routes'));
app.use('/admin', require('./routes/admin_routes'));
app.use('/content', require('./routes/content_routes'));
app.use('/multiplayer', require('./routes/multiplayer'));
app.use('/packages', require('./routes/packages'));
app.use('/api/private', require('./routes/api/private'));
app.use('/job', require('./routes/job_routes'));
app.use('', require('./routes/root'));
app.use((req, res) =>
render(req, res, 'ErrorPage', {
requestId: req.uuid,
title: '404: Page not found',
}),
);
app.use((err, req, res) => {
req.logger.error(err.message, err.stack);
if (!res.statusCode) {
res.status(500);
}
return render(req, res, 'ErrorPage', {
error: err.message,
requestId: req.uuid,
title: 'Oops! Something went wrong.',
});
});
// scryfall updates this data at 9, so this will minimize staleness
schedule.scheduleJob('0 10 * * *', async () => {
console.info('starting midnight cardbase update...');
await updateCardbase();
});
// Start server after carddb is initialized.
carddb.initializeCardDb().then(async () => {
const server = http.createServer(app).listen(process.env.PORT || 5000, '127.0.0.1');
console.info(`Server started on port ${process.env.PORT || 5000}...`);
// init socket io
setup(socketio(server));
});