-
Notifications
You must be signed in to change notification settings - Fork 3
/
user-controller.ts
1637 lines (1507 loc) · 59 KB
/
user-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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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 user-controller.
*
* @module users
*/
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 User, { UserType } from '../entity/user/user';
import BaseUserRequest, { CreateUserRequest, UpdateUserRequest } from './request/user-request';
import { parseRequestPagination } from '../helpers/pagination';
import ProductService from '../service/product-service';
import PointOfSaleService from '../service/point-of-sale-service';
import TransactionService, { parseGetTransactionsFilters } from '../service/transaction-service';
import ContainerService from '../service/container-service';
import TransferService, { parseGetTransferFilters } from '../service/transfer-service';
import MemberAuthenticator from '../entity/authenticator/member-authenticator';
import AuthenticationService, { AuthenticationContext } from '../service/authentication-service';
import TokenHandler from '../authentication/token-handler';
import RBACService from '../service/rbac-service';
import { isFail } from '../helpers/specification-validation';
import verifyUpdatePinRequest from './request/validators/update-pin-request-spec';
import UpdatePinRequest from './request/update-pin-request';
import UserService, {
parseGetFinancialMutationsFilters,
parseGetUsersFilters,
UserFilterParameters,
} from '../service/user-service';
import { asFromAndTillDate, asNumber, asReturnFileType } from '../helpers/validators';
import { verifyCreateUserRequest } from './request/validators/user-request-spec';
import userTokenInOrgan from '../helpers/token-helper';
import { parseUserToResponse } from '../helpers/revision-to-response';
import { AcceptTosRequest } from './request/accept-tos-request';
import PinAuthenticator from '../entity/authenticator/pin-authenticator';
import LocalAuthenticator from '../entity/authenticator/local-authenticator';
import UpdateLocalRequest from './request/update-local-request';
import verifyUpdateLocalRequest from './request/validators/update-local-request-spec';
import StripeService from '../service/stripe-service';
import verifyUpdateNfcRequest from './request/validators/update-nfc-request-spec';
import UpdateNfcRequest from './request/update-nfc-request';
import NfcAuthenticator from '../entity/authenticator/nfc-authenticator';
import KeyAuthenticator from '../entity/authenticator/key-authenticator';
import UpdateKeyResponse from './response/update-key-response';
import { randomBytes } from 'crypto';
import DebtorService from '../service/debtor-service';
import ReportService, { BuyerReportService, SalesReportService } from '../service/report-service';
import { ReturnFileType, UserReportParametersType } from 'pdf-generator-client';
import { reportPDFhelper } from '../helpers/express-pdf';
import { PdfError } from '../errors';
export default class UserController extends BaseController {
private logger: Logger = log4js.getLogger('UserController');
/**
* Reference to the token handler of the application.
*/
private tokenHandler: TokenHandler;
/**
* Create a new user controller instance.
* @param options - The options passed to the base controller.
* @param tokenHandler
*/
public constructor(
options: BaseControllerOptions,
tokenHandler: TokenHandler,
) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
this.tokenHandler = tokenHandler;
}
/**
* @inheritDoc
*/
public getPolicy(): Policy {
return {
'/': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', 'all', 'User', ['*'],
),
handler: this.getAllUsers.bind(this),
},
POST: {
body: { modelName: 'CreateUserRequest' },
policy: async (req) => this.roleManager.can(
req.token.roles, 'create', 'all', 'User', ['*'],
),
handler: this.createUser.bind(this),
},
},
'/usertype/:userType': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', 'all', 'User', ['*'],
),
handler: this.getAllUsersOfUserType.bind(this),
},
},
'/acceptTos': {
POST: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'acceptToS', 'own', 'User', ['*'],
),
handler: this.acceptToS.bind(this),
body: { modelName: 'AcceptTosRequest' },
restrictions: { acceptedTOS: false },
},
},
'/:id(\\d+)/authenticator/pin': {
PUT: {
body: { modelName: 'UpdatePinRequest' },
policy: async (req) => this.roleManager.can(
req.token.roles, 'update', UserController.getRelation(req), 'Authenticator', ['pin'],
),
handler: this.updateUserPin.bind(this),
},
},
'/:id(\\d+)/authenticator/nfc': {
PUT: {
body: { modelName: 'UpdateNfcRequest' },
policy: async (req) => this.roleManager.can(
req.token.roles, 'update', UserController.getRelation(req), 'Authenticator', ['nfcCode'],
),
handler: this.updateUserNfc.bind(this),
},
DELETE: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'delete', UserController.getRelation(req), 'Authenticator', [],
),
handler: this.deleteUserNfc.bind(this),
},
},
'/:id(\\d+)/authenticator/key': {
POST: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'update', UserController.getRelation(req), 'Authenticator', ['key'],
),
handler: this.updateUserKey.bind(this),
},
DELETE: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'update', UserController.getRelation(req), 'Authenticator', ['key'],
),
handler: this.deleteUserKey.bind(this),
},
},
'/:id(\\d+)/authenticator/local': {
PUT: {
body: { modelName: 'UpdateLocalRequest' },
policy: async (req) => this.roleManager.can(
req.token.roles, 'update', UserController.getRelation(req), 'Authenticator', ['password'],
),
handler: this.updateUserLocalPassword.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'User', ['*'],
),
handler: this.getIndividualUser.bind(this),
},
DELETE: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'delete', UserController.getRelation(req), 'User', ['*'],
),
handler: this.deleteUser.bind(this),
},
PATCH: {
body: { modelName: 'UpdateUserRequest' },
policy: async (req) => this.roleManager.can(
req.token.roles, 'update', UserController.getRelation(req), 'User', UserController.getAttributes(req),
),
handler: this.updateUser.bind(this),
},
},
'/:id(\\d+)/members': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'User', ['*'],
),
handler: this.getOrganMembers.bind(this),
},
},
'/:id(\\d+)/authenticate': {
POST: {
policy: async () => true,
handler: this.authenticateAsUser.bind(this),
},
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Authenticator', ['*'],
),
handler: this.getUserAuthenticatable.bind(this),
},
},
'/:id(\\d+)/products': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Product', ['*'],
),
handler: this.getUsersProducts.bind(this),
},
},
'/:id(\\d+)/roles': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Roles', ['*'],
),
handler: this.getUserRoles.bind(this),
},
},
'/:id(\\d+)/containers': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Container', ['*'],
),
handler: this.getUsersContainers.bind(this),
},
},
'/:id(\\d+)/pointsofsale': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'PointOfSale', ['*'],
),
handler: this.getUsersPointsOfSale.bind(this),
},
},
'/:id(\\d+)/transactions': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersTransactions.bind(this),
},
},
'/:id(\\d+)/transactions/sales/report': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersSalesReport.bind(this),
},
},
'/:id(\\d+)/transactions/sales/report/pdf': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersSalesReportPdf.bind(this),
},
},
'/:id(\\d+)/transactions/purchases/report': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersPurchasesReport.bind(this),
},
},
'/:id(\\d+)/transactions/purchases/report/pdf': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersPurchaseReportPdf.bind(this),
},
},
'/:id(\\d+)/transactions/report': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersTransactionsReport.bind(this),
},
},
'/:id(\\d+)/transfers': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transfer', ['*'],
),
handler: this.getUsersTransfers.bind(this),
},
},
'/:id(\\d+)/financialmutations': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transfer', ['*'],
) && this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transaction', ['*'],
),
handler: this.getUsersFinancialMutations.bind(this),
},
},
'/:id(\\d+)/deposits': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', UserController.getRelation(req), 'Transfer', ['*'],
),
handler: this.getUsersProcessingDeposits.bind(this),
},
},
'/:id(\\d+)/fines/waive': {
POST: {
policy: async (req) => this.roleManager.can(req.token.roles, 'delete', 'all', 'Fine', ['*']),
handler: this.waiveUserFines.bind(this),
},
},
};
}
/**
* Function to determine which credentials are needed to GET
* 'all' if user is not connected to User
* 'organ' if user is connected to User via organ
* 'own' if user is connected to User
* @param req
* @return whether User is connected to used token
*/
static getRelation(req: RequestWithToken): string {
if (userTokenInOrgan(req, asNumber(req.params.id))) return 'organ';
return req.params.id === req.token.user.id.toString() ? 'own' : 'all';
}
static getAttributes(req: RequestWithToken): string[] {
const attributes: string[] = [];
const body = req.body as BaseUserRequest;
for (const key in body) {
if (body.hasOwnProperty(key)) {
attributes.push(key);
}
}
return attributes;
}
/**
* GET /users
* @summary Get a list of all users
* @operationId getAllUsers
* @tags users - Operations of user controller
* @security JWT
* @param {integer} take.query - How many users the endpoint should return
* @param {integer} skip.query - How many users should be skipped (for pagination)
* @param {string} search.query - Filter based on first name
* @param {boolean} active.query - Filter based if the user is active
* @param {boolean} ofAge.query - Filter based if the user is 18+
* @param {integer} id.query - Filter based on user ID
* @param {string} type.query - enum:MEMBER,ORGAN,VOUCHER,LOCAL_USER,LOCAL_ADMIN,INVOICE,AUTOMATIC_INVOICE - Filter based on user type.
* @return {PaginatedUserResponse} 200 - A list of all users
*/
public async getAllUsers(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get all users by user', req.token.user);
let take;
let skip;
let filters: UserFilterParameters;
try {
const pagination = parseRequestPagination(req);
filters = parseGetUsersFilters(req);
take = pagination.take;
skip = pagination.skip;
} catch (e) {
res.status(400).send(e.message);
return;
}
try {
const users = await UserService.getUsers(filters, { take, skip });
res.status(200).json(users);
} catch (error) {
this.logger.error('Could not get users:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /users/usertype/{userType}
* @summary Get all users of user type
* @operationId getAllUsersOfUserType
* @tags users - Operations of user controller
* @param {string} userType.path.required - The userType of the requested users
* @security JWT
* @param {integer} take.query - How many users the endpoint should return
* @param {integer} skip.query - How many users should be skipped (for pagination)
* @return {PaginatedUserResponse} 200 - A list of all users
* @return {string} 404 - Nonexistent usertype
*/
public async getAllUsersOfUserType(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
this.logger.trace('Get all users of userType', parameters, 'by user', req.token.user);
const userType = req.params.userType.toUpperCase();
// If it does not exist, return a 404 error
const type = UserType[userType as keyof typeof UserType];
if (!type || Number(userType)) {
res.status(404).json('Unknown userType.');
return;
}
try {
req.query.type = userType;
await this.getAllUsers(req, res);
} catch (error) {
this.logger.error('Could not get users:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PUT /users/{id}/authenticator/pin
* @summary Put an users pin code
* @operationId updateUserPin
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @param {UpdatePinRequest} request.body.required -
* The PIN code to update to
* @security JWT
* @return 204 - Update success
* @return {string} 400 - Validation Error
* @return {string} 404 - Nonexistent user id
*/
public async updateUserPin(req: RequestWithToken, res: Response): Promise<void> {
const { params } = req;
const updatePinRequest = req.body as UpdatePinRequest;
this.logger.trace('Update user pin', params, 'by user', req.token.user);
try {
// Get the user object if it exists
const user = await User.findOne({ where: { id: parseInt(params.id, 10), deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
const validation = await verifyUpdatePinRequest(updatePinRequest);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
await new AuthenticationService().setUserAuthenticationHash(user,
updatePinRequest.pin.toString(), PinAuthenticator);
res.status(204).json();
} catch (error) {
this.logger.error('Could not update pin:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PUT /users/{id}/authenticator/nfc
* @summary Put a users NFC code
* @operationId updateUserNfc
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @param {UpdateNfcRequest} request.body.required -
* The NFC code to update to
* @security JWT
* @return 204 - Update success
* @return {string} 400 - Validation Error
* @return {string} 404 - Nonexistent user id
*/
public async updateUserNfc(req: RequestWithToken, res: Response): Promise<void> {
const { params } = req;
const updateNfcRequest = req.body as UpdateNfcRequest;
this.logger.trace('Update user NFC', params, 'by user', req.token.user);
try {
// Get the user object if it exists
const user = await User.findOne({ where: { id: parseInt(params.id, 10), deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
const validation = await verifyUpdateNfcRequest(updateNfcRequest);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
await new AuthenticationService().setUserAuthenticationNfc(user,
updateNfcRequest.nfcCode.toString(), NfcAuthenticator);
res.status(204).json();
} catch (error) {
this.logger.error('Could not update NFC:', error);
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /users/{id}/authenticator/nfc
* @summary Delete a nfc code
* @operationId deleteUserNfc
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @security JWT
* @return 200 - Delete nfc success
* @return {string} 400 - Validation Error
* @return {string} 403 - Nonexistent user nfc
* @return {string} 404 - Nonexistent user id
*/
public async deleteUserNfc(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
this.logger.trace('Delete user NFC', parameters, 'by user', req.token.user);
try {
// Get the user object if it exists
const user = await User.findOne({ where: { id: parseInt(parameters.id, 10), deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
if (await NfcAuthenticator.count({ where: { userId: parseInt(parameters.id, 10) } }) == 0) {
res.status(403).json('No saved nfc');
return;
}
await NfcAuthenticator.delete(parseInt(parameters.id, 10));
res.status(204).json();
} catch (error) {
this.logger.error('Could not update NFC:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /users/{id}/authenticator/key
* @summary POST an users update to new key code
* @operationId updateUserKey
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @security JWT
* @return {UpdateKeyResponse} 200 - The new key
* @return {string} 400 - Validation Error
* @return {string} 404 - Nonexistent user id
*/
public async updateUserKey(req: RequestWithToken, res: Response): Promise<void> {
const { params } = req;
this.logger.trace('Update user key', params, 'by user', req.token.user);
try {
const userId = parseInt(params.id, 10);
// Get the user object if it exists
const user = await User.findOne({ where: { id: userId, deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
const generatedKey = randomBytes(128).toString('hex');
await new AuthenticationService().setUserAuthenticationHash(user,
generatedKey, KeyAuthenticator);
const response = { key: generatedKey } as UpdateKeyResponse;
res.status(200).json(response);
} catch (error) {
this.logger.error('Could not update key:', error);
res.status(500).json('Internal server error.');
}
}
/**
* Delete /users/{id}/authenticator/key
* @summary Delete a users key code
* @operationId deleteUserKey
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @security JWT
* @return 200 - Deletion succesfull
* @return {string} 400 - Validation Error
* @return {string} 404 - Nonexistent user id
*/
public async deleteUserKey(req: RequestWithToken, res: Response): Promise<void> {
const { params } = req;
this.logger.trace('Delete user key', params, 'by user', req.token.user);
try {
// Get the user object if it exists
const user = await User.findOne({ where: { id: parseInt(params.id, 10), deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
await KeyAuthenticator.delete(parseInt(params.id, 10));
res.status(204).json();
} catch (error) {
this.logger.error('Could not delete key:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PUT /users/{id}/authenticator/local
* @summary Put a user's local password
* @operationId updateUserLocalPassword
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @param {UpdateLocalRequest} request.body.required -
* The password update
* @security JWT
* @return 204 - Update success
* @return {string} 400 - Validation Error
* @return {string} 404 - Nonexistent user id
*/
public async updateUserLocalPassword(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
const updateLocalRequest = req.body as UpdateLocalRequest;
this.logger.trace('Update user local password', parameters, 'by user', req.token.user);
try {
const id = Number.parseInt(parameters.id, 10);
// Get the user object if it exists
const user = await User.findOne({ where: { id, deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
const validation = await verifyUpdateLocalRequest(updateLocalRequest);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
await new AuthenticationService().setUserAuthenticationHash(user,
updateLocalRequest.password, LocalAuthenticator);
res.status(204).json();
} catch (error) {
this.logger.error('Could not update local password:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /users/{id}/members
* @summary Get an organs members
* @operationId getOrganMembers
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @param {integer} take.query - How many members the endpoint should return
* @param {integer} skip.query - How many members should be skipped (for pagination)
* @security JWT
* @return {PaginatedUserResponse} 200 - All members of the organ
* @return {string} 404 - Nonexistent user id
* @return {string} 400 - User is not an organ
*/
public async getOrganMembers(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
this.logger.trace('Get organ members', parameters, '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 organId = asNumber(parameters.id);
// Get the user object if it exists
const user = await User.findOne({ where: { id: organId } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
if (user.type !== UserType.ORGAN) {
res.status(400).json('User is not of type Organ');
return;
}
const members = await UserService.getUsers({ organId }, { take, skip });
res.status(200).json(members);
} catch (error) {
this.logger.error('Could not get organ members:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /users/{id}
* @summary Get an individual user
* @operationId getIndividualUser
* @tags users - Operations of user controller
* @param {integer} id.path.required - userID
* @security JWT
* @return {UserResponse} 200 - Individual user
* @return {string} 404 - Nonexistent user id
*/
public async getIndividualUser(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
this.logger.trace('Get individual user', parameters, 'by user', req.token.user);
try {
// Get the user object if it exists
const user = await UserService.getSingleUser(asNumber(parameters.id));
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
res.status(200).json(user);
} catch (error) {
this.logger.error('Could not get individual user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /users
* @summary Create a new user
* @operationId createUser
* @tags users - Operations of user controller
* @param {CreateUserRequest} request.body.required -
* The user which should be created
* @security JWT
* @return {UserResponse} 200 - New user
* @return {string} 400 - Bad request
*/
// eslint-disable-next-line class-methods-use-this
public async createUser(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as CreateUserRequest;
this.logger.trace('Create user', body, 'by user', req.token.user);
try {
const validation = await verifyCreateUserRequest(body);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
const user = await UserService.createUser(body);
res.status(201).json(user);
} catch (error) {
this.logger.error('Could not create user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PATCH /users/{id}
* @summary Update a user
* @operationId updateUser
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @param {UpdateUserRequest} request.body.required - The user which should be updated
* @security JWT
* @return {UserResponse} 200 - New user
* @return {string} 400 - Bad request
*/
public async updateUser(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as UpdateUserRequest;
const parameters = req.params;
this.logger.trace('Update user', parameters.id, 'with', body, 'by user', req.token.user);
if (body.firstName !== undefined && body.firstName.length === 0) {
res.status(400).json('firstName cannot be empty');
return;
}
if (body.firstName !== undefined && body.firstName.length > 64) {
res.status(400).json('firstName too long');
return;
}
if (body.lastName !== undefined && body.lastName.length > 64) {
res.status(400).json('lastName too long');
return;
}
if (body.nickname !== undefined && body.nickname.length > 64) {
res.status(400).json('nickname too long');
return;
}
if (body.nickname === '') body.nickname = null;
try {
const id = parseInt(parameters.id, 10);
// Get the user object if it exists
let user = await User.findOne({ where: { id, deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
user = {
...body,
} as User;
await User.update(parameters.id, user);
res.status(200).json(
await UserService.getSingleUser(asNumber(parameters.id)),
);
} catch (error) {
this.logger.error('Could not update user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /users/{id}
* @summary Delete a single user
* @operationId deleteUser
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @security JWT
* @return 204 - User successfully deleted
* @return {string} 400 - Cannot delete yourself
*/
public async deleteUser(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
this.logger.trace('Delete individual user', parameters, 'by user', req.token.user);
if (req.token.user.id === parseInt(parameters.id, 10)) {
res.status(400).json('Cannot delete yourself');
return;
}
try {
const id = parseInt(parameters.id, 10);
// Get the user object if it exists
const user = await User.findOne({ where: { id, deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
user.deleted = true;
await user.save();
res.status(204).json('User deleted');
} catch (error) {
this.logger.error('Could not create product:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /users/acceptTos
* @summary Accept the Terms of Service if you have not accepted it yet
* @operationId acceptTos
* @tags users - Operations of the User controller
* @param {AcceptTosRequest} request.body.required - "Tosrequest body"
* @security JWT
* @return 204 - ToS accepted
* @return {string} 400 - ToS already accepted
*/
public async acceptToS(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Accept ToS for user', req.token.user);
const { id } = req.token.user;
const body = req.body as AcceptTosRequest;
try {
const user = await UserService.getSingleUser(id);
if (user == null) {
res.status(404).json('User not found.');
return;
}
const success = await UserService.acceptToS(id, body);
if (!success) {
res.status(400).json('User already accepted ToS.');
return;
}
res.status(204).json();
return;
} catch (error) {
this.logger.error('Could not accept ToS for user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /users/{id}/products
* @summary Get an user's products
* @operationId getUsersProducts
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @param {integer} take.query - How many products the endpoint should return
* @param {integer} skip.query - How many products should be skipped (for pagination)
* @security JWT
* @return {PaginatedProductResponse} 200 - List of products.
*/
public async getUsersProducts(req: RequestWithToken, res: Response): Promise<void> {
const parameters = req.params;
this.logger.trace("Get user's products", parameters, '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;
}
// Handle request
try {
const id = parseInt(parameters.id, 10);
const owner = await User.findOne({ where: { id, deleted: false } });
if (owner == null) {
res.status(404).json({});
return;
}
const products = await ProductService.getProducts({}, { take, skip }, owner);
res.json(products);
} catch (error) {
this.logger.error('Could not return all products:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /users/{id}/containers
* @summary Returns the user's containers
* @operationId getUsersContainers
* @tags users - Operations of user controller
* @param {integer} id.path.required - The id of the user
* @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 users updated containers
* @return {string} 404 - Not found error
* @return {string} 500 - Internal server error
*/
public async getUsersContainers(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
this.logger.trace("Get user's containers", id, '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;
}
// handle request
try {
// Get the user object if it exists
const user = await User.findOne({ where: { id: parseInt(id, 10), deleted: false } });
// If it does not exist, return a 404 error
if (user == null) {
res.status(404).json('Unknown user ID.');
return;
}
const containers = (await ContainerService
.getContainers({}, { take, skip }, user));
res.json(containers);
} catch (error) {
this.logger.error('Could not return containers:', error);
res.status(500).json('Internal server error.');
}