-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathUserManager.java
More file actions
1319 lines (1114 loc) · 51 KB
/
UserManager.java
File metadata and controls
1319 lines (1114 loc) · 51 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
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
/*
* Copyright (c) 2005-2018 Fred Hutchinson Cancer Research Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.api.security;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.labkey.api.audit.AuditLogService;
import org.labkey.api.audit.AuditTypeEvent;
import org.labkey.api.data.Aggregate;
import org.labkey.api.data.ButtonBar;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.CompareType;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.CoreSchema;
import org.labkey.api.data.DbScope;
import org.labkey.api.data.DbScope.CommitTaskOption;
import org.labkey.api.data.DbScope.Transaction;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.RuntimeSQLException;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.SchemaTableInfo;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.data.SqlExecutor;
import org.labkey.api.data.SqlSelector;
import org.labkey.api.data.Table;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.exp.OntologyManager;
import org.labkey.api.exp.api.StorageProvisioner;
import org.labkey.api.query.ExprColumn;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.UserIdRenderer;
import org.labkey.api.security.SecurityManager.UserManagementException;
import org.labkey.api.security.permissions.AbstractActionPermissionTest;
import org.labkey.api.security.permissions.ApplicationAdminPermission;
import org.labkey.api.security.permissions.CanImpersonatePrivilegedSiteRolesPermission;
import org.labkey.api.security.permissions.SiteAdminPermission;
import org.labkey.api.security.roles.ApplicationAdminRole;
import org.labkey.api.security.roles.SiteAdminRole;
import org.labkey.api.util.HeartBeat;
import org.labkey.api.util.HtmlString;
import org.labkey.api.util.Link;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.Pair;
import org.labkey.api.util.TestContext;
import org.labkey.api.util.logging.LogHelper;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.AjaxCompletion;
import org.labkey.api.view.HttpView;
import org.labkey.api.view.ViewContext;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.labkey.api.security.SecurityManager.USER_ID_KEY;
import static org.labkey.api.security.permissions.AbstractActionPermissionTest.APPLICATION_ADMIN_EMAIL;
import static org.labkey.api.security.permissions.AbstractActionPermissionTest.SITE_ADMIN_EMAIL;
public class UserManager
{
private static final Logger LOG = LogHelper.getLogger(UserManager.class, "User management operations");
private static final CoreSchema CORE = CoreSchema.getInstance();
// NOTE: This static map will slowly grow, since user IDs & timestamps are added and never removed. It's a trivial amount of data, though.
private static final Map<Integer, Long> RECENT_USERS = new HashMap<>(100);
public static final String GROUP_NAME_CHAR_EXCLUSION_LIST = "@/\\&~"; // see renameGroup.jsp if you change this
public static final String USER_AUDIT_EVENT = "UserAuditEvent";
public static final int VALID_GROUP_NAME_LENGTH = 64;
public static final int VERIFICATION_EMAIL_TIMEOUT = 60 * 24; // in minutes, one day currently
public static final Comparator<User> USER_DISPLAY_NAME_COMPARATOR = Comparator.comparing(User::getFriendlyName, String.CASE_INSENSITIVE_ORDER);
/**
* Listener for user account related notifications. Typically registered during a module's startup via a call to
* {@link #addUserListener(UserListener)}
*/
public interface UserListener extends PropertyChangeListener
{
/** Fires when a user account is first created */
default void userAddedToSite(User user) {}
/** Fires when a user account is being completely deleted from the server */
default void userDeletedFromSite(User user) {}
/** Fires when a user account is being disabled, which prevents them from logging in but retains information associated with their account */
default void userAccountDisabled(User user) {}
/** Fires when a user account is being enabled, which allows them to log in again */
default void userAccountEnabled(User user) {}
/** Tell the user what side effects will happen if the user account is deactivated */
default List<HtmlString> previewUserAccountDeactivated(User user) { return Collections.emptyList(); }
/** Tell the user what side effects will happen if the user account is completely deleted */
default List<HtmlString> previewUserAccountDeleted(User user) { return Collections.emptyList(); }
/** Fires when a user's information has been changed, such as their first name */
default void userPropertiesUpdated(int userid) {}
@Override
default void propertyChange(PropertyChangeEvent evt) {}
}
// Thread-safe list implementation that allows iteration and modifications without external synchronization
private static final List<UserListener> _listeners = new CopyOnWriteArrayList<>();
/** Adds a listener to be notified when user account actions happen */
public static void addUserListener(UserListener listener)
{
addUserListener(listener, false);
}
/** Adds a listener with option to specify that it needs to be executed before the other listeners */
public static void addUserListener(UserListener listener, boolean meFirst)
{
if (meFirst)
_listeners.add(0, listener);
else
_listeners.add(listener);
}
private static List<UserListener> getListeners()
{
return _listeners;
}
protected static void fireAddUser(User user)
{
List<UserListener> list = getListeners();
for (UserListener userListener : list)
{
try
{
userListener.userAddedToSite(user);
}
catch (Throwable t)
{
LOG.error("fireAddPrincipalToGroup", t);
}
}
}
protected static List<Throwable> fireDeleteUser(User user)
{
List<UserListener> list = getListeners();
List<Throwable> errors = new ArrayList<>();
for (UserListener userListener : list)
{
try
{
userListener.userDeletedFromSite(user);
}
catch (Throwable t)
{
LOG.error("fireDeletePrincipalFromGroup", t);
errors.add(t);
}
}
return errors;
}
public static List<HtmlString> previewUserAccountDeleted(User user)
{
List<HtmlString> result = new ArrayList<>();
for (UserListener listener : _listeners)
{
result.addAll(listener.previewUserAccountDeleted(user));
}
return result;
}
public static List<HtmlString> previewUserAccountDeactivated(User user)
{
List<HtmlString> result = new ArrayList<>();
for (UserListener listener : _listeners)
{
result.addAll(listener.previewUserAccountDeactivated(user));
}
return result;
}
protected static List<Throwable> fireUserDisabled(User user)
{
List<UserListener> list = getListeners();
List<Throwable> errors = new ArrayList<>();
for (UserListener userListener : list)
{
try
{
userListener.userAccountDisabled(user);
}
catch (Throwable t)
{
LOG.error("fireUserDisabled", t);
errors.add(t);
}
}
return errors;
}
protected static List<Throwable> fireUserEnabled(User user)
{
List<UserListener> list = getListeners();
List<Throwable> errors = new ArrayList<>();
for (UserListener userListener : list)
{
try
{
userListener.userAccountEnabled(user);
}
catch (Throwable t)
{
LOG.error("fireUserEnabled", t);
errors.add(t);
}
}
return errors;
}
public static List<Throwable> fireUserPropertiesChanged(int userid)
{
List<UserListener> list = getListeners();
List<Throwable> errors = new ArrayList<>();
for (UserListener userListener : list)
{
try
{
userListener.userPropertiesUpdated(userid);
}
catch (Throwable t)
{
LOG.error("fireUserUpdated", t);
errors.add(t);
}
}
return errors;
}
public interface UserDetailsButtonProvider
{
void addButton(ButtonBar bb, Container c, User currentUser, User detailsUser, ActionURL returnUrl);
}
public enum UserDetailsButtonCategory
{
Authentication, // Place custom button after the built-in authentication buttons ("Reset Password", "Delete Password", "Change Password", etc.)
Account, // Place custom button after the built-in account buttons ("Change Email", "Deactivate", etc.)
Permissions // Place custom button after the built-in permissions buttons ("View Permissions", "Clone Permissions", etc.)
}
private static final Map<UserDetailsButtonCategory, List<UserDetailsButtonProvider>> USER_DETAILS_BUTTON_PROVIDERS = new EnumMap<>(UserDetailsButtonCategory.class);
static
{
// Map each button category to a list of providers. This approach should be both thread-safe and performant,
// particularly for read operations (which is what we care about).
Arrays.stream(UserDetailsButtonCategory.values())
.forEach(cat -> USER_DETAILS_BUTTON_PROVIDERS.put(cat, new CopyOnWriteArrayList<>()));
}
/**
* Register a provider that can choose to add a button to the User Details button bar.
* @param category A UserDetailsButtonCategory that determines where on the button bar the button will appear
* @param provider A UserDetailsButtonProvider that's invoked with appropriate context every time a User Details
* button bar is rendered. The provider must perform its own permissions checks on the current user
* as well as other checks to determine if showing the button is appropriate.
*/
public static void registerUserDetailsButtonProvider(UserDetailsButtonCategory category, UserDetailsButtonProvider provider)
{
USER_DETAILS_BUTTON_PROVIDERS.get(category).add(provider);
}
public static void addCustomButtons(UserDetailsButtonCategory category, ButtonBar bb, Container c, User currentUser, User detailsUser, ActionURL returnUrl)
{
USER_DETAILS_BUTTON_PROVIDERS.get(category).forEach(provider -> provider.addButton(bb, c, currentUser, detailsUser, returnUrl));
}
public static @Nullable User getUser(int userId)
{
if (userId == User.guest.getUserId())
return User.guest;
return UserCache.getUser(userId);
}
public static @Nullable User getUser(ValidEmail email)
{
return UserCache.getUser(email);
}
public static @Nullable User getUserByDisplayName(String displayName)
{
return UserCache.getUser(displayName);
}
public static List<User> getSiteAdmins()
{
return SecurityManager.getUsersWithPermissions(ContainerManager.getRoot(), Set.of(SiteAdminPermission.class));
}
public static List<User> getAppAdmins()
{
return SecurityManager.getUsersWithPermissions(ContainerManager.getRoot(), Set.of(ApplicationAdminPermission.class));
}
public static void updateRecentUser(User user)
{
synchronized(RECENT_USERS)
{
RECENT_USERS.put(user.getUserId(), HeartBeat.currentTimeMillis());
}
}
private static void removeRecentUser(User user)
{
synchronized(RECENT_USERS)
{
RECENT_USERS.remove(user.getUserId());
}
}
// Includes users who have logged in during any server session
public static int getRecentUserCount(Date since)
{
return new SqlSelector(CORE.getSchema(), new SQLFragment("SELECT COUNT(*) FROM " + CORE.getTableInfoUsersData() + " WHERE LastLogin >= ?", since)).getObject(Integer.class);
}
private static final Comparator<Pair<String, Long>> RECENT_USER_COMPARATOR = Comparator.comparing(Pair<String, Long>::getValue).thenComparing(Pair::getKey);
/** Returns all users who have logged in during this server session since the specified interval */
public static List<Pair<String, Long>> getRecentUsers(long since)
{
synchronized(RECENT_USERS)
{
long now = System.currentTimeMillis();
List<Pair<String, Long>> recentUsers = new ArrayList<>(RECENT_USERS.size());
for (int id : RECENT_USERS.keySet())
{
long lastActivity = RECENT_USERS.get(id);
if (lastActivity >= since)
{
User user = getUser(id);
String display = user != null ? user.getEmail() : "" + id;
recentUsers.add(new Pair<>(display, (now - lastActivity)/60000));
}
}
// Sort by number of minutes, then user email
recentUsers.sort(RECENT_USER_COMPARATOR);
return recentUsers;
}
}
public static Long getMinutesSinceMostRecentUserActivity()
{
synchronized(RECENT_USERS)
{
Optional<Long> mostRecent = RECENT_USERS.values().stream().min(Comparator.naturalOrder());
return mostRecent.isPresent() ?
TimeUnit.MILLISECONDS.toMinutes(HeartBeat.currentTimeMillis() - mostRecent.get().longValue()) :
null;
}
}
private enum LoggedInOrOut {in, out}
@NotNull
private static TableSelector getRecentLoginOrOuts(LoggedInOrOut inOrOut, @Nullable Date since, @Nullable TableInfo userAuditTable, @Nullable Collection<ColumnInfo> cols)
{
SimpleFilter f = new SimpleFilter(FieldKey.fromParts("Comment"), "logged " + inOrOut.toString(), CompareType.CONTAINS);
if (since != null)
{
f.addCondition(FieldKey.fromParts("Created"), since, CompareType.DATE_GTE);
}
if (null == userAuditTable)
userAuditTable = getUserAuditSchemaTableInfo();
if (null == cols)
return new TableSelector(userAuditTable, f, null);
else
return new TableSelector(userAuditTable, cols, f, null);
}
@NotNull
private static SchemaTableInfo getUserAuditSchemaTableInfo()
{
return StorageProvisioner.get().getSchemaTableInfo(AuditLogService.get().getAuditProvider(USER_AUDIT_EVENT).getDomain());
}
public static long getRecentLoginCount(Date since)
{
return getRecentLoginOrOuts(LoggedInOrOut.in, since, null, null).getRowCount();
}
@Nullable
public static Date getMostRecentLogin()
{
TableInfo uat = getUserAuditSchemaTableInfo();
FieldKey createdFk = FieldKey.fromParts("Created");
ColumnInfo createdCol = uat.getColumn(createdFk);
Aggregate maxLoginValue = new Aggregate(createdFk, Aggregate.BaseType.MAX, null, true);
TableSelector logins = getRecentLoginOrOuts(LoggedInOrOut.in, null, uat, Collections.singleton(createdCol));
Aggregate.Result result = logins.getAggregates(Collections.singletonList(maxLoginValue)).get(createdCol.getName()).get(0);
return (Date) result.getValue();
}
public static long getRecentLogOutCount(Date since)
{
return getRecentLoginOrOuts(LoggedInOrOut.out, since, null, null).getRowCount();
}
public static int getActiveDaysCount(Date since)
{
TableInfo uat = getUserAuditSchemaTableInfo();
FieldKey createdFk = FieldKey.fromParts("Created");
ColumnInfo datePartCol = new ExprColumn(uat, createdFk, new SQLFragment("CAST(Created AS DATE)"), JdbcType.DATE, uat.getColumn(createdFk));
Aggregate countDistinctDates = new Aggregate(datePartCol.getFieldKey(), Aggregate.BaseType.COUNT, null, true);
TableSelector logins = getRecentLoginOrOuts(LoggedInOrOut.in, since, uat, Collections.singleton(datePartCol));
Aggregate.Result result = logins.getAggregates(Collections.singletonList(countDistinctDates)).get(datePartCol.getName()).get(0);
return Math.toIntExact((long) result.getValue());
}
/** @return the number of unique users who have logged in since the provided date */
public static int getUniqueUsersCount(Date since)
{
TableInfo uat = getUserAuditSchemaTableInfo();
SQLFragment sql = new SQLFragment("SELECT COUNT(DISTINCT CreatedBy) FROM ");
sql.append(uat, "uat");
sql.append( " WHERE Created >= ?");
sql.add(since);
return new SqlSelector(uat.getSchema(), sql).getObject(Integer.class);
}
/** Of authenticated users, tallied when their session ends */
private static final AtomicLong _sessionCount = new AtomicLong();
/** In minutes */
private static final AtomicLong _totalSessionDuration = new AtomicLong();
private static final Set<String> _activeSessions = Collections.synchronizedSet(new HashSet<>());
public static void ensureSessionTracked(HttpSession s)
{
if (s != null)
{
Integer userId = (Integer)s.getAttribute(USER_ID_KEY);
if (null != userId && getGuestUser().getUserId() != userId)
_activeSessions.add(s.getId());
}
}
public static class SessionListener implements HttpSessionListener
{
@Override
public void sessionCreated(HttpSessionEvent event)
{
// We don't do anything with guest users, and we can rely on AuthFilter to call ensureSessionTracked().
}
@Override
public void sessionDestroyed(HttpSessionEvent event)
{
_activeSessions.remove(event.getSession().getId());
// Issue 44761 - track session duration for authenticated users
User user = SecurityManager.getSessionUser(event.getSession());
if (user != null)
{
long duration = TimeUnit.MILLISECONDS.toMinutes(event.getSession().getLastAccessedTime() - event.getSession().getCreationTime());
LOG.debug("Adding session duration to tally for " + user.getEmail() + ", " + duration + " minutes");
_sessionCount.incrementAndGet();
_totalSessionDuration.addAndGet(duration);
}
}
}
public static int getActiveUserSessionCount()
{
return _activeSessions.size();
}
public static Integer getAverageSessionDuration()
{
return _sessionCount.get() == 0 ? null : (int)(_totalSessionDuration.get() / _sessionCount.get());
}
public static User getGuestUser()
{
return User.guest;
}
// Return display name if user id != null and user exists, otherwise return null
public static String getDisplayName(Integer userId, User currentUser)
{
return getDisplayName(userId, false, currentUser);
}
// If userIdIfDeleted = true, then return "<userId>" if user doesn't exist
public static String getDisplayNameOrUserId(Integer userId, User currentUser)
{
return getDisplayName(userId, true, currentUser);
}
private static String getDisplayName(Integer userId, boolean userIdIfDeleted, User currentUser)
{
if (userId == null)
return null;
if (User.guest.getUserId() == userId)
return "Guest";
User user = getUser(userId);
if (user == null)
{
if (userIdIfDeleted)
return "<" + userId + ">";
else
return null;
}
return user.getDisplayName(currentUser);
}
public static String getEmailForId(Integer userId)
{
if (userId == null)
return null;
if (User.guest.getUserId() == userId)
return "Guest";
User user = getUser(userId);
return null != user ? user.getEmail() : null;
}
@NotNull
public static Collection<User> getActiveUsers()
{
return getUsers(false);
}
@NotNull
public static Collection<User> getUsers(boolean includeInactive)
{
return includeInactive ? UserCache.getActiveAndInactiveUsers() : UserCache.getActiveUsers() ;
}
public static List<Integer> getUserIds()
{
return UserCache.getUserIds();
}
public static Map<ValidEmail, User> getUserEmailMap()
{
return UserCache.getUserEmailMap();
}
public static void clearUserList()
{
UserCache.clear();
}
public static boolean userExists(ValidEmail email)
{
User user = getUser(email);
return (null != user);
}
public static String sanitizeEmailAddress(String email)
{
if (email == null)
return null;
int index = email.indexOf('@');
if (index != -1)
{
email = email.substring(0,index);
}
return email;
}
public static void addToUserHistory(User principal, String message)
{
User user = getGuestUser();
Container c = ContainerManager.getRoot();
try
{
ViewContext context = HttpView.currentContext();
if (context != null)
{
user = context.getUser();
c = context.getContainer();
}
}
catch (RuntimeException ignored){}
addAuditEvent(user, c, principal, message);
}
public static boolean hasUsers()
{
return getActiveUserCount() > 0;
}
public static boolean hasNoRealUsers()
{
return 0 == getActiveRealUserCount();
}
public static int getUserCount(Date registeredBefore)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("Created"), registeredBefore, CompareType.LTE);
return (int)new TableSelector(CORE.getTableInfoUsersData(), filter, null).getRowCount();
}
/** @return the number of user accounts, not including deactivated users */
public static int getActiveUserCount()
{
return UserCache.getActiveUserCount();
}
public static int getActiveRealUserCount()
{
return UserCache.getActiveRealUserCount();
}
/** Active users who are marked as "system" users, i.e., excluded from user limits **/
public static int getSystemUserCount()
{
return UserCache.getSystemUserCount();
}
public static String validGroupName(String name, @NotNull PrincipalType type)
{
if (null == name || name.isEmpty())
return "Name cannot be empty";
if (!name.trim().equals(name))
return "Name should not start or end with whitespace";
switch (type)
{
// USER
case USER -> throw new IllegalArgumentException("User names are not allowed");
// GROUP (regular project or global)
case ROLE, GROUP ->
{
// see renameGroup.jsp if you change this
if (!StringUtils.containsNone(name, GROUP_NAME_CHAR_EXCLUSION_LIST))
return "Group name should not contain punctuation.";
if (name.length() > VALID_GROUP_NAME_LENGTH) // issue 14147
return "Name value is too long, maximum length is " + VALID_GROUP_NAME_LENGTH + " characters, but supplied value was " + name.length() + " characters.";
}
// MODULE MANAGED
case MODULE ->
{
}
// no validation, HOWEVER must be UNIQUE
// recommended start with @ or look like a GUID
// must contain punctuation, but not look like email
default -> throw new IllegalArgumentException("Unknown principal type: '" + type + "'");
}
return null;
}
/** Record that a user logged in */
public static void updateLogin(User user)
{
SQLFragment sql = new SQLFragment("UPDATE " + CORE.getTableInfoUsersData() + " SET LastLogin = ? WHERE UserId = ?", new Date(), user.getUserId());
new SqlExecutor(CORE.getSchema()).execute(sql);
}
/** Clear the ExpirationDate field for the given user */
public static void clearExpirationDate(User adminUser, User expiringUser)
{
Table.update(adminUser, CORE.getTableInfoUsersData(), new HashMap<>(){{put("ExpirationDate", null);}}, expiringUser.getUserId());
clearUserList();
}
/**
* Updates a user's basic account information
* @param currentUser user to use to determine the display name for the user to be updated
* @param toUpdate the user object that is being updated
*/
public static void updateUser(@Nullable User currentUser, User toUpdate)
{
Map<String, Object> typedValues = new HashMap<>();
typedValues.put("phone", PageFlowUtil.formatPhoneNo(toUpdate.getPhone()));
typedValues.put("mobile", PageFlowUtil.formatPhoneNo(toUpdate.getMobile()));
typedValues.put("pager", PageFlowUtil.formatPhoneNo(toUpdate.getPager()));
typedValues.put("im", toUpdate.getIM());
if (currentUser != null && !currentUser.isGuest())
typedValues.put("displayName", toUpdate.getDisplayName(currentUser));
typedValues.put("firstName", toUpdate.getFirstName());
typedValues.put("lastName", toUpdate.getLastName());
typedValues.put("description", toUpdate.getDescription());
Table.update(currentUser, CORE.getTableInfoUsers(), typedValues, toUpdate.getUserId());
clearUserList();
addToUserHistory(toUpdate, "Contact information for " + toUpdate.getEmail() + " was updated");
}
public static void requestEmailChange(User userToChange, ValidEmail requestedEmail, String verificationToken, User currentUser) throws UserManagementException
{
if (SecurityManager.loginExists(userToChange.getEmail()))
{
DbScope scope = CORE.getSchema().getScope();
try (Transaction transaction = scope.ensureTransaction())
{
Instant timeoutDate = Instant.now().plus(VERIFICATION_EMAIL_TIMEOUT, ChronoUnit.MINUTES);
SqlExecutor executor = new SqlExecutor(CORE.getSchema());
int rows = executor.execute("UPDATE " + CORE.getTableInfoLogins() + " SET RequestedEmail = ?, Verification = ?, VerificationTimeout = ? WHERE Email = ?",
requestedEmail.getEmailAddress(), verificationToken, Date.from(timeoutDate), userToChange.getEmail());
if (1 != rows)
throw new UserManagementException(requestedEmail, "Unexpected number of rows returned when setting verification: " + rows);
addToUserHistory(userToChange, currentUser + " requested email address change from " + userToChange.getEmail() + " to " + requestedEmail +
" with token '" + verificationToken + "' and timeout date '" + Date.from(timeoutDate) + "'.");
transaction.commit();
}
}
}
public static void changeEmail(User currentUser, User userToChange, boolean isAdmin, String newEmail, String verificationToken)
throws UserManagementException, ValidEmail.InvalidEmailException
{
// make sure these emails are valid, and also have been processed (like changing to lowercase)
String oldEmail = userToChange.getEmail();
newEmail = new ValidEmail(newEmail).getEmailAddress();
DbScope scope = CORE.getSchema().getScope();
try (Transaction transaction = scope.ensureTransaction())
{
if (!isAdmin)
{
if (!getVerifyEmail(oldEmail).isVerified(verificationToken)) // shouldn't happen! should be testing this earlier too
{
throw new UserManagementException(oldEmail, "Verification token '" + verificationToken + "' is incorrect for email change for user " + oldEmail);
}
}
SqlExecutor executor = new SqlExecutor(CORE.getSchema());
int rows = executor.execute("UPDATE " + CORE.getTableInfoPrincipals() + " SET Name = ? WHERE UserId = ?", newEmail, userToChange.getUserId());
if (1 != rows)
throw new UserManagementException(oldEmail, "Unexpected number of rows returned when setting new name: " + rows);
executor.execute("UPDATE " + CORE.getTableInfoLogins() + " SET Email = ? WHERE Email = ?", newEmail, oldEmail); // won't update if non-LabKey-managed, because there is no data here
if (isAdmin)
{
addToUserHistory(userToChange, "Admin " + currentUser + " changed an email address from " + oldEmail + " to " + newEmail + ".");
}
else
{
addToUserHistory(userToChange, currentUser + " changed their email address from " + oldEmail + " to " + newEmail + " with token '" + verificationToken + "'.");
}
if (userToChange.getDisplayName(userToChange).equals(oldEmail))
{
rows = executor.execute("UPDATE " + CORE.getTableInfoUsersData() + " SET DisplayName = ? WHERE UserId = ?", newEmail, userToChange.getUserId());
if (1 != rows)
throw new UserManagementException(oldEmail, "Unexpected number of rows returned when setting new display name: " + rows);
}
ValidEmail validNewEmail = new ValidEmail(newEmail);
if (SecurityManager.loginExists(validNewEmail))
{
SecurityManager.setVerification(validNewEmail, null); // so we don't let user use this link again
}
transaction.commit();
}
clearUserList();
}
public static void auditEmailTimeout(int userId, String oldEmail, String newEmail, String verificationToken, User currentUser)
{
addToUserHistory(getUser(userId), currentUser + " tried to change an email address from " + oldEmail + " to " + newEmail +
" with token '" + verificationToken + "', but the verification link was timed out.");
}
public static void auditBadVerificationToken(int userId, String oldEmail, String newEmail, String verificationToken, User currentUser)
{
addToUserHistory(getUser(userId), currentUser + " tried to change an email address from " + oldEmail + " to " + newEmail +
" with token '" + verificationToken + "', but the verification token for that email address was not correct.");
}
public static VerifyEmail getVerifyEmail(String email)
{
SqlSelector sqlSelector = new SqlSelector(CORE.getSchema(), "SELECT Email, RequestedEmail, Verification, VerificationTimeout FROM " + CORE.getTableInfoLogins()
+ " WHERE Email = ?", email);
return sqlSelector.getObject(VerifyEmail.class);
}
public static class VerifyEmail
{
private String _email;
private String _requestedEmail;
private String _verification;
private Date _verificationTimeout;
public String getEmail()
{
return _email;
}
@SuppressWarnings("unused")
public void setEmail(String email)
{
_email = email;
}
public String getRequestedEmail()
{
return _requestedEmail;
}
@SuppressWarnings("unused")
public void setRequestedEmail(String requestedEmail)
{
_requestedEmail = requestedEmail;
}
public String getVerification()
{
return _verification;
}
@SuppressWarnings("unused")
public void setVerification(String verification)
{
_verification = verification;
}
public Date getVerificationTimeout()
{
return _verificationTimeout;
}
@SuppressWarnings("unused")
public void setVerificationTimeout(Date verificationTimeout)
{
_verificationTimeout = verificationTimeout;
}
public boolean isVerified(String userProvidedToken)
{
return userProvidedToken != null && userProvidedToken.equals(_verification);
}
}
public static void deleteUser(int userId) throws UserManagementException
{
User user = getUser(userId);
if (null == user)
return;
removeRecentUser(user);
List<Throwable> errors = fireDeleteUser(user);
if (!errors.isEmpty())
{
Throwable first = errors.get(0);
if (first instanceof RuntimeException)
throw (RuntimeException)first;
else
throw new RuntimeException(first);
}
try (Transaction transaction = CORE.getScope().ensureTransaction())
{
boolean needToEnsureRootAdmins = SecurityManager.isRootAdmin(user);
SqlExecutor executor = new SqlExecutor(CORE.getSchema());
executor.execute("DELETE FROM " + CORE.getTableInfoRoleAssignments() + " WHERE UserId=?", userId);
executor.execute("DELETE FROM " + CORE.getTableInfoMembers() + " WHERE UserId=?", userId);
addToUserHistory(user, user.getEmail() + " was deleted from the system");
executor.execute("DELETE FROM " + CORE.getTableInfoUsersData() + " WHERE UserId=?", userId);
executor.execute("DELETE FROM " + CORE.getTableInfoLogins() + " WHERE Email=?", user.getEmail());
executor.execute("DELETE FROM " + CORE.getTableInfoPrincipals() + " WHERE UserId=?", userId);
executor.execute("DELETE FROM " + CORE.getTableAPIKeys() + " WHERE CreatedBy=?", userId);
OntologyManager.deleteOntologyObject(user.getEntityId(), ContainerManager.getSharedContainer(), true);
// Clear user list immediately (before the last root admin check) and again after commit/rollback
transaction.addCommitTask(UserManager::clearUserList, CommitTaskOption.IMMEDIATE, CommitTaskOption.POSTCOMMIT, CommitTaskOption.POSTROLLBACK);
if (needToEnsureRootAdmins)
SecurityManager.ensureAtLeastOneRootAdminExists();
transaction.commit();
}
catch (Exception e)
{
LOG.error("deleteUser: " + e);
throw new UserManagementException(user.getEmail(), e);
}
//TODO: Delete User files
}
public static void setUserActive(User currentUser, int userIdToAdjust, boolean active) throws UserManagementException
{
setUserActive(currentUser, getUser(userIdToAdjust), active);
}
public static void setUserActive(User currentUser, User userToAdjust, boolean active) throws UserManagementException
{
setUserActive(currentUser, userToAdjust, active, "");
}
public static void setUserActive(User currentUser, User userToAdjust, boolean active, String extendedMessage) throws UserManagementException
{
if (null == userToAdjust)
return;
//no-op if active state is not actually changed
if (userToAdjust.isActive() == active)
return;
if (active && LimitActiveUsersService.get().isUserLimitReached())
throw new UserManagementException(userToAdjust.getEmail(), "User limit has been reached so no more users can be reactivated on this deployment.");
Integer userId = userToAdjust.getUserId();
List<Throwable> errors = active ? fireUserEnabled(userToAdjust) : fireUserDisabled(userToAdjust);
if (!errors.isEmpty())
{
Throwable first = errors.get(0);
if (first instanceof RuntimeException)
throw (RuntimeException)first;
else
throw new RuntimeException(first);
}
try (Transaction transaction = CoreSchema.getInstance().getScope().ensureTransaction())