-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtransfer-controller.ts
188 lines (174 loc) · 6.64 KB
/
transfer-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
/**
* 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 the transfer-controller.
*
* @module transfers
*/
import { Response } from 'express';
import log4js, { Logger } from 'log4js';
import BaseController, { BaseControllerOptions } from './base-controller';
import Policy from './policy';
import { RequestWithToken } from '../middleware/token-middleware';
import TransferService from '../service/transfer-service';
import TransferRequest from './request/transfer-request';
import Transfer from '../entity/transactions/transfer';
import { parseRequestPagination } from '../helpers/pagination';
import userTokenInOrgan from '../helpers/token-helper';
export default class TransferController extends BaseController {
private logger: Logger = log4js.getLogger('TransferController');
/**
* Creates a new transfer controller instance.
* @param options - The options passed to the base controller.
*/
public constructor(options: BaseControllerOptions) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
}
getPolicy(): Policy {
return {
'/': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Transfer', ['*']),
handler: this.returnAllTransfers.bind(this),
},
POST: {
body: { modelName: 'TransferRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'create', 'all', 'Transfer', ['*']),
handler: this.postTransfer.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', await TransferController.getRelation(req), 'Transfer', ['*']),
handler: this.returnTransfer.bind(this),
},
},
};
}
/**
* Function to determine which credentials are needed to get transaction
* all if user is not connected to transaction
* own if user is connected to transaction
* organ if user is connected to transaction via organ
* @param req
* @return whether transaction is connected to used token
*/
static async getRelation(req: RequestWithToken): Promise<string> {
const transfer = await Transfer.findOne({ where: { id: parseInt(req.params.id, 10) }, relations: ['to', 'from'] });
if (!transfer) return 'all';
const fromId = transfer.from != null ? transfer.from.id : undefined;
const toId = transfer.to != null ? transfer.to.id : undefined;
if (userTokenInOrgan(req, fromId) || userTokenInOrgan(req, toId)) return 'organ';
if (transfer
&& (fromId === req.token.user.id
|| toId === req.token.user.id)) {
return 'own';
}
return 'all';
}
/**
* GET /transfers
* @summary Returns all existing transfers
* @operationId getAllTransfers
* @tags transfers - Operations of transfer controller
* @security JWT
* @param {integer} take.query - How many transfers the endpoint should return
* @param {integer} skip.query - How many transfers should be skipped (for pagination)
* @return {Array.<TransferResponse>} 200 - All existing transfers
* @return {string} 500 - Internal server error
*/
public async returnAllTransfers(req: RequestWithToken, res: Response): Promise<void> {
const { body } = req;
this.logger.trace('Get all transfers by user', body, 'by user', req.token.user);
let take;
let skip;
try {
const pagination = parseRequestPagination(req);
take = pagination.take;
skip = pagination.skip;
} catch (e) {
res.status(400).send(e.message);
return;
}
try {
const transfers = await new TransferService().getTransfers({}, { take, skip });
res.json(transfers);
} catch (error) {
this.logger.error('Could not return all transfers:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /transfers/{id}
* @summary Returns the requested transfer
* @operationId getSingleTransfer
* @tags transfers - Operations of transfer controller
* @param {integer} id.path.required - The id of the transfer which should be returned
* @security JWT
* @return {TransferResponse} 200 - The requested transfer entity
* @return {string} 404 - Not found error
* @return {string} 500 - Internal server error
*/
public async returnTransfer(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
this.logger.trace('Get single transfer', id, 'by user', req.token.user);
try {
const parsedId = parseInt(id, 10);
const transfer = (
(await new TransferService().getTransfers({ id: parsedId }, {})).records[0]);
if (transfer) {
res.json(transfer);
} else {
res.status(404).json('Transfer not found.');
}
} catch (error) {
this.logger.error('Could not return transfer:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /transfers
* @summary Post a new transfer.
* @operationId createTransfer
* @tags transfers - Operations of transfer controller
* @param {TransferRequest} request.body.required
* - The transfer which should be created
* @security JWT
* @return {TransferResponse} 200 - The created transfer entity
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async postTransfer(req: RequestWithToken, res: Response) : Promise<void> {
const request = req.body as TransferRequest;
this.logger.trace('Post transfer', request, 'by user', req.token.user);
const transferService = new TransferService();
try {
if (!(await transferService.verifyTransferRequest(request))) {
res.status(400).json('Invalid transfer.');
return;
}
res.json(await transferService.postTransfer(request));
} catch (error) {
this.logger.error('Could not create transfer:', error);
res.status(500).json('Internal server error.');
}
}
}