-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontainer-controller.ts
368 lines (333 loc) · 13.4 KB
/
container-controller.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
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of container-controller.
*
* @module catalogue/containers
*/
import log4js, { Logger } from 'log4js';
import { Response } from 'express';
import BaseController, { BaseControllerOptions } from './base-controller';
import Policy from './policy';
import { RequestWithToken } from '../middleware/token-middleware';
import ContainerService from '../service/container-service';
import { PaginatedContainerResponse } from './response/container-response';
import ContainerRevision from '../entity/container/container-revision';
import Container from '../entity/container/container';
import { asNumber } from '../helpers/validators';
import { parseRequestPagination } from '../helpers/pagination';
import { verifyContainerRequest, verifyCreateContainerRequest } from './request/validators/container-request-spec';
import { isFail } from '../helpers/specification-validation';
import {
CreateContainerParams,
CreateContainerRequest,
UpdateContainerParams,
UpdateContainerRequest,
} from './request/container-request';
import userTokenInOrgan from '../helpers/token-helper';
export default class ContainerController extends BaseController {
private logger: Logger = log4js.getLogger('ContainerController');
/**
* Creates a new product controller instance.
* @param options - The options passed to the base controller.
*/
public constructor(options: BaseControllerOptions) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
}
/**
* @inheritdoc
*/
getPolicy(): Policy {
return {
'/': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Container', ['*']),
handler: this.getAllContainers.bind(this),
},
POST: {
body: { modelName: 'CreateContainerRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'create', 'own', 'Container', ['*']),
handler: this.createContainer.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', await ContainerController.getRelation(req), 'Container', ['*']),
handler: this.getSingleContainer.bind(this),
},
PATCH: {
body: { modelName: 'UpdateContainerRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'update', await ContainerController.getRelation(req), 'Container', ['*']),
handler: this.updateContainer.bind(this),
},
DELETE: {
policy: async (req) => this.roleManager.can(req.token.roles, 'delete', await ContainerController.getRelation(req), 'Container', ['*']),
handler: this.deleteContainer.bind(this),
},
},
'/:id(\\d+)/products': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', await ContainerController.getRelation(req), 'Container', ['*']),
handler: this.getProductsContainer.bind(this),
},
},
'/public': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'public', 'Container', ['*']),
handler: this.getPublicContainers.bind(this),
},
},
};
}
/**
* GET /containers
* @summary Returns all existing containers
* @operationId getAllContainers
* @tags containers - Operations of container controller
* @security JWT
* @param {integer} take.query - How many containers the endpoint should return
* @param {integer} skip.query - How many containers should be skipped (for pagination)
* @return {PaginatedContainerResponse} 200 - All existing containers
* @return {string} 500 - Internal server error
*/
public async getAllContainers(req: RequestWithToken, res: Response): Promise<void> {
const { body } = req;
this.logger.trace('Get all containers', body, 'by user', req.token.user);
const { take, skip } = parseRequestPagination(req);
// Handle request
try {
const containers: PaginatedContainerResponse = await ContainerService.getContainers(
{}, { take, skip },
);
res.json(containers);
} catch (error) {
this.logger.error('Could not return all containers:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /containers/{id}
* @summary Returns the requested container
* @operationId getSingleContainer
* @tags containers - Operations of container controller
* @param {integer} id.path.required - The id of the container which should be returned
* @security JWT
* @return {ContainerWithProductsResponse} 200 - The requested container
* @return {string} 404 - Not found error
* @return {string} 403 - Incorrect permissions
* @return {string} 500 - Internal server error
*/
public async getSingleContainer(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
this.logger.trace('Get single container', id, 'by user', req.token.user);
const containerId = parseInt(id, 10);
// Handle request
try {
const container = (await ContainerService
.getContainers({ containerId, returnProducts: true })).records[0];
if (!container) {
res.status(404).json('Container not found.');
return;
}
res.json(container);
} catch (error) {
this.logger.error('Could not return single container:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /containers/{id}/products
* @summary Returns all the products in the container
* @operationId getProductsContainer
* @tags containers - Operations of container controller
* @param {integer} id.path.required - The id of the container which should be returned
* @security JWT
* @return {Array.<ProductResponse>} 200 - All products in the container
* @return {string} 404 - Not found error
* @return {string} 500 - Internal server error
*/
public async getProductsContainer(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const containerId = parseInt(id, 10);
this.logger.trace('Get all products in container', containerId, 'by user', req.token.user);
try {
// Check if we should return a 404.
const exist = await ContainerRevision.findOne({ where: { container: { id: containerId } } });
if (!exist) {
res.status(404).json('Container not found.');
return;
}
const products = (await ContainerService.getSingleContainer({ containerId, returnProducts: true })).products;
res.json(products ? products : []);
} catch (error) {
this.logger.error('Could not return all products in container:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /containers
* @summary Create a new container.
* @operationId createContainer
* @tags containers - Operations of container controller
* @param {CreateContainerRequest} request.body.required -
* The container which should be created
* @security JWT
* @return {ContainerWithProductsResponse} 200 - The created container entity
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async createContainer(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as CreateContainerRequest;
this.logger.trace('Create container', body, 'by user', req.token.user);
// handle request
try {
const request: CreateContainerParams = {
...body,
ownerId: body.ownerId ?? req.token.user.id,
};
const validation = await verifyCreateContainerRequest(request);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
res.json(await ContainerService.createContainer(request));
} catch (error) {
this.logger.error('Could not create container:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /containers/public
* @summary Returns all public container
* @operationId getPublicContainers
* @tags containers - Operations of container controller
* @security JWT
* @param {integer} take.query - How many containers the endpoint should return
* @param {integer} skip.query - How many containers should be skipped (for pagination)
* @return {PaginatedContainerResponse} 200 - All existing public containers
* @return {string} 500 - Internal server error
*/
public async getPublicContainers(req: RequestWithToken, res: Response): Promise<void> {
const { body } = req;
this.logger.trace('Get all public containers', body, 'by user', req.token.user);
const { take, skip } = parseRequestPagination(req);
// Handle request
try {
const containers: PaginatedContainerResponse = await ContainerService.getContainers(
{ public: true }, { take, skip },
);
res.json(containers);
} catch (error) {
this.logger.error('Could not return all public containers:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PATCH /containers/{id}
* @summary Update an existing container.
* @operationId updateContainer
* @tags containers - Operations of container controller
* @param {integer} id.path.required - The id of the container which should be updated
* @param {UpdateContainerRequest} request.body.required -
* The container which should be updated
* @security JWT
* @return {ContainerWithProductsResponse} 200 - The created container entity
* @return {string} 400 - Validation error
* @return {string} 404 - Product not found error
* @return {string} 500 - Internal server error
*/
public async updateContainer(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as UpdateContainerRequest;
const { id } = req.params;
const containerId = Number.parseInt(id, 10);
this.logger.trace('Update container', id, 'with', body, 'by user', req.token.user);
// handle request
try {
const request: UpdateContainerParams = {
...body,
id: containerId,
};
const validation = await verifyContainerRequest(request);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
const container = await Container.findOne({ where: { id: containerId } });
if (!container) {
res.status(404).json('Container not found.');
return;
}
res.json(await ContainerService.updateContainer(request));
} catch (error) {
this.logger.error('Could not update container:', error);
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /containers/{id}
* @summary (Soft) delete the given container. Cannot be undone.
* @operationId deleteContainer
* @tags containers - Operations of container controller
* @param {integer} id.path.required - The id of the container which should be deleted
* @security JWT
* @return {string} 204 - Success
* @return {string} 404 - Not found error
* @return {string} 500 - Internal server error
*/
public async deleteContainer(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
this.logger.trace('Delete container', id, 'by user', req.token.user);
try {
const containerId = parseInt(id, 10);
const container = await Container.findOne({ where: { id: containerId } });
if (container == null) {
res.status(404).json('Container not found');
return;
}
await ContainerService.deleteContainer(containerId);
res.status(204).send();
return;
} catch (error) {
this.logger.error('Could not delete container', error);
res.status(500).json('Internal server error.');
}
}
/**
* Function to determine which credentials are needed to get container
* 'all' if user is not connected to container
* 'organ' if user is not connected to container via organ
* 'own' if user is connected to container
* @param req
* @return whether container is connected to used token
*/
static async getRelation(req: RequestWithToken): Promise<string> {
const containerId = asNumber(req.params.id);
const container: Container = await Container.findOne({ where: { id: containerId }, relations: ['owner'] });
if (!container) return 'all';
if (userTokenInOrgan(req, container.owner.id)) return 'organ';
const containerVisibility = await ContainerService.canViewContainer(
req.token.user.id, container,
);
if (containerVisibility.own) return 'own';
if (containerVisibility.public) return 'public';
return 'all';
}
}