-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUsersPresenter.php
More file actions
944 lines (841 loc) · 30.3 KB
/
UsersPresenter.php
File metadata and controls
944 lines (841 loc) · 30.3 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
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
<?php
namespace App\V1Module\Presenters;
use App\Helpers\MetaFormats\Attributes\Post;
use App\Helpers\MetaFormats\Attributes\Query;
use App\Helpers\MetaFormats\Attributes\Path;
use App\Helpers\MetaFormats\FormatDefinitions\UserFilterFormat;
use App\Helpers\MetaFormats\Validators\VArray;
use App\Helpers\MetaFormats\Validators\VBool;
use App\Helpers\MetaFormats\Validators\VEmail;
use App\Helpers\MetaFormats\Validators\VInt;
use App\Helpers\MetaFormats\Validators\VMixed;
use App\Helpers\MetaFormats\Validators\VString;
use App\Helpers\MetaFormats\Validators\VUuid;
use App\Exceptions\ForbiddenRequestException;
use App\Exceptions\FrontendErrorMappings;
use App\Exceptions\InvalidApiArgumentException;
use App\Exceptions\NotFoundException;
use App\Exceptions\WrongCredentialsException;
use App\Model\Entity\ExternalLogin;
use App\Model\Entity\Group;
use App\Model\Entity\Login;
use App\Model\Entity\SecurityEvent;
use App\Model\Entity\User;
use App\Model\Entity\UserUiData;
use App\Model\Repository\ExternalLogins;
use App\Model\Repository\Logins;
use App\Model\Repository\SecurityEvents;
use App\Exceptions\BadRequestException;
use App\Helpers\EmailVerificationHelper;
use App\Helpers\AnonymizationHelper;
use App\Helpers\MetaFormats\Validators\VObject;
use App\Model\View\GroupViewFactory;
use App\Model\View\InstanceViewFactory;
use App\Model\View\UserViewFactory;
use App\Security\ACL\IUserPermissions;
use App\Security\Roles;
use Nette\Security\Passwords;
use DateTime;
/**
* User management endpoints
*/
class UsersPresenter extends BasePresenter
{
/**
* @var Logins
* @inject
*/
public $logins;
/**
* @var ExternalLogins
* @inject
*/
public $externalLogins;
/**
* @var SecurityEvents
* @inject
*/
public $securityEvents;
/**
* @var EmailVerificationHelper
* @inject
*/
public $emailVerificationHelper;
/**
* @var AnonymizationHelper
* @inject
*/
public $anonymizationHelper;
/**
* @var GroupViewFactory
* @inject
*/
public $groupViewFactory;
/**
* @var UserViewFactory
* @inject
*/
public $userViewFactory;
/**
* @var IUserPermissions
* @inject
*/
public $userAcl;
/**
* @var Roles
* @inject
*/
public $roles;
/**
* @var InstanceViewFactory
* @inject
*/
public $instanceViewFactory;
/**
* @var Passwords
* @inject
*/
public $passwordsService;
public function checkDefault()
{
if (!$this->userAcl->canViewAll()) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of all users matching given filters in given pagination rage.
* The result conforms to pagination protocol.
* @GET
*/
#[Query("offset", new VInt(), "Index of the first result.", required: false)]
#[Query("limit", new VInt(), "Maximal number of results returned.", required: false, nullable: true)]
#[Query(
"orderBy",
new VString(),
"Name of the column (column concept). The '!' prefix indicate descending order.",
required: false,
nullable: true,
)]
#[Query(
"filters",
new VObject(UserFilterFormat::class),
"Named filters that prune the result.",
required: false,
nullable: true,
)]
#[Query(
"locale",
new VString(),
"Currently set locale (used to augment order by clause if necessary),",
required: false,
nullable: true,
)]
public function actionDefault(
int $offset = 0,
?int $limit = null,
?string $orderBy = null,
?array $filters = null,
?string $locale = null
) {
$pagination = $this->getPagination(
$offset,
$limit,
$locale,
$orderBy,
($filters === null) ? [] : $filters,
['search', 'instanceId', 'roles']
);
$users = $this->users->getPaginated($pagination, $totalCount);
$users = array_map(
function (User $user) {
return $this->userViewFactory->getUser($user);
},
$users
);
$this->sendPaginationSuccessResponse($users, $pagination, false, $totalCount);
}
public function checkListByIds()
{
if (!$this->userAcl->canViewList()) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of users based on given ids.
* @POST
*/
#[Post("ids", new VArray(), "Identifications of users")]
public function actionListByIds()
{
$users = $this->users->findByIds($this->getRequest()->getPost("ids"));
$users = array_filter(
$users,
function (User $user) {
return $this->userAcl->canViewPublicData($user);
}
);
$this->sendSuccessResponse($this->userViewFactory->getUsers($users));
}
public function checkDetail(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canViewPublicData($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Get details of a user account
* @GET
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionDetail(string $id)
{
$user = $this->users->findOrThrow($id);
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkFindByExternalLogin(string $service, string $externalId)
{
$user = $this->externalLogins->getUser($service, $externalId);
if (!$user) {
throw new NotFoundException("User with given external login not found.");
}
if (!$this->userAcl->canViewPublicData($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Get details of a user identified via external login.
* @GET
*/
#[Path("service", new VString(1), "External authentication service name", required: true)]
#[Path("externalId", new VString(1), "External user identifier", required: true)]
public function actionFindByExternalLogin(string $service, string $externalId)
{
$user = $this->externalLogins->getUser($service, $externalId);
$this->sendSuccessResponse($user ? $this->userViewFactory->getUser($user) : null);
}
public function checkDelete(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canDelete($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Delete a user account
* @DELETE
* @throws ForbiddenRequestException
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionDelete(string $id)
{
$user = $this->users->findOrThrow($id);
$this->anonymizationHelper->prepareUserForSoftDelete($user);
$this->users->remove($user);
$this->sendSuccessResponse("OK");
}
public function checkUpdateProfile(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canUpdateProfile($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Update the profile associated with a user account
* @POST
* @throws BadRequestException
* @throws ForbiddenRequestException
* @throws InvalidApiArgumentException
* @throws WrongCredentialsException
* @throws NotFoundException
*/
#[Post("firstName", new VString(2), "First name", required: false)]
#[Post("lastName", new VString(2), "Last name", required: false)]
#[Post("titlesBeforeName", new VMixed(), "Titles before name", required: false, nullable: true)]
#[Post("titlesAfterName", new VMixed(), "Titles after name", required: false, nullable: true)]
#[Post("email", new VEmail(), "New email address", required: false)]
#[Post("oldPassword", new VString(1), "Old password of current user", required: false)]
#[Post("password", new VString(1), "New password of current user", required: false)]
#[Post("passwordConfirm", new VString(1), "Confirmation of new password of current user", required: false)]
#[Post("gravatarUrlEnabled", new VBool(), "Enable or disable gravatar profile image", required: false)]
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionUpdateProfile(string $id)
{
$req = $this->getRequest();
// fill user with provided data
$user = $this->users->findOrThrow($id);
$login = $user->getLogin();
// change details in separate methods
$this->changeUserEmail($user, $req->getPost("email"));
$this->changePersonalData(
$user,
$req->getPost("titlesBeforeName"),
$req->getPost("firstName"),
$req->getPost("lastName"),
$req->getPost("titlesAfterName")
);
$passwordChanged = $this->changeUserPassword(
$login,
$req->getPost("oldPassword"),
$req->getPost("password"),
$req->getPost("passwordConfirm")
);
$gravatarUrlEnabled = $req->getPost("gravatarUrlEnabled");
if ($gravatarUrlEnabled !== null) { // null or missing value -> no update
$user->setGravatar(filter_var($gravatarUrlEnabled, FILTER_VALIDATE_BOOLEAN));
}
// make changes permanent
$this->users->flush();
$this->logins->flush();
$this->sendSuccessResponse(
[
"user" => $this->userViewFactory->getUser($user),
"accessToken" => $passwordChanged && $user === $this->getCurrentUser()
? $this->accessManager->issueRefreshedToken($this->getAccessToken())
: null
]
);
}
/**
* Change email if any given of the provided user.
* @param User $user
* @param null|string $email
* @throws BadRequestException
* @throws InvalidApiArgumentException
*/
private function changeUserEmail(User $user, ?string $email)
{
$email = trim($email ?? "");
if (strlen($email) === 0) {
return;
}
// check if there is not another user using provided email
$userEmail = $this->users->getByEmail($email);
if ($userEmail !== null && $userEmail->getId() !== $user->getId()) {
throw new BadRequestException("This email address is already taken.");
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidApiArgumentException('email', "Provided email is not in correct format");
}
$oldEmail = $user->getEmail();
if (strtolower($oldEmail) !== strtolower($email)) {
// old and new email are not same, we have to changed and verify it
$user->setEmail($email);
// do not forget to change local login (if any)
if ($user->getLogin()) {
$user->getLogin()->setUsername($email);
}
// email has to be re-verified
$user->setVerified(false);
$this->emailVerificationHelper->process($user);
}
}
/**
* Change first name and last name and check if user can change them.
* @param User $user
* @param null|string $titlesBefore
* @param null|string $firstName
* @param null|string $lastName
* @param null|string $titlesAfter
* @throws ForbiddenRequestException
*/
private function changePersonalData(
User $user,
?string $titlesBefore,
?string $firstName,
?string $lastName,
?string $titlesAfter
) {
if (
($titlesBefore !== null || $firstName !== null || $lastName !== null || $titlesAfter !== null) &&
!$this->userAcl->canUpdatePersonalData($user)
) {
throw new ForbiddenRequestException("You cannot update personal data");
}
if ($titlesBefore !== null) {
$user->setTitlesBeforeName(trim($titlesBefore));
}
if ($firstName && trim($firstName)) {
$user->setFirstName(trim($firstName));
}
if ($lastName && trim($lastName)) {
$user->setLastName(trim($lastName));
}
if ($titlesAfter !== null) {
$user->setTitlesAfterName(trim($titlesAfter));
}
}
/**
* Change password of user if provided.
* @param Login|null $login
* @param null|string $oldPassword
* @param null|string $password
* @param null|string $passwordConfirm
* @throws InvalidApiArgumentException
* @throws WrongCredentialsException
*/
private function changeUserPassword(
?Login $login,
?string $oldPassword,
?string $password,
?string $passwordConfirm
): bool {
if (!$login || (!$oldPassword && !$password && !$passwordConfirm)) {
// password was not provided, or user is not logged as local one
return false;
}
if (!$password || !$passwordConfirm) {
// old password was provided but the new ones not, illegal state
throw new InvalidApiArgumentException('password|passwordConfirm', "New password was not provided");
}
// passwords need to be handled differently
if (
$login->passwordsMatchOrEmpty($oldPassword, $this->passwordsService) ||
(!$oldPassword && $this->userAcl->canForceChangePassword($login->getUser()))
) {
// check if new passwords match each other
if ($password !== $passwordConfirm) {
throw new WrongCredentialsException(
"Provided passwords do not match",
FrontendErrorMappings::E400_102__WRONG_CREDENTIALS_PASSWORDS_NOT_MATCH
);
}
$login->changePassword($password, $this->passwordsService);
$login->getUser()->setTokenValidityThreshold(new DateTime());
$event = SecurityEvent::createChangePasswordEvent(
$this->getHttpRequest()->getRemoteAddress(),
$login->getUser()
);
$this->securityEvents->persist($event);
} else {
throw new WrongCredentialsException(
"Your current password does not match",
FrontendErrorMappings::E400_103__WRONG_CREDENTIALS_CURRENT_PASSWORD_NOT_MATCH
);
}
return true;
}
public function checkUpdateSettings(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canUpdateProfile($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Update the profile settings
* @POST
* @throws NotFoundException
*/
#[Post("defaultLanguage", new VString(), "Default language of UI", required: false)]
#[Post(
"newAssignmentEmails",
new VBool(),
"Flag if email should be sent to user when new assignment was created",
required: false,
)]
#[Post(
"assignmentDeadlineEmails",
new VBool(),
"Flag if email should be sent to user if assignment deadline is nearby",
required: false,
)]
#[Post(
"submissionEvaluatedEmails",
new VBool(),
"Flag if email should be sent to user when resubmission was evaluated",
required: false,
)]
#[Post(
"solutionCommentsEmails",
new VBool(),
"Flag if email should be sent to user when new submission comment is added",
required: false,
)]
#[Post(
"solutionReviewsEmails",
new VBool(),
"Flag enabling review-related email notifications sent to the author of the solution",
required: false,
)]
#[Post(
"pointsChangedEmails",
new VBool(),
"Flag if email should be sent to user when the points were awarded for assignment",
required: false,
)]
#[Post(
"assignmentSubmitAfterAcceptedEmails",
new VBool(),
"Flag if email should be sent to the group supervisor if a student submits new solution "
. "for already accepted assignment",
required: false,
)]
#[Post(
"assignmentSubmitAfterReviewedEmails",
new VBool(),
"Flag if email should be sent to group supervisor if a student submits new solution "
. "for already reviewed and not accepted assignment",
required: false,
)]
#[Post(
"exerciseNotificationEmails",
new VBool(),
"Flag if notifications sent by authors of exercises should be sent via email.",
required: false,
)]
#[Post(
"solutionAcceptedEmails",
new VBool(),
"Flag if notification should be sent to a student when solution accepted flag is changed.",
required: false,
)]
#[Post(
"solutionReviewRequestedEmails",
new VBool(),
"Flag if notification should be send to a teacher when a solution reviewRequested flag is changed "
. "in a supervised/admin-ed group.",
required: false,
)]
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionUpdateSettings(string $id)
{
$req = $this->getRequest();
$user = $this->users->findOrThrow($id);
$settings = $user->getSettings();
// handle boolean flags
$knownBoolFlags = [
"newAssignmentEmails",
"assignmentDeadlineEmails",
"submissionEvaluatedEmails",
"solutionCommentsEmails",
"solutionReviewsEmails",
"assignmentCommentsEmails",
"pointsChangedEmails",
"assignmentSubmitAfterAcceptedEmails",
"assignmentSubmitAfterReviewedEmails",
"exerciseNotificationEmails",
"solutionAcceptedEmails",
"solutionReviewRequestedEmails",
];
foreach ($knownBoolFlags as $flag) {
if ($req->getPost($flag) !== null) {
$settings->setFlag($flag, filter_var($req->getPost($flag), FILTER_VALIDATE_BOOLEAN));
}
}
// handle string flags
if ($req->getPost("defaultLanguage") !== null) {
$settings->setDefaultLanguage(trim($req->getPost("defaultLanguage")));
}
$this->users->persist($user);
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkUpdateUiData(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canUpdateProfile($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Update the user-specific structured UI data
* @POST
* @throws NotFoundException
*/
#[Post("uiData", new VArray(), "Structured user-specific UI data", nullable: true)]
#[Post(
"overwrite",
new VBool(),
"Flag indicating that uiData should be overwritten completely (instead of regular merge)",
required: false,
)]
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionUpdateUiData(string $id)
{
$req = $this->getRequest();
$user = $this->users->findOrThrow($id);
$uiData = $user->getUiData();
$overwrite = filter_var($req->getPost("overwrite"), FILTER_VALIDATE_BOOLEAN);
$newUiData = $req->getPost("uiData");
if (!$newUiData && !$overwrite) {
// nothing will change
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
return;
}
if (!$newUiData && ($overwrite || $uiData)) {
$user->setUiData(null); // ui data are being erased
} else {
if (!$overwrite && $uiData) {
$newUiData = array_merge($uiData->getData(), $newUiData);
}
if (!$uiData) {
$uiData = new UserUiData($newUiData);
$user->setUiData($uiData);
} else {
$uiData->setData($newUiData);
}
}
$this->users->persist($user);
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkCreateLocalAccount(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canCreateLocalAccount($user)) {
throw new ForbiddenRequestException();
}
if ($user->hasLocalAccount()) {
throw new BadRequestException("User is already registered locally");
}
if (!$user->isVerified()) {
throw new BadRequestException("Email address has to be verified before creating local account");
}
}
/**
* If user is registered externally, add local account as another login method.
* Created password is empty and has to be changed in order to use it.
* @POST
* @throws InvalidApiArgumentException
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionCreateLocalAccount(string $id)
{
$user = $this->users->findOrThrow($id);
Login::createLogin($user, $user->getEmail(), "", $this->passwordsService);
$this->users->flush();
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkGroups(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canViewGroups($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of non-archived groups for a user
* @GET
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionGroups(string $id)
{
$user = $this->users->findOrThrow($id);
$asStudent = $user->getGroupsAsStudent()->filter(
function (Group $group) {
return !$group->isArchived();
}
);
$asSupervisor = $user->getGroupsAsSupervisor()->filter(
function (Group $group) {
return !$group->isArchived();
}
);
$this->sendSuccessResponse(
[
"supervisor" => $this->groupViewFactory->getGroups($asSupervisor->getValues()),
"student" => $this->groupViewFactory->getGroups($asStudent->getValues()),
"stats" => $user->getGroupsAsStudent()->map(
function (Group $group) use ($user) {
return $this->groupViewFactory->getStudentsStats($group, $user);
}
)->getValues(),
]
);
}
public function checkAllGroups(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canViewGroups($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of all groups for a user
* @GET
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionAllGroups(string $id)
{
$user = $this->users->findOrThrow($id);
$this->sendSuccessResponse(
[
"supervisor" => $this->groupViewFactory->getGroups($user->getGroupsAsSupervisor()->getValues(), false),
"student" => $this->groupViewFactory->getGroups($user->getGroupsAsStudent()->getValues(), false)
]
);
}
public function checkInstances(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canViewInstances($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of instances where a user is registered
* @GET
* @throws NotFoundException
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionInstances(string $id)
{
$user = $this->users->findOrThrow($id);
$this->sendSuccessResponse($this->instanceViewFactory->getInstances(
$user->getInstances()->toArray(),
$this->getCurrentUser()
));
}
public function checkSetRole(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canSetRole($user)) {
throw new ForbiddenRequestException();
}
if ($this->getCurrentUser() === $user) {
throw new ForbiddenRequestException("You cannot change your role");
}
}
/**
* Set a given role to the given user.
* @POST
* @throws InvalidApiArgumentException
* @throws NotFoundException
*/
#[Post("role", new VString(1), "Role which should be assigned to the user")]
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionSetRole(string $id)
{
$user = $this->users->findOrThrow($id);
$role = $this->getRequest()->getPost("role");
// validate role
if (!$this->roles->validateRole($role)) {
throw new InvalidApiArgumentException('role', "Unknown user role '$role'");
}
$user->setRole($role);
$this->users->flush();
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkInvalidateTokens(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canInvalidateTokens($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Invalidate all existing tokens issued for given user
* @POST
* @throws ForbiddenRequestException
* @throws NotFoundException
*/
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionInvalidateTokens(string $id)
{
$user = $this->users->findOrThrow($id);
$user->setTokenValidityThreshold(new DateTime());
$this->users->flush();
$event = SecurityEvent::createInvalidateTokensEvent($this->getHttpRequest()->getRemoteAddress(), $user);
$this->securityEvents->persist($event);
$token = $this->getAccessToken();
$this->sendSuccessResponse(
[
"user" => $this->userViewFactory->getUser($user),
"accessToken" => $user === $this->getCurrentUser() ? $this->accessManager->issueRefreshedToken(
$token
) : null
]
);
}
public function checkSetAllowed(string $id)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canSetIsAllowed($user)) {
throw new ForbiddenRequestException();
}
if ($this->getCurrentUser() === $user) {
throw new ForbiddenRequestException("You cannot change the allow flag of your self");
}
}
/**
* Set "isAllowed" flag of the given user. The flag determines whether a user may perform any operation of the API.
* @POST
* @throws InvalidApiArgumentException
* @throws NotFoundException
*/
#[Post("isAllowed", new VBool(), "Whether the user is allowed (active) or not.")]
#[Path("id", new VUuid(), "Identifier of the user", required: true)]
public function actionSetAllowed(string $id)
{
$user = $this->users->findOrThrow($id);
$isAllowed = filter_var($this->getRequest()->getPost("isAllowed"), FILTER_VALIDATE_BOOLEAN);
$user->setIsAllowed($isAllowed);
$this->users->flush();
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkUpdateExternalLogin(string $id, string $service)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canSetExternalIds($user)) {
throw new ForbiddenRequestException();
}
// in the future, we might consider cross-checking the service ID
}
/**
* Add or update existing external ID of given authentication service.
* @POST
* @throws InvalidApiArgumentException
*/
#[Post("externalId", new VString(1, 128))]
#[Path("id", new VUuid(), "identifier of the user", required: true)]
#[Path("service", new VString(), "identifier of the authentication service (login type)", required: true)]
public function actionUpdateExternalLogin(string $id, string $service)
{
$user = $this->users->findOrThrow($id);
// make sure the external ID is not used for another user
$externalId = $this->getRequest()->getPost("externalId");
$anotherUser = $this->externalLogins->getUser($service, $externalId);
if ($anotherUser) {
if ($anotherUser->getId() !== $id) {
// oopsie, this external ID is already used for a different user
throw new InvalidApiArgumentException('externalId', "This ID is already used by another user.");
}
// otherwise the external ID is already set to this user, so there is nothing to change...
} else {
// create/update external login entry
$login = $this->externalLogins->findByUser($user, $service);
if ($login) {
$login->setExternalId($externalId);
} else {
$login = new ExternalLogin($user, $service, $externalId);
}
$this->externalLogins->persist($login);
$this->users->refresh($user);
}
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
public function checkRemoveExternalLogin(string $id, string $service)
{
$user = $this->users->findOrThrow($id);
if (!$this->userAcl->canSetExternalIds($user)) {
throw new ForbiddenRequestException();
}
// in the future, we might consider cross-checking the service ID
}
/**
* Remove external ID of given authentication service.
* @DELETE
*/
#[Path("id", new VUuid(), "identifier of the user", required: true)]
#[Path("service", new VString(), "identifier of the authentication service (login type)", required: true)]
public function actionRemoveExternalLogin(string $id, string $service)
{
$user = $this->users->findOrThrow($id);
$login = $this->externalLogins->findByUser($user, $service);
if ($login) {
$this->externalLogins->remove($login);
$this->users->refresh($user);
}
$this->sendSuccessResponse($this->userViewFactory->getUser($user));
}
}