-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
339 lines (286 loc) · 8.95 KB
/
server.js
File metadata and controls
339 lines (286 loc) · 8.95 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
const Koa = require('koa');
const Router = require('koa-router');
const session = require('koa-session');
const cors = require('@koa/cors');
const jsonBody = require('koa-json-body');
const { get } = require('lodash');
const { Queue } = require('bullmq');
const Redis = require('ioredis');
const authEndpoints = require('./auth/authEndpoints');
const fileHandler = require('./fileHandler');
const {
migrate,
getBuilds,
getBuild,
addBuild,
updateBuild,
removeBuild,
getPoster,
addPoster,
updatePoster,
removePoster,
} = require('./store');
const {
generatePoints,
getConfig,
setDateConfig,
setStatusConfig,
setUpdatedAtConfig,
} = require('./joreStore');
const { downloadPostersFromCloud } = require('./cloudService');
const { REDIS_CONNECTION_STRING, GROUP_GENERATE } = require('../constants');
const PORT = 4000;
const bullRedisConnection = new Redis(REDIS_CONNECTION_STRING, {
maxRetriesPerRequest: null,
enableReadyCheck: false,
});
const queue = new Queue('generator', { connection: bullRedisConnection });
const cancelSignalRedis = new Redis(REDIS_CONNECTION_STRING); // New connection to make sure that pub/sub will work correctly.
async function generatePoster(buildId, props) {
const { id } = await addPoster({ buildId, props });
const options = {
id,
props,
};
queue.add('generate', { options }, { jobId: id });
return { id };
}
const errorHandler = async (ctx, next) => {
try {
await next();
} catch (error) {
ctx.status = error.status || 500;
ctx.body = { message: error.message };
if (ctx.status !== 401) {
console.error(error); // eslint-disable-line no-console
}
}
};
const allowedToGenerate = (user) => {
if (!user || !user.email) return false;
if (user.groups && user.groups.includes(GROUP_GENERATE)) {
return true;
}
return false;
};
const authMiddleware = async (ctx, next) => {
const endpointsNotRequiringAuthentication = ['/login', '/logout', '/session'];
if (endpointsNotRequiringAuthentication.includes(ctx.path)) {
// Do not check the authentication beforehands for session related paths.
await next();
} else {
const authResponse = await authEndpoints.checkExistingSession(
ctx.request,
ctx.response,
ctx.session,
);
if (!authResponse.body.isOk) {
// Not authenticated, throw 401
ctx.throw(401);
} else {
// If the request is CRUD, check if the user has privileges to perform the action
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
const user = authResponse.body;
if (!allowedToGenerate(user)) {
ctx.throw(403, 'User does not have privileges to perform this action.');
}
}
await next();
}
}
};
async function main() {
await migrate();
const app = new Koa();
const router = new Router();
const unAuthorizedRouter = new Router();
router.get('/builds', async (ctx) => {
const builds = await getBuilds();
ctx.body = builds;
});
router.get('/builds/:id', async (ctx) => {
const { id } = ctx.params;
const builds = await getBuild({ id });
ctx.body = builds;
});
router.post('/builds', async (ctx) => {
const authResponse = await authEndpoints.checkExistingSession(
ctx.request,
ctx.response,
ctx.session,
);
if (!authResponse.body.isOk) {
ctx.throw(401, 'Not allowed.');
}
if (!authResponse.body.groups.includes(GROUP_GENERATE)) {
ctx.throw(403, 'User does not have permission to modify builds.');
}
const { title } = ctx.request.body;
const build = await addBuild({ title });
ctx.body = build;
});
router.put('/builds/:id', async (ctx) => {
const authResponse = await authEndpoints.checkExistingSession(
ctx.request,
ctx.response,
ctx.session,
);
if (!authResponse.body.isOk) {
ctx.throw(401, 'Not allowed.');
}
if (!authResponse.body.groups.includes(GROUP_GENERATE)) {
ctx.throw(403, 'User does not have permission to modify builds.');
}
const { id } = ctx.params;
const { status } = ctx.request.body;
const build = await updateBuild({
id,
status,
});
ctx.body = build;
});
router.delete('/builds/:id', async (ctx) => {
const { id } = ctx.params;
const build = await removeBuild({ id });
ctx.body = build;
});
router.get('/posters/:id', async (ctx) => {
const { id } = ctx.params;
const poster = await getPoster({ id });
ctx.body = poster;
});
router.post('/posters', async (ctx) => {
const { buildId, props } = ctx.request.body;
const authResponse = await authEndpoints.checkExistingSession(
ctx.request,
ctx.response,
ctx.session,
);
if (!authResponse.body.isOk) {
ctx.throw(401, 'Not allowed.');
}
if (!authResponse.body.groups.includes(GROUP_GENERATE)) {
ctx.throw(403, 'User does not have permission to generate posters.');
} else {
const posters = [];
for (let i = 0; i < props.length; i++) {
// eslint-disable-next-line no-await-in-loop
const poster = await generatePoster(buildId, props[i]);
posters.push(poster);
}
ctx.body = posters;
}
});
router.post('/cancelPoster', async (ctx) => {
const { item } = ctx.request.body;
const jobId = item.id;
const poster = await updatePoster({ id: jobId, status: 'FAILED' });
const success = await queue.remove(jobId);
if (!success) {
// The job is already being processed. Terminate the worker operation.
cancelSignalRedis.publish('cancel', jobId);
}
ctx.body = poster;
});
router.post('/removePosters', async (ctx) => {
const { item } = ctx.request.body;
const poster = await removePoster({ id: item.id });
ctx.body = poster;
});
router.get('/downloadBuild/:id', async (ctx) => {
const { id } = ctx.params;
const { title, posters } = await getBuild({ id });
const posterIds = posters
.filter((poster) => poster.status === 'READY')
.map((poster) => poster.id);
await downloadPostersFromCloud(posterIds);
const content = await fileHandler.concatenate(posterIds);
ctx.type = 'application/pdf';
ctx.set('Content-Disposition', `attachment; filename="${title}-${id}.pdf"`);
ctx.body = content;
content.on('close', () => {
fileHandler.removeFiles([id]);
});
});
router.get('/downloadPoster/:id', async (ctx) => {
const { id } = ctx.params;
const poster = await getPoster({ id });
const name = get(poster, 'props.configuration.name');
await downloadPostersFromCloud([id]);
const content = await fileHandler.concatenate([id]);
ctx.type = 'application/pdf';
ctx.set('Content-Disposition', `attachment; filename="${name}.pdf"`);
ctx.body = content;
content.on('close', () => {
fileHandler.removeFiles([id]);
});
});
router.post('/import', async (ctx) => {
const { targetDate } = ctx.query;
let config = await getConfig();
if (config && config.status === 'PENDING') {
ctx.throw(503, `Already running for date: ${config.target_date}`);
} else if (!targetDate) {
ctx.throw(400, 'Missing targetDate query parameter');
} else {
config = await setDateConfig(targetDate);
await generatePoints(config.target_date)
.then(async () => {
await setStatusConfig('READY');
})
.catch(async () => {
await setStatusConfig('ERROR');
});
ctx.body = config;
}
});
router.get('/config', async (ctx) => {
ctx.body = await getConfig();
});
router.post('/login', async (ctx) => {
const authResponse = await authEndpoints.authorize(ctx.request, ctx.response, ctx.session);
ctx.session = null;
if (authResponse.modifiedSession) {
ctx.session = authResponse.modifiedSession;
}
ctx.body = authResponse.body;
ctx.response.status = authResponse.status;
});
router.get('/logout', async (ctx) => {
const authResponse = await authEndpoints.logout(ctx.request, ctx.response, ctx.session);
ctx.session = null;
ctx.response.status = authResponse.status;
});
router.get('/session', async (ctx) => {
const authResponse = await authEndpoints.checkExistingSession(
ctx.request,
ctx.response,
ctx.session,
);
ctx.body = authResponse.body;
ctx.response.status = authResponse.status;
});
unAuthorizedRouter.get('/health', async (ctx) => {
ctx.status = 200;
});
app.keys = ['secret key'];
const CONFIG = {
renew: true,
maxAge: 86400000 * 30,
};
app.use(session(CONFIG, app));
app
.use(errorHandler)
.use(unAuthorizedRouter.routes())
.use(
cors({
credentials: true,
}),
)
.use(authMiddleware)
.use(jsonBody({ fallback: true, limit: '10mb' }))
.use(router.routes())
.use(router.allowedMethods())
.listen(PORT, () => console.log(`Listening at ${PORT}`)); // eslint-disable-line no-console
}
main().catch((error) => console.error(error)); // eslint-disable-line no-console