-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathUserAccountController.java
788 lines (688 loc) · 33.9 KB
/
UserAccountController.java
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
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.biz.tenants;
import sirius.biz.model.LoginData;
import sirius.biz.model.PermissionData;
import sirius.biz.packages.Packages;
import sirius.biz.protocol.AuditLog;
import sirius.biz.web.BasePageHelper;
import sirius.biz.web.BizController;
import sirius.db.mixing.BaseEntity;
import sirius.db.mixing.Mixing;
import sirius.kernel.commons.Context;
import sirius.kernel.commons.Explain;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Tuple;
import sirius.kernel.di.std.ConfigValue;
import sirius.kernel.di.std.Part;
import sirius.kernel.health.Exceptions;
import sirius.kernel.info.Product;
import sirius.kernel.nls.NLS;
import sirius.web.controller.AutocompleteHelper;
import sirius.web.controller.DefaultRoute;
import sirius.web.controller.Message;
import sirius.web.controller.Page;
import sirius.web.controller.Routed;
import sirius.web.http.WebContext;
import sirius.web.mails.Mails;
import sirius.web.security.LoginRequired;
import sirius.web.security.Permission;
import sirius.web.security.Permissions;
import sirius.web.security.UserContext;
import sirius.web.security.UserInfo;
import sirius.web.services.InternalService;
import sirius.web.services.JSONStructuredOutput;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Provides a GUI for managing user accounts.
*
* @param <I> the type of database IDs used by the concrete implementation
* @param <T> specifies the effective entity type used to represent Tenants
* @param <U> specifies the effective entity type used to represent UserAccounts
*/
public abstract class UserAccountController<I extends Serializable, T extends BaseEntity<I> & Tenant<I>, U extends BaseEntity<I> & UserAccount<I, T>>
extends BizController {
/**
* The permission required to add, modify or lock accounts.
*/
public static final String PERMISSION_MANAGE_USER_ACCOUNTS = "permission-manage-user-accounts";
/**
* The permission required to add, modify or lock accounts of the system tenant.
*/
public static final String PERMISSION_MANAGE_SYSTEM_USERS = "permission-manage-system-users";
/**
* The feature required to provide a custom config per user account.
*/
public static final String FEATURE_USER_ACCOUNT_CONFIG = "feature-user-account-config";
/**
* The permission required to delete accounts.
*/
public static final String PERMISSION_DELETE_USER_ACCOUNTS = "permission-delete-user-accounts";
private static final String PARAM_PASSWORD = "password";
private static final String PARAM_NAME = "name";
private static final String PARAM_USERNAME = "username";
private static final String PARAM_URL = "url";
private static final String PARAM_ROOT = "root";
private static final String PARAM_EMAIL = "email";
private static final String PARAM_REASON = "reason";
private static final String LIST_ROUTE = "/user-accounts";
private static final String DETAIL_ROUTE_PREFIX = "/user-account/";
@Part
protected Mails mails;
@ConfigValue("product.wondergemRoot")
protected String wondergemRoot;
@ConfigValue("security.roles")
protected List<String> roles;
@ConfigValue("security.subScopes")
protected List<String> subScopes;
@Part
protected AuditLog auditLog;
@Part
private Packages packages;
/**
* We provide a custom field for the tenant helper.
* <p>
* In contrast to <{@link #tenants}, this will have the generic arguments applied and is therefore
* fully aware of the exact classes to use.
*/
@Part
private Tenants<I, T, U> matchingTenants;
@Part
private ProfileController<I, T, U> profileController;
/**
* Shows a list of all available users of the current tenant.
*
* @param webContext the current request
*/
@Routed(LIST_ROUTE)
@DefaultRoute
@LoginRequired
public void accounts(WebContext webContext) {
assertProperUserManagementPermission();
Page<U> accounts =
getUsersAsPage(webContext).addBooleanFacet(UserAccount.USER_ACCOUNT_DATA.inner(UserAccountData.LOGIN)
.inner(LoginData.ACCOUNT_LOCKED)
.toString(),
NLS.get("LoginData.accountLocked"))
.withTotalCount()
.asPage();
webContext.respondWith().template("/templates/biz/tenants/user-accounts.html.pasta", accounts, getUserClass());
}
/**
* Ensures that the current user is permitted to manage the user accounts for the current tenant.
* <p>
* This is made public so that other controllers which enhance the user management can re-use the logic.
*/
public static void assertProperUserManagementPermission() {
UserInfo currentUser = UserContext.getCurrentUser();
currentUser.assertPermission(getUserManagementPermission());
}
/**
* Determines the permission to check for when determining if the current user can manage other users.
* <p>
* For the system tenant a user needs "permission-manage-system-users" for all others
* "permission-manage-user-accounts".
*/
public static String getUserManagementPermission() {
UserInfo currentUser = UserContext.getCurrentUser();
boolean isCurrentTenantSystemTenant = currentUser.tryAs(Tenant.class)
.map(tenant -> tenant.hasPermission(Tenant.PERMISSION_SYSTEM_TENANT))
.orElse(false);
if (isCurrentTenantSystemTenant) {
return PERMISSION_MANAGE_SYSTEM_USERS;
} else {
return PERMISSION_MANAGE_USER_ACCOUNTS;
}
}
/**
* Returns the effective entity class used to represent user accounts.
*
* @return the effective entity class for user accounts
*/
@SuppressWarnings("unchecked")
protected Class<U> getUserClass() {
return (Class<U>) tenants.getUserClass();
}
/**
* Constructs a page helper for the user accounts to view.
*
* @param webContext the current request
* @return the list of available user accounts wrapped as page helper
*/
protected abstract BasePageHelper<U, ?, ?, ?> getUsersAsPage(WebContext webContext);
/**
* Shows an editor for the given account.
*
* @param webContext the current request
* @param accountId the {@link UserAccount} to edit
*/
@Routed("/user-account/:1")
@LoginRequired
public void account(WebContext webContext, String accountId) {
assertProperUserManagementPermission();
U userAccount = findForTenant(getUserClass(), accountId);
boolean requestHandled =
prepareSave(webContext).withAfterCreateURI("/user-account/${id}").withPreSaveHandler(isNew -> {
if (isUserLockingHimself(userAccount)) {
throw Exceptions.createHandled().withNLSKey("UserAccountController.cannotLockSelf").handle();
}
List<String> accessiblePermissions = getRoles();
packages.loadAccessiblePermissions(webContext.getParameters("roles"),
accessiblePermissions::contains,
userAccount.getUserAccountData()
.getPermissions()
.getPermissions()
.modify());
}).saveEntity(userAccount);
if (!requestHandled) {
validate(userAccount);
webContext.respondWith()
.template("/templates/biz/tenants/user-account-details.html.pasta", userAccount, this);
}
}
private boolean isUserLockingHimself(U userAccount) {
if (!userAccount.isChanged(UserAccount.USER_ACCOUNT_DATA.inner(UserAccountData.LOGIN)
.inner(LoginData.ACCOUNT_LOCKED))) {
return false;
}
if (!userAccount.getUserAccountData().getLogin().isAccountLocked()) {
return false;
}
return Objects.equals(getUser().getUserObject(UserAccount.class), userAccount);
}
/**
* Returns a list of supported languages and their translated name.
*
* @return a list of tuples containing the ISO code and the translated name
*/
public List<Tuple<String, String>> getAvailableLanguages() {
return tenants.getTenantUserManager().getAvailableLanguages();
}
/**
* Shows an editor for the custom configuration of the given user.
*
* @param webContext the current request
* @param accountId the id of the account which config will be edited
*/
@Routed("/user-account/:1/config")
@LoginRequired
@Permission(FEATURE_USER_ACCOUNT_CONFIG)
public void accountConfig(WebContext webContext, String accountId) {
assertProperUserManagementPermission();
U userAccount = findForTenant(getUserClass(), accountId);
assertNotNew(userAccount);
webContext.respondWith().template("/templates/biz/tenants/user-account-config.html.pasta", userAccount);
}
/**
* Provides a JSON API to change the settings of an account, including its configuration.
*
* @param webContext the current request
* @param jsonOutput the JSON response being generated
* @param accountId the id of the account to update
*/
@Routed("/user-account/:1/config/update")
@InternalService
@LoginRequired
@Permission(FEATURE_USER_ACCOUNT_CONFIG)
public void updateAccountConfig(WebContext webContext, JSONStructuredOutput jsonOutput, String accountId) {
assertProperUserManagementPermission();
U userAccount = findForTenant(getUserClass(), accountId);
assertNotNew(userAccount);
String configFieldName = UserAccount.USER_ACCOUNT_DATA.inner(UserAccountData.PERMISSIONS)
.inner(PermissionData.CONFIG_STRING)
.getName();
if (webContext.hasParameter(configFieldName)) {
// Reads configuration manually to prevent altering other fields
String config = webContext.getParameter(configFieldName);
userAccount.getUserAccountData().getPermissions().setConfigString(config);
// parses the config to make sure it is valid
userAccount.getUserAccountData().getPermissions().getConfig();
}
userAccount.getMapper().update(userAccount);
}
/**
* Lists all roles which can be granted to a user.
*
* @return all roles which can be granted to a user
*/
public List<String> getRoles() {
Tenant<?> tenant = tenants.getRequiredTenant();
return packages.filterAccessiblePermissions(roles, tenant::hasPermission);
}
/**
* Returns the translated name of a role.
*
* @param role the role to translate
* @return a translated name for the given role
*/
public String getRoleName(String role) {
return Permissions.getTranslatedPermission(role);
}
/**
* Returns a description of the role.
*
* @param role the role to fetch the description for
* @return the description of the given role
*/
public String getRoleDescription(String role) {
return Permissions.getPermissionDescription(role);
}
public List<String> getSubScopes() {
return Collections.unmodifiableList(subScopes);
}
/**
* Returns the name of the given sub scope.
*
* @param scope the technical name of the sub scope
* @return the sub scope name as shown to the user
*/
public String getSubScopeName(String scope) {
return NLS.get("SubScope." + scope + ".name");
}
/**
* Sets a new password for the given account.
*
* @param webContext the current request
* @param accountId the account for which a password is to be set
*/
@Routed("/user-account/:1/password")
@LoginRequired
public void setPassword(final WebContext webContext, String accountId) {
U userAccount = findForTenant(getUserClass(), accountId);
// the own user must not change the password without giving the old one; we just forward to the regular profile
// password change site
if (userAccount.getUserAccountData().isOwnUser()) {
profileController.profileChangePassword(webContext);
return;
}
assertProperUserManagementPermission();
if (webContext.ensureSafePOST()) {
try {
String newPassword = webContext.get(ProfileController.PARAM_NEW_PASSWORD).asString();
String confirmation = webContext.get(ProfileController.PARAM_CONFIRMATION).asString();
profileController.validateNewPassword(userAccount, newPassword, confirmation);
userAccount.getUserAccountData().getLogin().setCleartextPassword(newPassword);
userAccount.getMapper().update(userAccount);
auditLog.neutral("AuditLog.passwordChangeOther")
.causedByCurrentUser()
.forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername())
.forTenant(String.valueOf(userAccount.getTenant().getId()),
matchingTenants.fetchCachedRequiredTenant(userAccount.getTenant())
.getTenantData()
.getName())
.log();
showSavedMessage();
webContext.respondWith().redirectToGet(DETAIL_ROUTE_PREFIX + accountId);
return;
} catch (Exception exception) {
auditLog.neutral("AuditLog.passwordChangeOtherFailed")
.causedByCurrentUser()
.forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername())
.forTenant(String.valueOf(userAccount.getTenant().getId()),
matchingTenants.fetchCachedRequiredTenant(userAccount.getTenant())
.getTenantData()
.getName())
.log();
UserContext.handle(exception);
}
}
// load the password dialog in "user" mode without requiring the old password
webContext.respondWith()
.template("/templates/biz/tenants/profile-change-password.html.pasta", userAccount, "user", false);
}
/**
* Generates a new password for the given account.
*
* @param webContext the current request
* @param accountId the account for which a password is to be created
*/
@Routed("/user-account/:1/generate-password")
@LoginRequired
public void generatePassword(final WebContext webContext, String accountId) {
assertProperUserManagementPermission();
U userAccount = findForTenant(getUserClass(), accountId);
generateNewPassword(userAccount);
UserContext.message(Message.info().withTextMessage(NLS.get("UserAccountConroller.passwordGenerated")));
webContext.respondWith().redirectToGet(DETAIL_ROUTE_PREFIX + accountId);
}
/**
* Generates a new password for the given account and send a mail to the user.
*
* @param webContext the current request
* @param accountId the account for which a password is to be created
*/
@Routed("/user-account/:1/generate-and-send-password")
@LoginRequired
public void generateAndSendPassword(final WebContext webContext, String accountId) {
assertProperUserManagementPermission();
U userAccount = findForTenant(getUserClass(), accountId);
generateNewPassword(userAccount);
if (userAccount.getUserAccountData().canSendGeneratedPassword()) {
UserContext.message(Message.info()
.withTextMessage(NLS.fmtr("UserAccountConroller.passwordGeneratedAndSent")
.set(PARAM_EMAIL,
userAccount.getUserAccountData().getEmail())
.format()));
UserContext userContext = UserContext.get();
userContext.runAs(userContext.getUserManager().findUserByUserId(userAccount.getUniqueName()), () -> {
Context mailContext = Context.create();
mailContext.set(PARAM_PASSWORD, userAccount.getUserAccountData().getLogin().getGeneratedPassword())
.set(PARAM_NAME, userAccount.getUserAccountData().getAddressableName())
.set(PARAM_USERNAME, userAccount.getUserAccountData().getLogin().getUsername())
.set(PARAM_URL, getBaseUrl())
.set(PARAM_REASON,
NLS.fmtr("UserAccountController.generatedPassword.reason")
.set("product", Product.getProduct().getName())
.format())
.set(PARAM_ROOT, wondergemRoot);
mails.createEmail()
.to(userAccount.getUserAccountData().getEmail(), userAccount.getUserAccountData().toString())
.subject(NLS.fmtr("UserAccountController.generatedPassword.subject")
.set("product", Product.getProduct().getName())
.format())
.textTemplate("/mail/useraccount/password.pasta", mailContext)
.htmlTemplate("/mail/useraccount/password.html.pasta", mailContext)
.send();
});
} else {
UserContext.message(Message.info().withTextMessage(NLS.get("UserAccountConroller.passwordGenerated")));
}
webContext.respondWith().redirectToGet(DETAIL_ROUTE_PREFIX + accountId);
}
private void generateNewPassword(U userAccount) {
assertNotNew(userAccount);
if (!userAccount.getUserAccountData().isPasswordGenerationPossible()) {
throw Exceptions.createHandled()
.withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser")
.handle();
}
userAccount.getUserAccountData().getLogin().forceGenerationOfPassword();
userAccount.getMapper().update(userAccount);
auditLog.neutral("AuditLog.passwordGenerated")
.causedByCurrentUser()
.forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername())
.forTenant(String.valueOf(userAccount.getTenant().getId()),
matchingTenants.fetchCachedRequiredTenant(userAccount.getTenant()).getTenantData().getName())
.log();
}
/**
* Provides a JSON API which re-sends the password to the account with the given email address.
*
* @param webContext the current request
* @param jsonOutput the JSON response being generated
*/
@Routed("/forgotPassword")
@InternalService
public void forgotPassword(final WebContext webContext, JSONStructuredOutput jsonOutput) {
List<U> accounts = findUserAccountsWithEmail(webContext.get(PARAM_EMAIL).asString().toLowerCase());
if (accounts.isEmpty()) {
throw Exceptions.createHandled().withNLSKey("UserAccountController.noUserFoundForEmail").handle();
}
if (accounts.size() > 1) {
throw Exceptions.createHandled().withNLSKey("UserAccountController.tooManyUsersFoundForEmail").handle();
}
U account = accounts.getFirst();
if (account.getUserAccountData().getLogin().isAccountLocked()) {
auditLog.negative("AuditLog.resetPasswordRejected")
.causedByUser(account.getUniqueName(), account.getUserAccountData().getLogin().getUsername())
.forUser(account.getUniqueName(), account.getUserAccountData().getLogin().getUsername())
.forTenant(account.getTenant().getIdAsString(),
matchingTenants.fetchCachedRequiredTenant(account.getTenant()).getTenantData().getName())
.log();
throw Exceptions.createHandled().withNLSKey("LoginData.accountIsLocked").handle();
}
account.getUserAccountData().getLogin().forceGenerationOfPassword();
UserContext userContext = UserContext.get();
userContext.runAs(userContext.getUserManager().findUserByUserId(account.getUniqueName()),
() -> account.getMapper().update(account));
auditLog.neutral("AuditLog.resetPassword")
.causedByUser(account.getUniqueName(), account.getUserAccountData().getLogin().getUsername())
.forUser(account.getUniqueName(), account.getUserAccountData().getLogin().getUsername())
.forTenant(account.getTenant().getIdAsString(),
matchingTenants.fetchCachedRequiredTenant(account.getTenant()).getTenantData().getName())
.log();
if (Strings.isFilled(account.getUserAccountData().getEmail())) {
userContext.runAs(userContext.getUserManager().findUserByUserId(account.getUniqueName()), () -> {
Context context = Context.create()
.set(PARAM_REASON,
NLS.fmtr("UserAccountController.forgotPassword.reason")
.set("ip", webContext.getRemoteIP().toString())
.format())
.set(PARAM_PASSWORD,
account.getUserAccountData().getLogin().getGeneratedPassword())
.set(PARAM_NAME, account.getUserAccountData().getAddressableName())
.set(PARAM_USERNAME, account.getUserAccountData().getLogin().getUsername())
.set(PARAM_URL, getBaseUrl())
.set(PARAM_ROOT, wondergemRoot);
mails.createEmail()
.to(account.getUserAccountData().getEmail(), account.getUserAccountData().toString())
.subject(NLS.get("UserAccountController.forgotPassword.subject"))
.textTemplate("/mail/useraccount/password.pasta", context)
.htmlTemplate("/mail/useraccount/password.html.pasta", context)
.send();
});
}
}
@SuppressWarnings("unchecked")
@Explain("The redundant cast is required as otherwise the Java compiler gets confused.")
protected List<U> findUserAccountsWithEmail(String email) {
return (List<U>) (Object) mixing.getDescriptor(getUserClass())
.getMapper()
.select(getUserClass())
.eq(UserAccount.USER_ACCOUNT_DATA.inner(UserAccountData.EMAIL), email)
.limit(2)
.queryList();
}
/**
* Locks the given account.
*
* @param webContext the current request
* @param accountId the account to lock
*/
@LoginRequired
@Routed("/user-account/:1/lock")
public void lockUser(final WebContext webContext, String accountId) {
assertProperUserManagementPermission();
Optional<U> account = tryFindForTenant(getUserClass(), accountId);
account.ifPresent(user -> {
if (Objects.equals(getUser().getUserObject(UserAccount.class), user)) {
throw Exceptions.createHandled().withNLSKey("UserAccountController.cannotLockSelf").handle();
}
user.getUserAccountData().getLogin().setAccountLocked(true);
user.getMapper().update(user);
});
webContext.respondWith().redirectToGet(LIST_ROUTE);
}
/**
* Unlocks the given account.
*
* @param webContext the current request
* @param accountId the account to unlock
*/
@LoginRequired
@Routed("/user-account/:1/unlock")
public void unlockUser(final WebContext webContext, String accountId) {
assertProperUserManagementPermission();
Optional<U> account = tryFindForTenant(getUserClass(), accountId);
account.ifPresent(user -> {
user.getUserAccountData().getLogin().setAccountLocked(false);
user.getMapper().update(user);
});
webContext.respondWith().redirectToGet(LIST_ROUTE);
}
/**
* Deletes the given account.
*
* @param webContext the current request
* @param accountId the account to delete
*/
@LoginRequired
@Routed("/user-account/:1/delete")
@Permission(PERMISSION_DELETE_USER_ACCOUNTS)
public void deleteAdmin(final WebContext webContext, String accountId) {
assertProperUserManagementPermission();
Optional<U> account = tryFindForTenant(getUserClass(), accountId);
account.ifPresent(u -> {
if (Objects.equals(getUser().getUserObject(UserAccount.class), u)) {
throw Exceptions.createHandled().withNLSKey("UserAccountController.cannotDeleteSelf").handle();
}
});
deleteEntity(webContext, account);
webContext.respondWith().redirectToGet(LIST_ROUTE);
}
/**
* Executes a logout for the current scope.
*
* @param webContext the current request
*/
@Routed("/logout")
public void logout(WebContext webContext) {
UserContext.get().getUserManager().logout(webContext);
webContext.respondWith().redirectToGet(wondergemRoot);
}
/**
* Autocompletion for UserAccounts.
* <p>
* Only accepts UserAccounts which belong to the current Tenant.
*
* @param webContext the current request
*/
@LoginRequired
@Routed("/user-accounts/autocomplete")
public void usersAutocomplete(final WebContext webContext) {
AutocompleteHelper.handle(webContext, (query, result) -> {
Page<U> accounts = getUsersAsPage(webContext).asPage();
accounts.getItems().stream().limit(AutocompleteHelper.DEFAULT_LIMIT).forEach(userAccount -> {
result.accept(AutocompleteHelper.suggest(userAccount.getUniqueName())
.withFieldLabel(userAccount.toString()));
});
});
}
/**
* Lists all users which the current user can "become" (switch to).
*
* @param webContext the current request
*/
@Routed("/user-accounts/select")
@LoginRequired
@Permission(TenantUserManager.PERMISSION_SELECT_USER_ACCOUNT)
public void selectUserAccounts(WebContext webContext) {
Page<U> selectableUsers = getSelectableUsersAsPage().withContext(webContext)
.addBooleanFacet(UserAccount.USER_ACCOUNT_DATA.inner(
UserAccountData.LOGIN)
.inner(LoginData.ACCOUNT_LOCKED)
.toString(),
NLS.get("LoginData.accountLocked"))
.withTotalCount()
.asPage();
webContext.respondWith()
.template("/templates/biz/tenants/select-user-account.html.pasta",
selectableUsers,
isCurrentlySpying(webContext));
}
private boolean isCurrentlySpying(WebContext webContext) {
return webContext.getSessionValue(UserContext.getCurrentScope().getScopeId() + TenantUserManager.SPY_ID_SUFFIX)
.isFilled();
}
/**
* Constructs a page helper for the selectable user accounts.
*
* @return the list of selectable user accounts wrapped as page helper
*/
protected abstract BasePageHelper<U, ?, ?, ?> getSelectableUsersAsPage();
/**
* Switches from the current user to the given user.
* <p>
* The current user can act on the behalf of the given user, he will appear as he is that user,
* and he will have the roles the given user has.
* The only permissions kept from the original user may be {@link TenantUserManager#PERMISSION_SYSTEM_TENANT_AFFILIATE},
* and {@link TenantUserManager#PERMISSION_SELECT_USER_ACCOUNT} (to switch back).
* Additionally, the permission {@link TenantUserManager#PERMISSION_SPY_USER} is given, so the system can identify the user switch.
*
* @param webContext the current request
* @param accountId the id of the user to switch to
*/
@LoginRequired
@Routed("/user-accounts/select/:1")
public void selectUserAccount(final WebContext webContext, String accountId) {
if ("main".equals(accountId)) {
// If we try to switch back to the main user - without being different user in the first place,
// then this action was most probably triggered by the "tenant info badge" in the UI, and meant to
// actually reset the tenant not the user - therefore we redirect to there.
if (!isCurrentlySpying(webContext)) {
webContext.respondWith().redirectToGet("/tenants/select/main");
return;
}
String originalUserId = tenants.getTenantUserManager().getOriginalUserId();
UserAccount<?, ?> account = tenants.getTenantUserManager().fetchAccount(originalUserId);
auditLog.neutral("AuditLog.switchedToMainUser")
.hideFromUser()
.causedByUser(account.getUniqueName(), account.getUserAccountData().getLogin().getUsername())
.forCurrentUser()
.log();
webContext.setSessionValue(UserContext.getCurrentScope().getScopeId() + TenantUserManager.SPY_ID_SUFFIX,
null);
webContext.respondWith().redirectTemporarily("/user-accounts/select");
return;
}
// Check that the user is generally permitted to "select / become" another user...
assertPermission(TenantUserManager.PERMISSION_SELECT_USER_ACCOUNT);
U user = mixing.getDescriptor(getUserClass()).getMapper().find(getUserClass(), accountId).orElse(null);
if (user == null) {
UserContext.get()
.addMessage(Message.error().withTextMessage(NLS.get("UserAccountController.cannotBecomeUser")));
selectUserAccounts(webContext);
return;
}
if (!user.getUserAccountData().canSelect()) {
UserContext.get()
.addMessage(Message.error().withTextMessage(NLS.get("UserAccountController.cannotBecomeUser")));
selectUserAccounts(webContext);
return;
}
// If the target user belongs to the system tenant, our current user has to have highest user management
// permission as otherwise we would perform an unwanted roles delegation (giving the current user higher
// access rights - right up to the system management level...)
if (Strings.areEqual(tenants.getTenantUserManager().getSystemTenantId(), user.getTenant().getIdAsString())
&& !getUser().hasPermission(PERMISSION_MANAGE_SYSTEM_USERS)) {
UserContext.get()
.addMessage(Message.error().withTextMessage(NLS.get("UserAccountController.cannotBecomeUser")));
selectUserAccounts(webContext);
return;
}
// If we're not part of the system tenant, ensure that we can only select users from the same tenant...
if (!getUser().hasPermission(TenantUserManager.PERMISSION_SYSTEM_TENANT_AFFILIATE)) {
assertTenant(user);
}
auditLog.neutral("AuditLog.selectedUser")
.hideFromUser()
.causedByCurrentUser()
.forUser(user.getUniqueName(), user.getUserAccountData().getLogin().getUsername())
.forTenant(user.getTenant().getIdAsString(),
matchingTenants.fetchCachedRequiredTenant(user.getTenant()).getTenantData().getName())
.log();
webContext.setSessionValue(UserContext.getCurrentScope().getScopeId() + TenantUserManager.SPY_ID_SUFFIX,
user.getUniqueName());
webContext.respondWith().redirectTemporarily(webContext.get("goto").asString(wondergemRoot));
}
/**
* Fetches the raw identifier of the current user's database entity, by removing the prefix indicating the entity's
* type.
*
* @return the raw identifier of the current user's database entity
*/
protected String fetchRawCurrentUserId() {
String userId = getUser().getUserId();
String prefix = Mixing.getNameForType(getUserClass()) + '-';
return userId.startsWith(prefix) ? userId.substring(prefix.length()) : userId;
}
}