From ba8e2fef6b0a47727f03d58f4fe2809d6e65c017 Mon Sep 17 00:00:00 2001 From: Michal Hajas Date: Fri, 4 Dec 2020 08:33:42 +0100 Subject: [PATCH] KEYCLOAK-15524 Cleanup user related interfaces --- .../permission/UMAPolicyProviderFactory.java | 2 +- .../user/UserPolicyProviderFactory.java | 6 +- .../kerberos/KerberosFederationProvider.java | 12 +- .../storage/ldap/LDAPStorageProvider.java | 71 ++- .../ldap/LDAPStorageProviderFactory.java | 4 +- .../UserAttributeLDAPStorageMapper.java | 4 +- .../sssd/SSSDFederationProvider.java | 10 +- .../models/cache/infinispan/UserAdapter.java | 2 +- .../cache/infinispan/UserCacheSession.java | 111 +++-- .../AuthenticationSessionAdapter.java | 2 +- .../infinispan/UserSessionAdapter.java | 2 +- .../keycloak/models/jpa/JpaRealmProvider.java | 47 +- .../keycloak/models/jpa/JpaUserProvider.java | 77 +--- .../keycloak/models/jpa/PaginationUtils.java | 43 ++ .../MapAuthenticationSessionAdapter.java | 2 +- .../models/map/client/MapClientProvider.java | 20 +- .../models/map/group/MapGroupProvider.java | 40 +- .../models/map/role/MapRoleProvider.java | 38 +- .../models/map/user/MapUserProvider.java | 97 ++-- ...bstractUserEntityCredentialsOrderTest.java | 0 .../QuarkusJpaConnectionProviderFactory.java | 3 +- .../policy/evaluation/DefaultEvaluation.java | 6 +- .../session/PersistentUserSessionAdapter.java | 2 +- .../models/utils/KeycloakModelUtils.java | 4 +- .../models/utils/ModelToRepresentation.java | 6 +- .../models/utils/RepresentationToModel.java | 6 +- .../java/org/keycloak/utils/StreamsUtil.java | 31 ++ .../org/keycloak/models/GroupProvider.java | 4 +- .../org/keycloak/models/UserProvider.java | 360 +++++++++++---- .../keycloak/storage/UserStorageProvider.java | 13 + .../storage/user/ImportSynchronization.java | 5 + .../storage/user/ImportedUserValidation.java | 8 +- .../storage/user/UserBulkUpdateProvider.java | 3 + .../storage/user/UserLookupProvider.java | 82 +++- .../storage/user/UserQueryProvider.java | 419 +++++++++++------- .../user/UserRegistrationProvider.java | 17 +- .../broker/AbstractIdpAuthenticator.java | 2 +- .../IdpCreateUserIfUniqueAuthenticator.java | 4 +- .../browser/WebAuthnAuthenticator.java | 2 +- .../resetcred/ResetCredentialChooseUser.java | 6 +- .../x509/UserIdentityToModelMapper.java | 2 +- .../admin/PolicyEvaluationService.java | 4 +- .../admin/ResourceSetService.java | 2 +- .../PolicyEvaluationResponseBuilder.java | 4 +- .../permission/PermissionTicketService.java | 8 +- .../oidc/AbstractOAuth2IdentityProvider.java | 2 +- .../broker/oidc/OIDCIdentityProvider.java | 2 +- .../email/EmailEventListenerProvider.java | 2 +- .../exportimport/util/ExportUtils.java | 2 +- .../model/AccountFederatedIdentityBean.java | 2 +- .../freemarker/model/AuthorizationBean.java | 4 +- .../login/freemarker/LoginFormsUtil.java | 4 +- .../partialimport/UsersPartialImport.java | 12 +- .../keycloak/protocol/oidc/TokenManager.java | 4 +- .../oidc/endpoints/TokenEndpoint.java | 10 +- .../authenticator/HttpBasicAuthenticator.java | 2 +- .../DynamicClientRegisterContext.java | 2 +- .../DynamicClientUpdateContext.java | 2 +- .../ClientUpdateSourceGroupsCondition.java | 2 +- .../ClientUpdateSourceRolesCondition.java | 2 +- .../ClientRegistrationAuth.java | 2 +- .../managers/DefaultBruteForceProtector.java | 4 +- .../resources/IdentityBrokerService.java | 12 +- .../resources/KeycloakApplication.java | 3 +- .../resources/LoginActionsServiceChecks.java | 2 +- .../resources/account/AccountFormService.java | 12 +- .../account/LinkedAccountsResource.java | 6 +- .../resources/AbstractResourceService.java | 2 +- .../account/resources/ResourceService.java | 4 +- .../admin/AttackDetectionResource.java | 4 +- .../admin/ClientScopeEvaluateResource.java | 2 +- .../admin/IdentityProviderResource.java | 2 +- .../resources/admin/UserResource.java | 4 +- .../resources/admin/UsersResource.java | 20 +- .../twitter/TwitterIdentityProvider.java | 2 +- .../keycloak/storage/UserStorageManager.java | 110 ++--- .../LegacyUserProfileProvider.java | 2 +- .../validation/StaticValidators.java | 8 +- .../ExpectedParamAuthenticator.java | 2 +- .../BackwardsCompatibilityUserStorage.java | 2 +- .../DummyUserFederationProvider.java | 11 +- .../FailableHardcodedStorageProvider.java | 34 +- ...ssThroughFederatedUserStorageProvider.java | 8 +- .../testsuite/federation/UserMapStorage.java | 60 +-- .../federation/UserPropertyFileStorage.java | 88 ++-- ...yncDummyUserFederationProviderFactory.java | 2 +- .../rest/TestingResourceProvider.java | 6 +- .../testsuite/runonserver/RunHelpers.java | 2 +- .../account/AccountFormServiceTest.java | 2 +- .../admin/FineGrainAdminUnitTest.java | 19 +- .../testsuite/admin/ImpersonationTest.java | 2 +- .../testsuite/authz/PolicyEvaluationTest.java | 2 +- .../authz/UmaRepresentationTest.java | 5 +- .../testsuite/broker/AccountLinkTest.java | 6 +- .../broker/BrokerRunOnServerUtil.java | 6 +- .../keycloak/testsuite/cli/KcinitTest.java | 19 +- .../ldap/LDAPBinaryAttributesTest.java | 2 +- .../ldap/LDAPGroupMapperSyncTest.java | 3 +- .../federation/ldap/LDAPGroupMapperTest.java | 36 +- .../ldap/LDAPHardcodedAttributeTest.java | 2 +- .../federation/ldap/LDAPMSADFullNameTest.java | 18 +- .../federation/ldap/LDAPMSADMapperTest.java | 2 +- .../ldap/LDAPMultipleAttributesTest.java | 10 +- .../federation/ldap/LDAPNoCacheTest.java | 8 +- .../federation/ldap/LDAPNoMSADTest.java | 2 +- .../ldap/LDAPProvidersFullNameMapperTest.java | 10 +- .../ldap/LDAPProvidersIntegrationTest.java | 94 ++-- .../federation/ldap/LDAPRoleMapperTest.java | 16 +- .../federation/ldap/LDAPRoleMappingsTest.java | 22 +- .../federation/ldap/LDAPSpecialCharsTest.java | 2 +- .../federation/ldap/LDAPSyncTest.java | 6 +- .../federation/ldap/LDAPTestAsserts.java | 2 +- .../ldap/LdapUsernameAttributeTest.java | 24 +- .../LDAPMultipleAttributesNoImportTest.java | 4 +- .../LDAPProvidersIntegrationNoImportTest.java | 22 +- .../LDAPRoleMappingsNoImportTest.java | 28 +- ...BackwardsCompatibilityUserStorageTest.java | 3 +- .../storage/UserStorageFailureTest.java | 38 +- .../federation/storage/UserStorageTest.java | 72 +-- .../testsuite/forms/PasswordHashingTest.java | 2 +- .../ResetCredentialsAlternativeFlowsTest.java | 2 +- .../login/LoginTimeoutValidationTest.java | 4 +- .../AuthenticationSessionProviderTest.java | 10 +- .../keycloak/testsuite/model/CacheTest.java | 4 +- .../model/CompositeRolesModelTest.java | 12 +- .../model/ConcurrentTransactionsTest.java | 8 +- .../testsuite/model/CredentialModelTest.java | 14 +- .../testsuite/model/MultipleRealmsTest.java | 20 +- .../testsuite/model/OwnerReplacementTest.java | 2 +- .../testsuite/model/UserConsentModelTest.java | 38 +- .../UserConsentWithUserStorageModelTest.java | 38 +- .../testsuite/model/UserModelTest.java | 66 +-- .../model/UserSessionInitializerTest.java | 18 +- .../UserSessionPersisterProviderTest.java | 42 +- .../model/UserSessionProviderOfflineTest.java | 34 +- .../model/UserSessionProviderTest.java | 76 ++-- .../oauth/ClientTokenExchangeTest.java | 2 +- .../testsuite/oauth/RefreshTokenTest.java | 2 +- .../session/SessionTimeoutValidationTest.java | 4 +- testsuite/model/pom.xml | 14 + .../testsuite/model/UserModelTest.java | 26 +- .../util/cli/AbstractSessionCacheCommand.java | 2 +- .../util/cli/PersistSessionsCommand.java | 2 +- .../testsuite/util/cli/TestCacheUtils.java | 10 +- .../testsuite/util/cli/UserCommands.java | 4 +- 145 files changed, 1625 insertions(+), 1381 deletions(-) create mode 100644 model/jpa/src/main/java/org/keycloak/models/jpa/PaginationUtils.java rename model/map/src/{main => }/test/java/org/keycloak/models/map/user/AbstractUserEntityCredentialsOrderTest.java (100%) diff --git a/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/permission/UMAPolicyProviderFactory.java b/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/permission/UMAPolicyProviderFactory.java index 4fe6e890aa..51107ae8a2 100644 --- a/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/permission/UMAPolicyProviderFactory.java +++ b/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/permission/UMAPolicyProviderFactory.java @@ -349,7 +349,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory userProvider.getUserById(id, realm).getUsername()).collect(Collectors.toList()))); + config.put("users", JsonSerialization.writeValueAsString(userRep.getUsers().stream().map(id -> userProvider.getUserById(realm, id).getUsername()).collect(Collectors.toList()))); } catch (IOException cause) { throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause); } @@ -142,12 +142,12 @@ public class UserPolicyProviderFactory implements PolicyProviderFactoryMarek Posolda */ public class KerberosFederationProvider implements UserStorageProvider, - UserLookupProvider, + UserLookupProvider.Streams, CredentialInputValidator, CredentialInputUpdater.Streams, CredentialAuthentication, @@ -83,7 +83,7 @@ public class KerberosFederationProvider implements UserStorageProvider, } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { KerberosUsernamePasswordAuthenticator authenticator = factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig); if (authenticator.isUserAvailable(username)) { // Case when method was called with username including kerberos realm like john@REALM.ORG . Authenticator already checked that kerberos realm was correct @@ -98,12 +98,12 @@ public class KerberosFederationProvider implements UserStorageProvider, } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { return null; } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { return null; } @@ -234,9 +234,9 @@ public class KerberosFederationProvider implements UserStorageProvider, * @return user if found or successfully created. Null if user with same username already exists, but is not linked to this provider */ protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) { - UserModel user = session.userLocalStorage().getUserByUsername(username, realm); + UserModel user = session.userLocalStorage().getUserByUsername(realm, username); if (user != null) { - user = session.users().getUserById(user.getId(), realm); // make sure we get a cached instance + user = session.users().getUserById(realm, user.getId()); // make sure we get a cached instance logger.debug("Kerberos authenticated user " + username + " found in Keycloak storage"); if (!model.getId().equals(user.getFederationLink())) { diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java index fff1ce1aa1..89804f9554 100755 --- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java +++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java @@ -79,6 +79,8 @@ import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserQueryProvider; import org.keycloak.storage.user.UserRegistrationProvider; +import static org.keycloak.utils.StreamsUtil.paginatedStream; + /** * @author Marek Posolda * @author Bill Burke @@ -88,11 +90,12 @@ public class LDAPStorageProvider implements UserStorageProvider, CredentialInputValidator, CredentialInputUpdater.Streams, CredentialAuthentication, - UserLookupProvider, + UserLookupProvider.Streams, UserRegistrationProvider, UserQueryProvider.Streams, ImportedUserValidation { private static final Logger logger = Logger.getLogger(LDAPStorageProvider.class); + private static final int DEFAULT_MAX_RESULTS = Integer.MAX_VALUE >> 1; protected LDAPStorageProviderFactory factory; protected KeycloakSession session; @@ -176,7 +179,7 @@ public class LDAPStorageProvider implements UserStorageProvider, // We need to avoid having CachedUserModel as cache is upper-layer then LDAP. Hence having CachedUserModel here may cause StackOverflowError if (local instanceof CachedUserModel) { - local = session.userStorageManager().getUserById(local.getId(), realm); + local = session.userStorageManager().getUserById(realm, local.getId()); existing = userManager.getManagedProxiedUser(local.getId()); if (existing != null) { @@ -245,7 +248,7 @@ public class LDAPStorageProvider implements UserStorageProvider, } @Override - public Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { try (LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm)) { LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder(); @@ -256,7 +259,7 @@ public class LDAPStorageProvider implements UserStorageProvider, return ldapObjects.stream().map(ldapUser -> { String ldapUsername = LDAPUtils.getUsername(ldapUser, this.ldapIdentityStore.getConfig()); - UserModel localUser = session.userLocalStorage().getUserByUsername(ldapUsername, realm); + UserModel localUser = session.userLocalStorage().getUserByUsername(realm, ldapUsername); if (localUser == null) { return importUserFromLDAP(session, realm, ldapUser); } else { @@ -323,12 +326,12 @@ public class LDAPStorageProvider implements UserStorageProvider, } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { UserModel alreadyLoadedInSession = userManager.getManagedProxiedUser(id); if (alreadyLoadedInSession != null) return alreadyLoadedInSession; StorageId storageId = new StorageId(id); - return getUserByUsername(storageId.getExternalId(), realm); + return getUserByUsername(realm, storageId.getExternalId()); } @Override @@ -342,29 +345,20 @@ public class LDAPStorageProvider implements UserStorageProvider, } @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { return Stream.empty(); } @Override - public Stream searchForUserStream(String search, RealmModel realm) { - return searchForUserStream(search, realm, 0, Integer.MAX_VALUE - 1); - } - - @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { Map attributes = new HashMap(); attributes.put(UserModel.SEARCH,search); - return searchForUserStream(attributes, realm, firstResult, maxResults); + return searchForUserStream(realm, attributes, firstResult, maxResults); } - @Override - public Stream searchForUserStream(Map params, RealmModel realm) { - return searchForUserStream(params, realm, 0, Integer.MAX_VALUE - 1); - } @Override - public Stream searchForUserStream(Map params, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, Map params, Integer firstResult, Integer maxResults) { String search = params.get(UserModel.SEARCH); if(search!=null) { int spaceIndex = search.lastIndexOf(' '); @@ -385,41 +379,34 @@ public class LDAPStorageProvider implements UserStorageProvider, Stream stream = searchLDAP(realm, params).stream() .filter(ldapObject -> { String ldapUsername = LDAPUtils.getUsername(ldapObject, this.ldapIdentityStore.getConfig()); - return (session.userLocalStorage().getUserByUsername(ldapUsername, realm) == null); + return (session.userLocalStorage().getUserByUsername(realm, ldapUsername) == null); }); - if (firstResult > 0) - stream = stream.skip(firstResult); - if (maxResults >= 0) - stream = stream.limit(maxResults); - return stream.map(ldapObject -> importUserFromLDAP(session, realm, ldapObject)); - } - @Override - public Stream getGroupMembersStream(RealmModel realm, GroupModel group) { - return getGroupMembersStream(realm, group, 0, Integer.MAX_VALUE - 1); + return paginatedStream(stream, firstResult, maxResults).map(ldapObject -> importUserFromLDAP(session, realm, ldapObject)); } @Override public Stream getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { + int first = firstResult == null ? 0 : firstResult; + int max = maxResults == null ? DEFAULT_MAX_RESULTS : maxResults; + return realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName()) .sorted(ldapMappersComparator.sortAsc()) .map(mapperModel -> - mapperManager.getMapper(mapperModel).getGroupMembers(realm, group, firstResult, maxResults)) + mapperManager.getMapper(mapperModel).getGroupMembers(realm, group, first, max)) .filter(((Predicate) List::isEmpty).negate()) .map(List::stream) .findFirst().orElse(Stream.empty()); } - @Override - public Stream getRoleMembersStream(RealmModel realm, RoleModel role) { - return getRoleMembersStream(realm, role, 0, Integer.MAX_VALUE - 1); - } - @Override public Stream getRoleMembersStream(RealmModel realm, RoleModel role, Integer firstResult, Integer maxResults) { + int first = firstResult == null ? 0 : firstResult; + int max = maxResults == null ? DEFAULT_MAX_RESULTS : maxResults; + return realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName()) .sorted(ldapMappersComparator.sortAsc()) - .map(mapperModel -> mapperManager.getMapper(mapperModel).getRoleMembers(realm, role, firstResult, maxResults)) + .map(mapperModel -> mapperManager.getMapper(mapperModel).getRoleMembers(realm, role, first, max)) .filter(((Predicate) List::isEmpty).negate()) .map(List::stream) .findFirst().orElse(Stream.empty()); @@ -428,7 +415,7 @@ public class LDAPStorageProvider implements UserStorageProvider, public List loadUsersByUsernames(List usernames, RealmModel realm) { List result = new ArrayList<>(); for (String username : usernames) { - UserModel kcUser = session.users().getUserByUsername(username, realm); + UserModel kcUser = session.users().getUserByUsername(realm, username); if (kcUser == null) { logger.warnf("User '%s' referenced by membership wasn't found in LDAP", username); } else if (model.isImportEnabled() && !model.getId().equals(kcUser.getFederationLink())) { @@ -514,7 +501,7 @@ public class LDAPStorageProvider implements UserStorageProvider, } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { LDAPObject ldapUser = loadLDAPUserByUsername(realm, username); if (ldapUser == null) { return null; @@ -575,7 +562,7 @@ public class LDAPStorageProvider implements UserStorageProvider, @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { LDAPObject ldapUser = queryByEmail(realm, email); if (ldapUser == null) { return null; @@ -583,7 +570,7 @@ public class LDAPStorageProvider implements UserStorageProvider, // Check here if user already exists String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig()); - UserModel user = session.userLocalStorage().getUserByUsername(ldapUsername, realm); + UserModel user = session.userLocalStorage().getUserByUsername(realm, ldapUsername); if (user != null) { LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig()); @@ -771,7 +758,7 @@ public class LDAPStorageProvider implements UserStorageProvider, * @return finded or newly created user */ protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) { - UserModel user = session.userLocalStorage().getUserByUsername(username, realm); + UserModel user = session.userLocalStorage().getUserByUsername(realm, username); if (user != null) { logger.debugf("Kerberos authenticated user [%s] found in Keycloak storage", username); if (!model.getId().equals(user.getFederationLink())) { @@ -796,7 +783,7 @@ public class LDAPStorageProvider implements UserStorageProvider, // Creating user to local storage logger.debugf("Kerberos authenticated user [%s] not in Keycloak storage. Creating him", username); - return getUserByUsername(username, realm); + return getUserByUsername(realm, username); } public LDAPObject loadLDAPUserByUsername(RealmModel realm, String username) { diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java index 66aef7024c..76ac3ee750 100755 --- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java +++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java @@ -593,7 +593,7 @@ public class LDAPStorageProviderFactory implements UserStorageProviderFactory groupIds) { return getDelegate().getUsersCount(realm, groupIds); } @Override - public int getUsersCount(String search, RealmModel realm) { - return getDelegate().getUsersCount(search, realm); + public int getUsersCount(RealmModel realm, String search) { + return getDelegate().getUsersCount(realm, search); } @Override - public int getUsersCount(String search, RealmModel realm, Set groupIds) { - return getDelegate().getUsersCount(search, realm, groupIds); + public int getUsersCount(RealmModel realm, String search, Set groupIds) { + return getDelegate().getUsersCount(realm, search, groupIds); } @Override - public int getUsersCount(Map params, RealmModel realm) { - return getDelegate().getUsersCount(params, realm); + public int getUsersCount(RealmModel realm, Map params) { + return getDelegate().getUsersCount(realm, params); } @Override - public int getUsersCount(Map params, RealmModel realm, Set groupIds) { - return getDelegate().getUsersCount(params, realm, groupIds); + public int getUsersCount(RealmModel realm, Map params, Set groupIds) { + return getDelegate().getUsersCount(realm, params, groupIds); } @Override @@ -586,49 +581,49 @@ public class UserCacheSession implements UserCache.Streams { } @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { return getUsersStream(realm, firstResult, maxResults, false); } @Override - public Stream searchForUserStream(String search, RealmModel realm) { - return getDelegate().searchForUserStream(search, realm); + public Stream searchForUserStream(RealmModel realm, String search) { + return getDelegate().searchForUserStream(realm, search); } @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { - return getDelegate().searchForUserStream(search, realm, firstResult, maxResults); + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { + return getDelegate().searchForUserStream(realm, search, firstResult, maxResults); } @Override - public Stream searchForUserStream(Map attributes, RealmModel realm) { - return getDelegate().searchForUserStream(attributes, realm); + public Stream searchForUserStream(RealmModel realm, Map attributes) { + return getDelegate().searchForUserStream(realm, attributes); } @Override - public Stream searchForUserStream(Map attributes, RealmModel realm, Integer firstResult, Integer maxResults) { - return getDelegate().searchForUserStream(attributes, realm, firstResult, maxResults); + public Stream searchForUserStream(RealmModel realm, Map attributes, Integer firstResult, Integer maxResults) { + return getDelegate().searchForUserStream(realm, attributes, firstResult, maxResults); } @Override - public Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { - return getDelegate().searchForUserByUserAttributeStream(attrName, attrValue, realm); + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { + return getDelegate().searchForUserByUserAttributeStream(realm, attrName, attrValue); } @Override - public Stream getFederatedIdentitiesStream(UserModel user, RealmModel realm) { + public Stream getFederatedIdentitiesStream(RealmModel realm, UserModel user) { logger.tracev("getFederatedIdentities: {0}", user.getUsername()); String cacheKey = getFederatedIdentityLinksCacheKey(user.getId()); if (realmInvalidations.contains(realm.getId()) || invalidations.contains(user.getId()) || invalidations.contains(cacheKey)) { - return getDelegate().getFederatedIdentitiesStream(user, realm); + return getDelegate().getFederatedIdentitiesStream(realm, user); } CachedFederatedIdentityLinks cachedLinks = cache.get(cacheKey, CachedFederatedIdentityLinks.class); if (cachedLinks == null) { Long loaded = cache.getCurrentRevision(cacheKey); - Set federatedIdentities = getDelegate().getFederatedIdentitiesStream(user, realm) + Set federatedIdentities = getDelegate().getFederatedIdentitiesStream(realm, user) .collect(Collectors.toSet()); cachedLinks = new CachedFederatedIdentityLinks(loaded, cacheKey, realm, federatedIdentities); cache.addRevisioned(cachedLinks, startupRevision); @@ -639,15 +634,15 @@ public class UserCacheSession implements UserCache.Streams { } @Override - public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) { + public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { logger.tracev("getFederatedIdentity: {0} {1}", user.getUsername(), socialProvider); String cacheKey = getFederatedIdentityLinksCacheKey(user.getId()); if (realmInvalidations.contains(realm.getId()) || invalidations.contains(user.getId()) || invalidations.contains(cacheKey)) { - return getDelegate().getFederatedIdentity(user, socialProvider, realm); + return getDelegate().getFederatedIdentity(realm, user, socialProvider); } - return getFederatedIdentitiesStream(user, realm) + return getFederatedIdentitiesStream(realm, user) .filter(socialLink -> Objects.equals(socialLink.getIdentityProvider(), socialProvider)) .findFirst().orElse(null); } @@ -748,7 +743,7 @@ public class UserCacheSession implements UserCache.Streams { @Override public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) { if (!isRegisteredForInvalidation(realm, user.getId())) { - UserModel foundUser = getUserById(user.getId(), realm); + UserModel foundUser = getUserById(realm, user.getId()); if (foundUser instanceof UserAdapter) { ((UserAdapter) foundUser).invalidate(); } @@ -764,7 +759,7 @@ public class UserCacheSession implements UserCache.Streams { return getDelegate().getNotBeforeOfUser(realm, user); } - UserModel foundUser = getUserById(user.getId(), realm); + UserModel foundUser = getUserById(realm, user.getId()); if (foundUser instanceof UserAdapter) { return ((UserAdapter) foundUser).cached.getNotBefore(); } else { @@ -793,7 +788,7 @@ public class UserCacheSession implements UserCache.Streams { // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user protected void fullyInvalidateUser(RealmModel realm, UserModel user) { Stream federatedIdentities = realm.isIdentityFederationEnabled() ? - getFederatedIdentitiesStream(user, realm) : Stream.empty(); + getFederatedIdentitiesStream(realm, user) : Stream.empty(); UserFullInvalidationEvent event = UserFullInvalidationEvent.create(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), realm.isIdentityFederationEnabled(), federatedIdentities); @@ -827,7 +822,7 @@ public class UserCacheSession implements UserCache.Streams { @Override public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { // Needs to invalidate both directions - FederatedIdentityModel socialLink = getFederatedIdentity(user, socialProvider, realm); + FederatedIdentityModel socialLink = getFederatedIdentity(realm, user, socialProvider); UserFederationLinkRemovedEvent event = UserFederationLinkRemovedEvent.create(user.getId(), realm.getId(), socialLink); cache.federatedIdentityLinkRemovedInvalidation(user.getId(), realm.getId(), event.getIdentityProviderId(), event.getSocialUserId(), invalidations); diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/AuthenticationSessionAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/AuthenticationSessionAdapter.java index 831bd324bd..1853ad1790 100644 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/AuthenticationSessionAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/AuthenticationSessionAdapter.java @@ -282,7 +282,7 @@ public class AuthenticationSessionAdapter implements AuthenticationSessionModel @Override public UserModel getAuthenticatedUser() { - return entity.getAuthUserId() == null ? null : session.users().getUserById(entity.getAuthUserId(), getRealm()); } + return entity.getAuthUserId() == null ? null : session.users().getUserById(getRealm(), entity.getAuthUserId()); } @Override public void setAuthenticatedUser(UserModel user) { diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/UserSessionAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/UserSessionAdapter.java index b96f3cfde7..8a4779945b 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/UserSessionAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/UserSessionAdapter.java @@ -175,7 +175,7 @@ public class UserSessionAdapter implements UserSessionModel { return entity.getBrokerUserId(); } public UserModel getUser() { - return session.users().getUserById(entity.getUser(), realm); + return session.users().getUserById(realm, entity.getUser()); } @Override diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java index 4c3c5e5361..72b2275b44 100644 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java @@ -57,6 +57,7 @@ import java.util.stream.Stream; import org.keycloak.models.ModelException; import static org.keycloak.common.util.StackUtil.getShortStackTrace; +import static org.keycloak.models.jpa.PaginationUtils.paginateQuery; import static org.keycloak.utils.StreamsUtil.closing; @@ -288,12 +289,7 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro } protected Stream getRolesStream(TypedQuery query, RealmModel realm, Integer first, Integer max) { - if(Objects.nonNull(first) && Objects.nonNull(max) - && first >= 0 && max >= 0) { - query= query.setFirstResult(first).setMaxResults(max); - } - - Stream results = query.getResultStream(); + Stream results = paginateQuery(query, first, max).getResultStream(); return closing(results.map(role -> new RoleAdapter(session, realm, em, role))); } @@ -451,18 +447,6 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro return closing(paginateQuery(query, first, max).getResultStream()) .map(g -> session.groups().getGroupById(realm, g)); } - - private static TypedQuery paginateQuery(TypedQuery query, Integer first, Integer max) { - if (first != null && first > 0) { - query = query.setFirstResult(first); - } - - if (max != null && max >= 0) { - query = query.setMaxResults(max); - } - - return query; - } @Override public Stream getGroupsStream(RealmModel realm, Stream ids) { @@ -515,13 +499,8 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro public Stream getGroupsByRoleStream(RealmModel realm, RoleModel role, Integer firstResult, Integer maxResults) { TypedQuery query = em.createNamedQuery("groupsInRole", GroupEntity.class); query.setParameter("roleId", role.getId()); - if (firstResult != null && firstResult > 0) { - query = query.setFirstResult(firstResult); - } - if (maxResults != null && maxResults > 0) { - query = query.setMaxResults(maxResults); - } - Stream results = query.getResultStream(); + + Stream results = paginateQuery(query, firstResult, maxResults).getResultStream(); return closing(results .map(g -> (GroupModel) new GroupAdapter(realm, em, g)) @@ -657,14 +636,9 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro @Override public Stream getClientsStream(RealmModel realm, Integer firstResult, Integer maxResults) { TypedQuery query = em.createNamedQuery("getClientIdsByRealm", String.class); - if (firstResult != null && firstResult > 0) { - query.setFirstResult(firstResult); - } - if (maxResults != null && maxResults > 0) { - query.setMaxResults(maxResults); - } + query.setParameter("realm", realm.getId()); - Stream clients = query.getResultStream(); + Stream clients = paginateQuery(query, firstResult, maxResults).getResultStream(); return closing(clients.map(c -> session.clients().getClientById(realm, c)).filter(Objects::nonNull)); } @@ -706,15 +680,10 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro @Override public Stream searchClientsByClientIdStream(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) { TypedQuery query = em.createNamedQuery("searchClientsByClientId", String.class); - if (firstResult != null && firstResult > 0) { - query.setFirstResult(firstResult); - } - if (maxResults != null && maxResults > 0) { - query.setMaxResults(maxResults); - } query.setParameter("clientId", clientId); query.setParameter("realm", realm.getId()); - Stream results = query.getResultStream(); + + Stream results = paginateQuery(query, firstResult, maxResults).getResultStream(); return closing(results.map(c -> session.clients().getClientById(realm, c))); } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java index 02e771e380..1f90a7e26f 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java @@ -65,12 +65,12 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import javax.persistence.LockModeType; +import static org.keycloak.models.jpa.PaginationUtils.paginateQuery; import static org.keycloak.utils.StreamsUtil.closing; @@ -97,18 +97,6 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor credentialStore = new JpaUserCredentialStore(session, em); } - private static TypedQuery paginateQuery(TypedQuery query, Integer first, Integer max) { - if (first != null && first > 0) { - query = query.setFirstResult(first); - } - - if (max != null && max >= 0) { - query = query.setMaxResults(max); - } - - return query; - } - @Override public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { if (id == null) { @@ -364,12 +352,18 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor @Override public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) { UserEntity entity = em.getReference(UserEntity.class, user.getId()); + if (entity == null) { + throw new ModelException("User does not exists"); + } entity.setNotBefore(notBefore); } @Override public int getNotBeforeOfUser(RealmModel realm, UserModel user) { UserEntity entity = em.getReference(UserEntity.class, user.getId()); + if (entity == null) { + throw new ModelException("User does not exists"); + } return entity.getNotBefore(); } @@ -514,14 +508,14 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { UserEntity userEntity = em.find(UserEntity.class, id); if (userEntity == null || !realm.getId().equals(userEntity.getRealmId())) return null; return new UserAdapter(session, realm, em, userEntity); } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { TypedQuery query = em.createNamedQuery("getRealmUserByUsername", UserEntity.class); query.setParameter("username", username.toLowerCase()); query.setParameter("realmId", realm.getId()); @@ -531,7 +525,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { TypedQuery query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class); query.setParameter("email", email.toLowerCase()); query.setParameter("realmId", realm.getId()); @@ -549,7 +543,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public UserModel getUserByFederatedIdentity(FederatedIdentityModel identity, RealmModel realm) { + public UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel identity) { TypedQuery query = em.createNamedQuery("findUserByFederatedIdentityAndRealm", UserEntity.class); query.setParameter("realmId", realm.getId()); query.setParameter("identityProvider", identity.getIdentityProvider()); @@ -583,11 +577,6 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } } - @Override - public Stream getUsersStream(RealmModel realm, boolean includeServiceAccounts) { - return getUsersStream(realm, -1, -1, includeServiceAccounts); - } - @Override public int getUsersCount(RealmModel realm, boolean includeServiceAccount) { String namedQuery = "getRealmUserCountExcludeServiceAccount"; @@ -602,11 +591,6 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor return ((Number)count).intValue(); } - @Override - public int getUsersCount(RealmModel realm) { - return getUsersCount(realm, false); - } - @Override public int getUsersCount(RealmModel realm, Set groupIds) { if (groupIds == null || groupIds.isEmpty()) { @@ -622,7 +606,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public int getUsersCount(String search, RealmModel realm) { + public int getUsersCount(RealmModel realm, String search) { TypedQuery query = em.createNamedQuery("searchForUserCount", Long.class); query.setParameter("realmId", realm.getId()); query.setParameter("search", "%" + search.toLowerCase() + "%"); @@ -632,7 +616,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public int getUsersCount(String search, RealmModel realm, Set groupIds) { + public int getUsersCount(RealmModel realm, String search, Set groupIds) { if (groupIds == null || groupIds.isEmpty()) { return 0; } @@ -647,7 +631,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public int getUsersCount(Map params, RealmModel realm) { + public int getUsersCount(RealmModel realm, Map params) { CriteriaBuilder qb = em.getCriteriaBuilder(); CriteriaQuery userQuery = qb.createQuery(Long.class); Root from = userQuery.from(UserEntity.class); @@ -691,7 +675,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public int getUsersCount(Map params, RealmModel realm, Set groupIds) { + public int getUsersCount(RealmModel realm, Map params, Set groupIds) { if (groupIds == null || groupIds.isEmpty()) { return 0; } @@ -740,12 +724,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public Stream getUsersStream(RealmModel realm) { - return getUsersStream(realm, false); - } - - @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { return getUsersStream(realm, firstResult, maxResults, false); } @@ -776,25 +755,15 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public Stream searchForUserStream(String search, RealmModel realm) { - return searchForUserStream(search, realm, -1, -1); - } - - @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { Map attributes = new HashMap<>(); attributes.put(UserModel.SEARCH, search); session.setAttribute(UserModel.INCLUDE_SERVICE_ACCOUNT, false); - return searchForUserStream(attributes, realm, firstResult, maxResults); + return searchForUserStream(realm, attributes, firstResult, maxResults); } @Override - public Stream searchForUserStream(Map attributes, RealmModel realm) { - return searchForUserStream(attributes, realm, -1, -1); - } - - @Override - public Stream searchForUserStream(Map attributes, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, Map attributes, Integer firstResult, Integer maxResults) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery queryBuilder = builder.createQuery(UserEntity.class); Root root = queryBuilder.from(UserEntity.class); @@ -903,11 +872,11 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor UserProvider users = session.users(); return closing(paginateQuery(query, firstResult, maxResults).getResultStream()) - .map(userEntity -> users.getUserById(userEntity.getId(), realm)); + .map(userEntity -> users.getUserById(realm, userEntity.getId())); } @Override - public Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { TypedQuery query = em.createNamedQuery("getRealmUsersByAttributeNameAndValue", UserEntity.class); query.setParameter("name", attrName); query.setParameter("value", attrValue); @@ -928,7 +897,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor @Override - public Stream getFederatedIdentitiesStream(UserModel user, RealmModel realm) { + public Stream getFederatedIdentitiesStream(RealmModel realm, UserModel user) { TypedQuery query = em.createNamedQuery("findFederatedIdentityByUser", FederatedIdentityEntity.class); UserEntity userEntity = em.getReference(UserEntity.class, user.getId()); query.setParameter("user", userEntity); @@ -938,7 +907,7 @@ public class JpaUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public FederatedIdentityModel getFederatedIdentity(UserModel user, String identityProvider, RealmModel realm) { + public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String identityProvider) { FederatedIdentityEntity entity = findFederatedIdentity(user, identityProvider, LockModeType.NONE); return (entity != null) ? new FederatedIdentityModel(entity.getIdentityProvider(), entity.getUserId(), entity.getUserName(), entity.getToken()) : null; } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/PaginationUtils.java b/model/jpa/src/main/java/org/keycloak/models/jpa/PaginationUtils.java new file mode 100644 index 0000000000..715539642b --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/PaginationUtils.java @@ -0,0 +1,43 @@ +/* + * Copyright 2020 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * 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.keycloak.models.jpa; + +import javax.persistence.TypedQuery; + +public class PaginationUtils { + + public static final int DEFAULT_MAX_RESULTS = Integer.MAX_VALUE >> 1; + + public static TypedQuery paginateQuery(TypedQuery query, Integer first, Integer max) { + if (first != null && first > 0) { + query = query.setFirstResult(first); + + // Workaround for https://hibernate.atlassian.net/browse/HHH-14295 + if (max == null || max < 0) { + max = DEFAULT_MAX_RESULTS; + } + } + + if (max != null && max >= 0) { + query = query.setMaxResults(max); + } + + return query; + } + +} diff --git a/model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionAdapter.java b/model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionAdapter.java index f23fd54008..f2ca89580f 100644 --- a/model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionAdapter.java +++ b/model/map/src/main/java/org/keycloak/models/map/authSession/MapAuthenticationSessionAdapter.java @@ -77,7 +77,7 @@ public class MapAuthenticationSessionAdapter implements AuthenticationSessionMod @Override public UserModel getAuthenticatedUser() { - return entity.getAuthUserId() == null ? null : session.users().getUserById(entity.getAuthUserId(), getRealm()); + return entity.getAuthUserId() == null ? null : session.users().getUserById(getRealm(), entity.getAuthUserId()); } @Override diff --git a/model/map/src/main/java/org/keycloak/models/map/client/MapClientProvider.java b/model/map/src/main/java/org/keycloak/models/map/client/MapClientProvider.java index 1e618c65d6..c6ae69b208 100644 --- a/model/map/src/main/java/org/keycloak/models/map/client/MapClientProvider.java +++ b/model/map/src/main/java/org/keycloak/models/map/client/MapClientProvider.java @@ -38,7 +38,9 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.keycloak.models.map.storage.MapStorage; + import static org.keycloak.common.util.StackUtil.getShortStackTrace; +import static org.keycloak.utils.StreamsUtil.paginatedStream; public class MapClientProvider implements ClientProvider { @@ -130,14 +132,7 @@ public class MapClientProvider implements ClientProvider { @Override public Stream getClientsStream(RealmModel realm, Integer firstResult, Integer maxResults) { - Stream s = getClientsStream(realm); - if (firstResult != null && firstResult >= 0) { - s = s.skip(firstResult); - } - if (maxResults != null && maxResults >= 0) { - s = s.limit(maxResults); - } - return s; + return paginatedStream(getClientsStream(realm), firstResult, maxResults); } private Stream getNotRemovedUpdatedClientsStream() { @@ -281,14 +276,7 @@ public class MapClientProvider implements ClientProvider { .filter(entity -> entity.getClientId() != null && entity.getClientId().toLowerCase().contains(clientIdLower)) .sorted(COMPARE_BY_CLIENT_ID); - if (firstResult != null && firstResult >= 0) { - s = s.skip(firstResult); - } - if (maxResults != null && maxResults >= 0) { - s = s.limit(maxResults); - } - - return s.map(entityToAdapterFunc(realm)); + return paginatedStream(s, firstResult, maxResults).map(entityToAdapterFunc(realm)); } @Override diff --git a/model/map/src/main/java/org/keycloak/models/map/group/MapGroupProvider.java b/model/map/src/main/java/org/keycloak/models/map/group/MapGroupProvider.java index 2e9f02b29b..759b5aaf73 100644 --- a/model/map/src/main/java/org/keycloak/models/map/group/MapGroupProvider.java +++ b/model/map/src/main/java/org/keycloak/models/map/group/MapGroupProvider.java @@ -36,6 +36,7 @@ import java.util.function.Predicate; import java.util.stream.Stream; import static org.keycloak.common.util.StackUtil.getShortStackTrace; +import static org.keycloak.utils.StreamsUtil.paginatedStream; public class MapGroupProvider implements GroupProvider { @@ -124,15 +125,7 @@ public class MapGroupProvider implements GroupProvider { groupModelStream = groupModelStream.filter(groupModel -> groupModel.getName().toLowerCase().contains(s)); } - if (first != null && first > 0) { - groupModelStream = groupModelStream.skip(first); - } - - if (max != null && max >= 0) { - groupModelStream = groupModelStream.limit(max); - } - - return groupModelStream; + return paginatedStream(groupModelStream, first, max); } @Override @@ -157,15 +150,7 @@ public class MapGroupProvider implements GroupProvider { LOG.tracef("getGroupsByRole(%s, %s, %d, %d)%s", realm, role, firstResult, maxResults, getShortStackTrace()); Stream groupModelStream = getGroupsStream(realm).filter(groupModel -> groupModel.hasRole(role)); - if (firstResult != null && firstResult > 0) { - groupModelStream = groupModelStream.skip(firstResult); - } - - if (maxResults != null && maxResults >= 0) { - groupModelStream = groupModelStream.limit(maxResults); - } - - return groupModelStream; + return paginatedStream(groupModelStream, firstResult, maxResults); } @Override @@ -179,15 +164,7 @@ public class MapGroupProvider implements GroupProvider { public Stream getTopLevelGroupsStream(RealmModel realm, Integer firstResult, Integer maxResults) { Stream groupModelStream = getTopLevelGroupsStream(realm); - if (firstResult != null && firstResult > 0) { - groupModelStream = groupModelStream.skip(firstResult); - } - - if (maxResults != null && maxResults >= 0) { - groupModelStream = groupModelStream.limit(maxResults); - } - - return groupModelStream; + return paginatedStream(groupModelStream, firstResult, maxResults); } @@ -197,15 +174,8 @@ public class MapGroupProvider implements GroupProvider { Stream groupModelStream = getGroupsStream(realm) .filter(groupModel -> groupModel.getName().contains(search)); - if (firstResult != null && firstResult > 0) { - groupModelStream = groupModelStream.skip(firstResult); - } - if (maxResults != null && maxResults >= 0) { - groupModelStream = groupModelStream.limit(maxResults); - } - - return groupModelStream; + return paginatedStream(groupModelStream, firstResult, maxResults); } @Override diff --git a/model/map/src/main/java/org/keycloak/models/map/role/MapRoleProvider.java b/model/map/src/main/java/org/keycloak/models/map/role/MapRoleProvider.java index 0012618461..75bd41719a 100644 --- a/model/map/src/main/java/org/keycloak/models/map/role/MapRoleProvider.java +++ b/model/map/src/main/java/org/keycloak/models/map/role/MapRoleProvider.java @@ -35,6 +35,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import org.keycloak.models.map.storage.MapStorage; import static org.keycloak.common.util.StackUtil.getShortStackTrace; +import static org.keycloak.utils.StreamsUtil.paginatedStream; + import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleProvider; import org.keycloak.models.map.common.StreamUtils; @@ -126,14 +128,7 @@ public class MapRoleProvider implements RoleProvider { @Override public Stream getRealmRolesStream(RealmModel realm, Integer first, Integer max) { - Stream s = getRealmRolesStream(realm); - if (first != null && first >= 0) { - s = s.skip(first); - } - if (max != null && max >= 0) { - s = s.limit(max); - } - return s; + return paginatedStream(getRealmRolesStream(realm), first, max); } @Override @@ -171,14 +166,7 @@ public class MapRoleProvider implements RoleProvider { @Override public Stream getClientRolesStream(ClientModel client, Integer first, Integer max) { - Stream s = getClientRolesStream(client); - if (first != null && first > 0) { - s = s.skip(first); - } - if (max != null && max >= 0) { - s = s.limit(max); - } - return s; + return paginatedStream(getClientRolesStream(client), first, max); } @Override @@ -326,14 +314,7 @@ public class MapRoleProvider implements RoleProvider { ) .sorted(COMPARE_BY_NAME); - if (first != null && first > 0) { - s = s.skip(first); - } - if (max != null && max >= 0) { - s = s.limit(max); - } - - return s.map(entityToAdapterFunc(realm)); + return paginatedStream(s.map(entityToAdapterFunc(realm)), first, max); } @Override @@ -350,14 +331,7 @@ public class MapRoleProvider implements RoleProvider { ) .sorted(COMPARE_BY_NAME); - if (first != null && first > 0) { - s = s.skip(first); - } - if (max != null && max >= 0) { - s = s.limit(max); - } - - return s.map(entityToAdapterFunc(client.getRealm())); + return paginatedStream(s,first, max).map(entityToAdapterFunc(client.getRealm())); } @Override diff --git a/model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java b/model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java index fafa314b96..c6a4cf04b2 100644 --- a/model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java +++ b/model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java @@ -68,6 +68,7 @@ import static org.keycloak.models.UserModel.EMAIL_VERIFIED; import static org.keycloak.models.UserModel.FIRST_NAME; import static org.keycloak.models.UserModel.LAST_NAME; import static org.keycloak.models.UserModel.USERNAME; +import static org.keycloak.utils.StreamsUtil.paginatedStream; public class MapUserProvider implements UserProvider.Streams, UserCredentialStore.Streams { @@ -96,12 +97,12 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor @Override public boolean checkEmailUniqueness(RealmModel realm, String email) { - return getUserByEmail(email, realm) != null; + return getUserByEmail(realm, email) != null; } @Override public boolean checkUsernameUniqueness(RealmModel realm, String username) { - return getUserByUsername(username, realm) != null; + return getUserByUsername(realm, username) != null; } }; } @@ -156,18 +157,6 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor return getNotRemovedUpdatedUsersStream() .filter(entityRealmFilter(realm)); } - - private Stream paginatedStream(Stream originalStream, Integer first, Integer max) { - if (first != null && first > 0) { - originalStream = originalStream.skip(first); - } - - if (max != null && max >= 0) { - originalStream = originalStream.limit(max); - } - - return originalStream; - } @Override public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) { @@ -206,7 +195,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public Stream getFederatedIdentitiesStream(UserModel user, RealmModel realm) { + public Stream getFederatedIdentitiesStream(RealmModel realm, UserModel user) { LOG.tracef("getFederatedIdentitiesStream(%s, %s)%s", realm, user.getId(), getShortStackTrace()); return getEntityById(realm, user.getId()) .map(AbstractUserEntity::getFederatedIdentities).orElseGet(Stream::empty) @@ -214,7 +203,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) { + public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { LOG.tracef("getFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialProvider, getShortStackTrace()); return getEntityById(realm, user.getId()) .map(userEntity -> userEntity.getFederatedIdentity(socialProvider)) @@ -223,7 +212,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) { + public UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel socialLink) { LOG.tracef("getUserByFederatedIdentity(%s, %s)%s", realm, socialLink, getShortStackTrace()); return getUnsortedUserEntitiesStream(realm) .filter(userEntity -> Objects.nonNull(userEntity.getFederatedIdentity(socialLink.getIdentityProvider()))) @@ -231,7 +220,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { - if (list.size() == 0) { + if (list.isEmpty()) { return null; } else if (list.size() != 1) { throw new IllegalStateException("More results found for identityProvider=" + socialLink.getIdentityProvider() + @@ -246,8 +235,8 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { LOG.tracef("addConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace()); - UserConsentEntity consentEntity = UserConsentEntity.fromModel(consent); - getRegisteredEntityById(realm, userId).ifPresent(userEntity -> userEntity.addUserConsent(consentEntity)); + getRegisteredEntityByIdOrThrow(realm, userId) + .addUserConsent(UserConsentEntity.fromModel(consent)); } @Override @@ -298,15 +287,15 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor @Override public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) { LOG.tracef("setNotBeforeForUser(%s, %s, %d)%s", realm, user.getId(), notBefore, getShortStackTrace()); - getRegisteredEntityById(realm, user.getId()).ifPresent(userEntity -> userEntity.setNotBefore(notBefore)); + getRegisteredEntityByIdOrThrow(realm, user.getId()).setNotBefore(notBefore); } @Override public int getNotBeforeOfUser(RealmModel realm, UserModel user) { LOG.tracef("getNotBeforeOfUser(%s, %s)%s", realm, user.getId(), getShortStackTrace()); return getEntityById(realm, user.getId()) - .map(AbstractUserEntity::getNotBefore) - .orElse(0); + .orElseThrow(this::userDoesntExistException) + .getNotBefore(); } @Override @@ -317,7 +306,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { - if (list.size() == 0) { + if (list.isEmpty()) { return null; } else if (list.size() != 1) { throw new IllegalStateException("More service account linked users found for client=" + client.getClientId() + @@ -479,13 +468,13 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { LOG.tracef("getUserById(%s, %s)%s", realm, id, getShortStackTrace()); return getEntityById(realm, id).map(entityToAdapterFunc(realm)).orElse(null); } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { if (username == null) return null; final String usernameLowercase = username.toLowerCase(); @@ -497,12 +486,12 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { LOG.tracef("getUserByEmail(%s, %s)%s", realm, email, getShortStackTrace()); List usersWithEmail = getUnsortedUserEntitiesStream(realm) - .filter(userEntity -> Objects.equals(userEntity.getEmail(), email)) + .filter(userEntity -> Objects.equals(userEntity.getEmail(), email.toLowerCase())) .collect(Collectors.toList()); - if (usersWithEmail.size() == 0) return null; + if (usersWithEmail.isEmpty()) return null; if (usersWithEmail.size() > 1) { // Realm settings have been changed from allowing duplicate emails to not allowing them @@ -523,21 +512,15 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor return new MapUserAdapter(session, realm, userEntity) { @Override public boolean checkEmailUniqueness(RealmModel realm, String email) { - return getUserByEmail(email, realm) != null; + return getUserByEmail(realm, email) != null; } @Override public boolean checkUsernameUniqueness(RealmModel realm, String username) { - return getUserByUsername(username, realm) != null; + return getUserByUsername(realm, username) != null; } }; } - @Override - public int getUsersCount(RealmModel realm) { - LOG.tracef("getUsersCount(%s)%s", realm, getShortStackTrace()); - return getUsersCount(realm, false); - } - @Override public int getUsersCount(RealmModel realm, boolean includeServiceAccount) { LOG.tracef("getUsersCount(%s, %s)%s", realm, includeServiceAccount, getShortStackTrace()); @@ -564,46 +547,22 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public Stream getUsersStream(RealmModel realm) { - LOG.tracef("getUsersStream(%s)%s", realm, getShortStackTrace()); - return getUsersStream(realm, null, null, false); - } - - @Override - public Stream getUsersStream(RealmModel realm, boolean includeServiceAccounts) { - LOG.tracef("getUsersStream(%s)%s", realm, getShortStackTrace()); - return getUsersStream(realm, null, null, includeServiceAccounts); - } - - @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { LOG.tracef("getUsersStream(%s, %d, %d)%s", realm, firstResult, maxResults, getShortStackTrace()); return getUsersStream(realm, firstResult, maxResults, false); } @Override - public Stream searchForUserStream(String search, RealmModel realm) { - LOG.tracef("searchForUserStream(%s, %s)%s", realm, search, getShortStackTrace()); - return searchForUserStream(search, realm, null, null); - } - - @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, search, firstResult, maxResults, getShortStackTrace()); Map attributes = new HashMap<>(); attributes.put(UserModel.SEARCH, search); session.setAttribute(UserModel.INCLUDE_SERVICE_ACCOUNT, false); - return searchForUserStream(attributes, realm, firstResult, maxResults); + return searchForUserStream(realm, attributes, firstResult, maxResults); } @Override - public Stream searchForUserStream(Map params, RealmModel realm) { - LOG.tracef("searchForUserStream(%s, %s)%s", realm, params, getShortStackTrace()); - return searchForUserStream(params, realm, null, null); - } - - @Override - public Stream searchForUserStream(Map attributes, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, Map attributes, Integer firstResult, Integer maxResults) { LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, attributes, firstResult, maxResults, getShortStackTrace()); /* Find all predicates based on attributes map */ List> predicatesList = new ArrayList<>(); @@ -735,13 +694,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor } @Override - public Stream getGroupMembersStream(RealmModel realm, GroupModel group) { - LOG.tracef("getGroupMembersStream(%s, %s)%s", realm, group.getId(), getShortStackTrace()); - return getGroupMembersStream(realm, group, null, null); - } - - @Override - public Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { LOG.tracef("searchForUserByUserAttributeStream(%s, %s, %s)%s", realm, attrName, attrValue, getShortStackTrace()); return getUnsortedUserEntitiesStream(realm) .filter(userEntity -> userEntity.getAttribute(attrName).contains(attrValue)) diff --git a/model/map/src/main/test/java/org/keycloak/models/map/user/AbstractUserEntityCredentialsOrderTest.java b/model/map/src/test/java/org/keycloak/models/map/user/AbstractUserEntityCredentialsOrderTest.java similarity index 100% rename from model/map/src/main/test/java/org/keycloak/models/map/user/AbstractUserEntityCredentialsOrderTest.java rename to model/map/src/test/java/org/keycloak/models/map/user/AbstractUserEntityCredentialsOrderTest.java diff --git a/quarkus/runtime/src/main/java/org/keycloak/connections/jpa/QuarkusJpaConnectionProviderFactory.java b/quarkus/runtime/src/main/java/org/keycloak/connections/jpa/QuarkusJpaConnectionProviderFactory.java index 0c7b2fa4b1..dcc9e6dfa5 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/connections/jpa/QuarkusJpaConnectionProviderFactory.java +++ b/quarkus/runtime/src/main/java/org/keycloak/connections/jpa/QuarkusJpaConnectionProviderFactory.java @@ -61,7 +61,6 @@ import org.keycloak.models.UserModel; import org.keycloak.models.UserProvider; import org.keycloak.models.dblock.DBLockManager; import org.keycloak.models.dblock.DBLockProvider; -import org.keycloak.models.utils.DefaultKeyProviders; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.provider.ServerInfoAwareProviderFactory; @@ -497,7 +496,7 @@ public class QuarkusJpaConnectionProviderFactory implements JpaConnectionProvide UserProvider users = session.users(); - if (users.getUserByUsername(userRep.getUsername(), realm) != null) { + if (users.getUserByUsername(realm, userRep.getUsername()) != null) { ServicesLogger.LOGGER.notCreatingExistingUser(userRep.getUsername()); } else { UserModel user = users.addUser(realm, userRep.getUsername()); diff --git a/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java b/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java index e192c099ea..e8fccd0f01 100644 --- a/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java +++ b/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java @@ -165,13 +165,13 @@ public class DefaultEvaluation implements Evaluation { private UserModel getUser(String id, KeycloakSession session) { RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserById(id, realm); + UserModel user = session.users().getUserById(realm, id); if (Objects.isNull(user)) { - user = session.users().getUserByUsername(id, realm); + user = session.users().getUserByUsername(realm ,id); } if (Objects.isNull(user)) { - user = session.users().getUserByEmail(id, realm); + user = session.users().getUserByEmail(realm, id); } if (Objects.isNull(user)) { user = session.users().getServiceAccount(realm.getClientById(id)); diff --git a/server-spi-private/src/main/java/org/keycloak/models/session/PersistentUserSessionAdapter.java b/server-spi-private/src/main/java/org/keycloak/models/session/PersistentUserSessionAdapter.java index 5a19aabb93..e1607ead2e 100644 --- a/server-spi-private/src/main/java/org/keycloak/models/session/PersistentUserSessionAdapter.java +++ b/server-spi-private/src/main/java/org/keycloak/models/session/PersistentUserSessionAdapter.java @@ -120,7 +120,7 @@ public class PersistentUserSessionAdapter implements OfflineUserSessionModel { @Override public UserModel getUser() { if (user == null) { - user = session.users().getUserById(userId, realm); + user = session.users().getUserById(realm, userId); } return user; } diff --git a/server-spi-private/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java b/server-spi-private/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java index e67d281133..4e71c38407 100755 --- a/server-spi-private/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java +++ b/server-spi-private/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java @@ -205,13 +205,13 @@ public final class KeycloakModelUtils { */ public static UserModel findUserByNameOrEmail(KeycloakSession session, RealmModel realm, String username) { if (realm.isLoginWithEmailAllowed() && username.indexOf('@') != -1) { - UserModel user = session.users().getUserByEmail(username, realm); + UserModel user = session.users().getUserByEmail(realm, username); if (user != null) { return user; } } - return session.users().getUserByUsername(username, realm); + return session.users().getUserByUsername(realm, username); } /** diff --git a/server-spi-private/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java b/server-spi-private/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java index 6b55c21a45..7ab8051e68 100755 --- a/server-spi-private/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java +++ b/server-spi-private/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java @@ -885,7 +885,7 @@ public class ModelToRepresentation { ClientModel clientModel = realm.getClientById(resourceServer); owner.setName(clientModel.getClientId()); } else { - UserModel userModel = keycloakSession.users().getUserById(owner.getId(), realm); + UserModel userModel = keycloakSession.users().getUserById(realm, owner.getId()); if (userModel == null) { throw new RuntimeException("Could not find the user [" + owner.getId() + "] who owns the Resource [" + resource.getId() + "]."); @@ -934,8 +934,8 @@ public class ModelToRepresentation { representation.setResourceName(resource.getName()); KeycloakSession keycloakSession = authorization.getKeycloakSession(); RealmModel realm = authorization.getRealm(); - UserModel userOwner = keycloakSession.users().getUserById(ticket.getOwner(), realm); - UserModel requester = keycloakSession.users().getUserById(ticket.getRequester(), realm); + UserModel userOwner = keycloakSession.users().getUserById(realm, ticket.getOwner()); + UserModel requester = keycloakSession.users().getUserById(realm, ticket.getRequester()); representation.setRequesterName(requester.getUsername()); if (userOwner != null) { representation.setOwnerName(userOwner.getUsername()); diff --git a/server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java b/server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java index de9b471158..b0bbb1939f 100755 --- a/server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java +++ b/server-spi-private/src/main/java/org/keycloak/models/utils/RepresentationToModel.java @@ -2257,7 +2257,7 @@ public class RepresentationToModel { owner.setId(resourceServer.getId()); resource.setOwner(owner); } else if (owner.getName() != null) { - UserModel user = session.users().getUserByUsername(owner.getName(), realm); + UserModel user = session.users().getUserByUsername(realm, owner.getName()); if (user != null) { owner.setId(user.getId()); @@ -2572,10 +2572,10 @@ public class RepresentationToModel { RealmModel realm = authorization.getRealm(); KeycloakSession keycloakSession = authorization.getKeycloakSession(); UserProvider users = keycloakSession.users(); - UserModel ownerModel = users.getUserById(ownerId, realm); + UserModel ownerModel = users.getUserById(realm, ownerId); if (ownerModel == null) { - ownerModel = users.getUserByUsername(ownerId, realm); + ownerModel = users.getUserByUsername(realm, ownerId); } if (ownerModel == null) { diff --git a/server-spi-private/src/main/java/org/keycloak/utils/StreamsUtil.java b/server-spi-private/src/main/java/org/keycloak/utils/StreamsUtil.java index 61ec1b6687..0f7a020422 100644 --- a/server-spi-private/src/main/java/org/keycloak/utils/StreamsUtil.java +++ b/server-spi-private/src/main/java/org/keycloak/utils/StreamsUtil.java @@ -24,6 +24,15 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; public class StreamsUtil { + + /** + * Returns the original stream that is closed on terminating operation. + * + * It is used, for example, for closing hibernate provided streams since it is required by hibernate documentation. + * + * @param stream the stream which is expected to be closed on termination + * @return stream that will be closed on terminating operation + */ public static Stream closing(Stream stream) { return Stream.of(stream).flatMap(Function.identity()); } @@ -42,4 +51,26 @@ public class StreamsUtil { throw ex; } } + + /** + * Returns the original stream that is limited with {@link Stream#skip(long) skip} and + * {@link Stream#limit(long) limit} functions based on values of {@code first} and {@code max} parameters. + * + * @param originalStream Stream to be limited. + * @param first Index of first item to be returned by the stream. Ignored if negative, zero {@code null}. + * @param max Maximum number of items to be returned by the stream. Ignored if negative or {@code null}. + * @param Type of items in the stream + * @return Stream + */ + public static Stream paginatedStream(Stream originalStream, Integer first, Integer max) { + if (first != null && first > 0) { + originalStream = originalStream.skip(first); + } + + if (max != null && max >= 0) { + originalStream = originalStream.limit(max); + } + + return originalStream; + } } diff --git a/server-spi/src/main/java/org/keycloak/models/GroupProvider.java b/server-spi/src/main/java/org/keycloak/models/GroupProvider.java index 309bf69d69..c22a905eb5 100644 --- a/server-spi/src/main/java/org/keycloak/models/GroupProvider.java +++ b/server-spi/src/main/java/org/keycloak/models/GroupProvider.java @@ -38,7 +38,7 @@ public interface GroupProvider extends Provider, GroupLookupProvider { * @param id Id. * @param realm Realm. * @return GroupModel with the corresponding id. - * @deprecated Use method {@code getGroupById(realm, id)} + * @deprecated Use method {@link #getGroupById(RealmModel, String) getGroupById} */ default GroupModel getGroupById(String id, RealmModel realm) { return getGroupById(realm, id); @@ -140,7 +140,7 @@ public interface GroupProvider extends Provider, GroupLookupProvider { * @param firstResult First result to return. Ignored if negative. * @param maxResults Maximum number of results to return. Ignored if negative. * @return List of groups with the given role. - * @deprecated Use {@link #getGroupsByRoleStream(RealmModel, RoleModel, int, int) getGroupsByRoleStream} instead. + * @deprecated Use {@link #getGroupsByRoleStream(RealmModel, RoleModel, Integer, Integer) getGroupsByRoleStream} instead. */ @Deprecated default List getGroupsByRole(RealmModel realm, RoleModel role, int firstResult, int maxResults) { diff --git a/server-spi/src/main/java/org/keycloak/models/UserProvider.java b/server-spi/src/main/java/org/keycloak/models/UserProvider.java index 249f55ab24..9784b4d26f 100755 --- a/server-spi/src/main/java/org/keycloak/models/UserProvider.java +++ b/server-spi/src/main/java/org/keycloak/models/UserProvider.java @@ -38,73 +38,35 @@ public interface UserProvider extends Provider, UserQueryProvider, UserRegistrationProvider, UserBulkUpdateProvider { - // Note: The reason there are so many query methods here is for layering a cache on top of an persistent KeycloakSession - - void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink); - boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider); - void preRemove(RealmModel realm, IdentityProviderModel provider); - void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel); /** - * @deprecated Use {@link #getFederatedIdentitiesStream(UserModel, RealmModel) getFederatedIdentitiesStream} instead. - */ - @Deprecated - Set getFederatedIdentities(UserModel user, RealmModel realm); - - /** - * Obtains the federated identities of the specified user. + * Sets the notBefore value for the given user * - * @param user a reference to the user. - * @param realm a reference to the realm. - * @return a non-null {@link Stream} of federated identities associated with the user. - */ - default Stream getFederatedIdentitiesStream(UserModel user, RealmModel realm) { - Set value = this.getFederatedIdentities(user, realm); - return value != null ? value.stream() : Stream.empty(); - } - - FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm); - UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm); - - void addConsent(RealmModel realm, String userId, UserConsentModel consent); - UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientInternalId); - - /** - * @deprecated Use {@link #getConsentsStream(RealmModel, String) getConsentsStream} instead. - */ - @Deprecated - List getConsents(RealmModel realm, String userId); - - /** - * Obtains the consents associated with the user identified by the specified {@code userId}. + * @param realm a reference to the realm + * @param user the user model + * @param notBefore new value for notBefore * - * @param realm a reference to the realm. - * @param userId the user identifier. - * @return a non-null {@link Stream} of consents associated with the user. + * @throws ModelException when user doesn't exist in the storage */ - default Stream getConsentsStream(RealmModel realm, String userId) { - List value = this.getConsents(realm, userId); - return value != null ? value.stream() : Stream.empty(); - } - - /** - * - * @param realm - * @param userId - * @param consent - * @throws ModelException when consent doesn't exist for the userId - */ - void updateConsent(RealmModel realm, String userId, UserConsentModel consent); - boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId); - void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore); + + /** + * Gets the notBefore value for the given user + * + * @param realm a reference to the realm + * @param user the user model + * @return the value of notBefore + * + * @throws ModelException when user doesn't exist in the storage + */ int getNotBeforeOfUser(RealmModel realm, UserModel user); /** + * Return a UserModel representing service account of the client * - * @param client + * @param client the client model * @throws IllegalArgumentException when there are more service accounts associated with the given clientId - * @return + * @return userModel representing service account of the client */ UserModel getServiceAccount(ClientModel client); @@ -136,8 +98,8 @@ public interface UserProvider extends Provider, * Obtains the users associated with the specified realm. * * @param realm a reference to the realm being used for the search. - * @param firstResult first result to return. Ignored if negative. - * @param maxResults maximum number of results to return. Ignored if negative. + * @param firstResult first result to return. Ignored if negative, zero, or {@code null}. + * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @param includeServiceAccounts {@code true} if service accounts should be included in the result; {@code false} otherwise. * @return a non-null {@link Stream} of users associated withe the realm. */ @@ -147,53 +109,297 @@ public interface UserProvider extends Provider, } /** + * Adds a new user into the storage. + *

* only used for local storage * - * @param realm - * @param id - * @param username - * @param addDefaultRoles - * @param addDefaultRequiredActions - * @return + * @param realm the realm that user will be created in + * @param id id of the new user. Should be generated to a random value if {@code null}. + * @param username username + * @param addDefaultRoles if {@code true}, the user should join all realm default roles + * @param addDefaultRequiredActions if {@code true}, all default required actions are added to the created user + * @return model of created user + * + * @throws NullPointerException when username or realm is {@code null} + * @throws ModelDuplicateException when a user with given id or username already exists */ UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions); - void preRemove(RealmModel realm); /** * Removes any imported users from a specific User Storage Provider. * - * @param realm - * @param storageProviderId + * @param realm a reference to the realm + * @param storageProviderId id of the user storage provider */ void removeImportedUsers(RealmModel realm, String storageProviderId); /** - * Set federation link to null to imported users of a specific User Storage Provider + * Set federation link to {@code null} to imported users of a specific User Storage Provider * - * @param realm - * @param storageProviderId + * @param realm a reference to the realm + * @param storageProviderId id of the storage provider */ void unlinkUsers(RealmModel realm, String storageProviderId); + /* USER CONSENTS methods */ + + /** + * Add user consent for the user. + * + * @param realm a reference to the realm + * @param userId id of the user + * @param consent all details corresponding to the granted consent + * + * @throws ModelException If there is no user with userId + */ + void addConsent(RealmModel realm, String userId, UserConsentModel consent); + + /** + * Returns UserConsentModel given by a user with the userId for the client with clientInternalId + * + * @param realm a reference to the realm + * @param userId id of the user + * @param clientInternalId id of the client + * @return consent given by the user to the client or {@code null} if no consent or user exists + * + * @throws ModelException when there are more consents fulfilling specified parameters + */ + UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientInternalId); + + /** + * @deprecated Use {@link #getConsentsStream(RealmModel, String) getConsentsStream} instead. + */ + @Deprecated + List getConsents(RealmModel realm, String userId); + + /** + * Obtains the consents associated with the user identified by the specified {@code userId}. + * + * @param realm a reference to the realm. + * @param userId the user identifier. + * @return a non-null {@link Stream} of consents associated with the user. + */ + default Stream getConsentsStream(RealmModel realm, String userId) { + List value = this.getConsents(realm, userId); + return value != null ? value.stream() : Stream.empty(); + } + + /** + * Update client scopes in the stored user consent + * + * @param realm a reference to the realm + * @param userId id of the user + * @param consent new details of the user consent + * + * @throws ModelException when consent doesn't exist for the userId + */ + void updateConsent(RealmModel realm, String userId, UserConsentModel consent); + + /** + * Remove a user consent given by the user id and client id + * + * @param realm a reference to the realm + * @param userId id of the user + * @param clientInternalId id of the client + * @return {@code true} if the consent was removed, {@code false} otherwise + */ + boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId); + + /* FEDERATED IDENTITIES methods */ + + /** + * Adds a federated identity link for the user within the realm + * + * @param realm a reference to the realm + * @param user the user model + * @param socialLink the federated identity model containing all details of the association between the user and + * the identity provider + */ + void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink); + + /** + * Removes federation link between the user and the identity provider given by its id + * + * @param realm a reference to the realm + * @param user the user model + * @param socialProvider alias of the identity provider, see {@link IdentityProviderModel#getAlias()} + * @return {@code true} if the association was removed, {@code false} otherwise + */ + boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider); + + /** + * Update details of association between the federatedUser and the idp given by the federatedIdentityModel + * + * @param realm a reference to the realm + * @param federatedUser the user model + * @param federatedIdentityModel the federated identity model containing all details of the association between + * the user and the identity provider + */ + void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel); + + /** + * @deprecated Use {@link #getFederatedIdentitiesStream(RealmModel, UserModel) getFederatedIdentitiesStream} instead. + */ + @Deprecated + Set getFederatedIdentities(UserModel user, RealmModel realm); + + /** + * Obtains the federated identities of the specified user. + * + * @param realm a reference to the realm. + * @param user the reference to the user. + * @return a non-null {@link Stream} of federated identities associated with the user. + */ + default Stream getFederatedIdentitiesStream(RealmModel realm, UserModel user) { + Set value = this.getFederatedIdentities(user, realm); + return value != null ? value.stream() : Stream.empty(); + } + + /** + * Returns details of the association between the user and the socialProvider. + * + * @param realm a reference to the realm + * @param user the user model + * @param socialProvider the id of the identity provider + * @return federatedIdentityModel or {@code null} if no association exists + */ + default FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { + return getFederatedIdentity(user, socialProvider, realm); + } + /** + * @deprecated Use {@link #getFederatedIdentity(RealmModel, UserModel, String) getFederatedIdentity} instead. + */ + @Deprecated + FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm); + + /** + * Returns a userModel that corresponds to the given socialLink. + * + * @param realm a reference to the realm + * @param socialLink the socialLink + * @return the user corresponding to socialLink and {@code null} if no such user exists + * + * @throws IllegalStateException when there are more users for the given socialLink + */ + default UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel socialLink) { + return getUserByFederatedIdentity(socialLink, realm); + } + /** + * @deprecated Use {@link #getUserByFederatedIdentity(RealmModel, FederatedIdentityModel) getUserByFederatedIdentity} instead. + */ + @Deprecated + UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm); + + /* PRE REMOVE methods - for cleaning user related properties when some other entity is removed */ + + /** + * Called when a realm is removed. + * Should remove all users that belong to the realm. + * + * @param realm a reference to the realm + */ + void preRemove(RealmModel realm); + + /** + * Called when an identity provider is removed. + * Should remove all federated identities assigned to users from the provider. + * + * @param realm a reference to the realm + * @param provider provider model + */ + void preRemove(RealmModel realm, IdentityProviderModel provider); + + /** + * Called when a role is removed. + * Should remove the role membership for each user. + * + * @param realm a reference to the realm + * @param role the role model + */ void preRemove(RealmModel realm, RoleModel role); + + /** + * Called when a group is removed. + * Should remove the group membership for each user. + * + * @param realm a reference to the realm + * @param group the group model + */ void preRemove(RealmModel realm, GroupModel group); + /** + * Called when a client is removed. + * Should remove all user consents associated with the client + * + * @param realm a reference to the realm + * @param client the client model + */ void preRemove(RealmModel realm, ClientModel client); + + /** + * Called when a protocolMapper is removed + * + * @param protocolMapper the protocolMapper model + */ void preRemove(ProtocolMapperModel protocolMapper); + + /** + * Called when a client scope is removed. + * Should remove the clientScope from each user consent + * + * @param clientScope the clientScope model + */ void preRemove(ClientScopeModel clientScope); + /** + * Called when a component is removed. + * Should remove all data in UserStorage associated with removed component. + * For example, + *

    + *
  • if component corresponds to UserStorageProvider all imported users from the provider should be removed,
  • + *
  • if component corresponds to ClientStorageProvider all consents granted for clients imported from the + * provider should be removed
  • + *
+ * + * @param realm a reference to the realm + * @param component the component model + */ + void preRemove(RealmModel realm, ComponentModel component); + void close(); - void preRemove(RealmModel realm, ComponentModel component); + /** + * The {@link UserProvider.Streams} interface makes all collection-based methods in {@link UserProvider} default by + * providing implementations that delegate to the {@link Stream}-based variants instead of the other way around. + *

+ * It allows for implementations to focus on the {@link Stream}-based approach for processing sets of data and benefit + * from the potential memory and performance optimizations of that approach. + */ + interface Streams extends UserProvider, UserQueryProvider.Streams, UserLookupProvider.Streams { - interface Streams extends UserProvider, UserQueryProvider.Streams { @Override - default Set getFederatedIdentities(UserModel user, RealmModel realm) { - return this.getFederatedIdentitiesStream(user, realm).collect(Collectors.toSet()); + FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider); + + @Override + default FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) { + return getFederatedIdentity(realm, user, socialProvider); } @Override - Stream getFederatedIdentitiesStream(UserModel user, RealmModel realm); + UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel socialLink); + + @Override + default UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) { + return getUserByFederatedIdentity(realm, socialLink); + } + + @Override + default Set getFederatedIdentities(UserModel user, RealmModel realm) { + return this.getFederatedIdentitiesStream(realm, user).collect(Collectors.toSet()); + } + + @Override + Stream getFederatedIdentitiesStream(RealmModel realm, UserModel user); @Override default List getConsents(RealmModel realm, String userId) { @@ -209,7 +415,9 @@ public interface UserProvider extends Provider, } @Override - Stream getUsersStream(RealmModel realm, boolean includeServiceAccounts); + default Stream getUsersStream(RealmModel realm, boolean includeServiceAccounts) { + return getUsersStream(realm, null, null, includeServiceAccounts); + } @Override default List getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) { diff --git a/server-spi/src/main/java/org/keycloak/storage/UserStorageProvider.java b/server-spi/src/main/java/org/keycloak/storage/UserStorageProvider.java index 92d7c1a5ce..31bb5ce814 100644 --- a/server-spi/src/main/java/org/keycloak/storage/UserStorageProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/UserStorageProvider.java @@ -22,6 +22,19 @@ import org.keycloak.models.RoleModel; import org.keycloak.provider.Provider; /** + * A class implementing this interface represents a user storage provider to Keycloak. + *

+ * This interface contains only very basic methods for manipulating users. However, the storage provider capabilities + * are extended by implementing one or more of the following capability interfaces: + *

    + *
  • {@link org.keycloak.storage.user.UserLookupProvider UserLookupProvider} - Provide basic lookup methods. After implementing it is possible to login using users from the storage.
  • + *
  • {@link org.keycloak.storage.user.UserQueryProvider UserQueryProvider} - Provide complex lookup methods. After implementing it is possible to manage users from admin console.
  • + *
  • {@link org.keycloak.storage.user.UserRegistrationProvider UserRegistrationProvider} - Provide methods for adding users. After implementing it is possible to store registered users in the storage.
  • + *
  • {@link org.keycloak.storage.user.UserBulkUpdateProvider UserBulkUpdateProvider} - After implementing it is possible to perform bulk operations on all users from storage (for example, addition of a role to all users).
  • + *
  • {@link org.keycloak.storage.user.ImportedUserValidation ImportedUserValidation} - Provider method for validating users within Keycloak local storage that are imported from the storage.
  • + *
  • {@link org.keycloak.storage.user.ImportSynchronization ImportSynchronization} - Provider methods for synchronization of the storage with Keycloak local storage. After implementing it is possible to sync users in the Admin console.
  • + *
+ * * @author Bill Burke * @version $Revision: 1 $ */ diff --git a/server-spi/src/main/java/org/keycloak/storage/user/ImportSynchronization.java b/server-spi/src/main/java/org/keycloak/storage/user/ImportSynchronization.java index 635da10b5a..0206d3cb2a 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/ImportSynchronization.java +++ b/server-spi/src/main/java/org/keycloak/storage/user/ImportSynchronization.java @@ -22,6 +22,11 @@ import org.keycloak.storage.UserStorageProviderModel; import java.util.Date; /** + * + * This is an optional capability interface that is intended to be implemented by any + * {@link org.keycloak.storage.UserStorageProvider UserStorageProvider} that supports syncing users to keycloak local + * storage. You must implement this interface if you want to be able to use sync functionality within the Admin console. + * * @author Bill Burke * @version $Revision: 1 $ */ diff --git a/server-spi/src/main/java/org/keycloak/storage/user/ImportedUserValidation.java b/server-spi/src/main/java/org/keycloak/storage/user/ImportedUserValidation.java index 7e374e39c0..dbd43e1dae 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/ImportedUserValidation.java +++ b/server-spi/src/main/java/org/keycloak/storage/user/ImportedUserValidation.java @@ -20,8 +20,12 @@ import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** - * If your UserStorageProvider is importing users into local storage, you can validate that import whenever the - * user is queried from local storage. + * This is an optional capability interface that is intended to be implemented by any + * {@link org.keycloak.storage.UserStorageProvider UserStorageProvider} that supports validating users. You must + * implement this interface if your storage imports users into the Keycloak local storage and you want to sync these + * users with your storage. The idea is, that whenever keycloak queries users imported from your storage, the method + * {@link #validate(RealmModel, UserModel) validate()} is called and if it returns null, the user is removed from + * local storage and reloaded from your storage by corresponding method. * * @author Bill Burke * @version $Revision: 1 $ diff --git a/server-spi/src/main/java/org/keycloak/storage/user/UserBulkUpdateProvider.java b/server-spi/src/main/java/org/keycloak/storage/user/UserBulkUpdateProvider.java index 843692ddfc..4ec605150e 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/UserBulkUpdateProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/user/UserBulkUpdateProvider.java @@ -20,6 +20,9 @@ import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; /** + * This is an optional capability interface that is intended to be implemented by any + * {@link org.keycloak.storage.UserStorageProvider UserStorageProvider} that supports bulk operations. + * * @author Bill Burke * @version $Revision: 1 $ */ diff --git a/server-spi/src/main/java/org/keycloak/storage/user/UserLookupProvider.java b/server-spi/src/main/java/org/keycloak/storage/user/UserLookupProvider.java index 4f405213d5..a8ab8e3057 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/UserLookupProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/user/UserLookupProvider.java @@ -20,23 +20,93 @@ import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** - * Optional capability interface implemented by UserStorageProviders. This interface is required - * if you want the UserStorageProvider to support basic login capabilities. + * This is an optional capability interface that is intended to be implemented by any + * {@link org.keycloak.storage.UserStorageProvider UserStorageProvider} that supports basic user querying. You must + * implement this interface if you want to be able to log in to keycloak using users from your storage. + *

+ * Note that all methods in this interface should limit search only to data available within the storage that is + * represented by this provider. They should not lookup other storage providers for additional information. + * Optional capability interface implemented by UserStorageProviders. * * @author Bill Burke * @version $Revision: 1 $ */ public interface UserLookupProvider { + + /** + * Returns a user with the given id belonging to the realm + * + * @param id id of the user + * @param realm the realm model + * @return found user model, or {@code null} if no such user exists + */ + default UserModel getUserById(RealmModel realm, String id) { + return getUserById(id, realm); + } + /** + * @deprecated Use {@link #getUserById(RealmModel, String) getUserById} instead. + */ + @Deprecated UserModel getUserById(String id, RealmModel realm); + /** + * Returns a user with the given username belonging to the realm + * + * @param username case insensitive username (case-sensitivity is controlled by storage) + * @param realm the realm model + * @return found user model, or {@code null} if no such user exists + */ + default UserModel getUserByUsername(RealmModel realm, String username) { + return getUserByUsername(username, realm); + } + /** + * @deprecated Use {@link #getUserByUsername(RealmModel, String) getUserByUsername} instead. + */ + @Deprecated UserModel getUserByUsername(String username, RealmModel realm); /** - * - * @param email - * @param realm + * Returns a user with the given email belonging to the realm + * + * @param email case insensitive email address (case-sensitivity is controlled by storage) + * @param realm the realm model + * @return found user model, or {@code null} if no such user exists + * * @throws org.keycloak.models.ModelDuplicateException when there are more users with same email - * @return */ + default UserModel getUserByEmail(RealmModel realm, String email) { + return getUserByEmail(email, realm); + } + /** + * @deprecated Use {@link #getUserByEmail(RealmModel, String) getUserByEmail} instead. + */ + @Deprecated UserModel getUserByEmail(String email, RealmModel realm); + + interface Streams extends UserLookupProvider { + @Override + UserModel getUserById(RealmModel realm, String id); + + @Override + default UserModel getUserById(String id, RealmModel realm) { + return getUserById(realm, id); + } + + @Override + UserModel getUserByUsername(RealmModel realm, String username); + + @Override + default UserModel getUserByUsername(String username, RealmModel realm) { + return getUserByUsername(realm, username); + } + + @Override + UserModel getUserByEmail(RealmModel realm, String email); + + @Override + default UserModel getUserByEmail(String email, RealmModel realm) { + return getUserByEmail(realm, email); + } + + } } diff --git a/server-spi/src/main/java/org/keycloak/storage/user/UserQueryProvider.java b/server-spi/src/main/java/org/keycloak/storage/user/UserQueryProvider.java index a36424714b..238a30a168 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/UserQueryProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/user/UserQueryProvider.java @@ -21,6 +21,7 @@ import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -28,9 +29,13 @@ import java.util.stream.Collectors; import java.util.stream.Stream; /** - * Optional capability interface implemented by UserStorageProviders. - * Defines complex queries that are used to locate one or more users. You must implement this interface - * if you want to view and manager users from the administration console. + * + * This is an optional capability interface that is intended to be implemented by any + * {@link org.keycloak.storage.UserStorageProvider UserStorageProvider} that supports complex user querying. You must + * implement this interface if you want to view and manage users from the administration console. + *

+ * Note that all methods in this interface should limit search only to data available within the storage that is + * represented by this provider. They should not lookup other storage providers for additional information. * * @author Bill Burke * @version $Revision: 1 $ @@ -43,14 +48,16 @@ public interface UserQueryProvider { * @param realm the realm * @return the number of users */ - int getUsersCount(RealmModel realm); + default int getUsersCount(RealmModel realm) { + return getUsersCount(realm, false); + } /** * Returns the number of users that are in at least one of the groups * given. * * @param realm the realm - * @param groupIds set of groups id to check for + * @param groupIds set of groups IDs, the returned user needs to belong to at least one of them * @return the number of users that are in at least one of the groups */ default int getUsersCount(RealmModel realm, Set groupIds) { @@ -61,41 +68,64 @@ public interface UserQueryProvider { } /** - * Returns the number of users that match the given criteria. + * Returns the number of users that would be returned by a call to {@link #searchForUserStream(RealmModel, String) searchForUserStream} * - * @param search search criteria * @param realm the realm + * @param search case insensitive list of strings separated by whitespaces. * @return number of users that match the search */ - default int getUsersCount(String search, RealmModel realm) { - return (int) searchForUserStream(search, realm).count(); + default int getUsersCount(RealmModel realm, String search) { + return getUsersCount(search, realm); } /** - * Returns the number of users that match the given criteria and are in - * at least one of the groups given. + * @deprecated Use {@link #getUsersCount(RealmModel, String) getUsersCount} + */ + @Deprecated + default int getUsersCount(String search, RealmModel realm) { + return (int) searchForUserStream(realm, search).count(); + } + + /** + * Returns the number of users that would be returned by a call to {@link #searchForUserStream(RealmModel, String) searchForUserStream} + * and are members of at least one of the groups given by the {@code groupIds} set. * - * @param search search criteria * @param realm the realm - * @param groupIds set of groups to check for + * @param search case insensitive list of strings separated by whitespaces. + * @param groupIds set of groups IDs, the returned user needs to belong to at least one of them * @return number of users that match the search and given groups */ + default int getUsersCount(RealmModel realm, String search, Set groupIds) { + return getUsersCount(search, realm, groupIds); + } + + /** + * @deprecated Use {@link #getUsersCount(RealmModel, String, Set) getUsersCount} instead. + */ + @Deprecated default int getUsersCount(String search, RealmModel realm, Set groupIds) { if (groupIds == null || groupIds.isEmpty()) { return 0; } - return countUsersInGroups(searchForUserStream(search, realm), groupIds); + return countUsersInGroups(searchForUserStream(realm, search), groupIds); } /** * Returns the number of users that match the given filter parameters. * - * @param params filter parameters * @param realm the realm + * @param params filter parameters * @return number of users that match the given filters */ + default int getUsersCount(RealmModel realm, Map params) { + return getUsersCount(params, realm); + } + /** + * @deprecated Use {@link #getUsersCount(RealmModel, Set) getUsersCount} instead. + */ + @Deprecated default int getUsersCount(Map params, RealmModel realm) { - return (int) searchForUserStream(params, realm).count(); + return (int) searchForUserStream(realm, params).count(); } /** @@ -107,13 +137,21 @@ public interface UserQueryProvider { * @param groupIds set if groups to check for * @return number of users that match the given filters and groups */ + default int getUsersCount(RealmModel realm, Map params, Set groupIds) { + return getUsersCount(params, realm, groupIds); + } + /** + * @deprecated Use {@link #getUsersCount(RealmModel, Map, Set) getUsersCount} instead. + */ + @Deprecated default int getUsersCount(Map params, RealmModel realm, Set groupIds) { if (groupIds == null || groupIds.isEmpty()) { return 0; } - return countUsersInGroups(searchForUserStream(params, realm), groupIds); + return countUsersInGroups(searchForUserStream(realm, params), groupIds); } + /** * Returns the number of users from the given list of users that are in at * least one of the groups given in the groups set. @@ -154,7 +192,7 @@ public interface UserQueryProvider { } /** - * @deprecated Use {@link #getUsersStream(RealmModel, int, int) getUsersStream} instead. + * @deprecated Use {@link #getUsersStream(RealmModel, Integer, Integer) getUsersStream} instead. */ @Deprecated List getUsers(RealmModel realm, int firstResult, int maxResults); @@ -163,184 +201,221 @@ public interface UserQueryProvider { * Searches all users in the realm, starting from the {@code firstResult} and containing at most {@code maxResults}. * * @param realm a reference to the realm. - * @param firstResult first result to return. Ignored if negative. + * @param firstResult first result to return. Ignored if negative or zero. * @param maxResults maximum number of results to return. Ignored if negative. * @return a non-null {@link Stream} of users. */ - default Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { - List value = this.getUsers(realm, firstResult, maxResults); + default Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { + List value = this.getUsers(realm, firstResult == null ? -1 : firstResult, + maxResults == null ? -1 : maxResults); return value != null ? value.stream() : Stream.empty(); } /** - * Search for users with username, email or first + last name that is like search string. - * + * Searches for users whose username, email, first name or last name contain any of the strings in {@code search} separated by whitespace. + *

* If possible, implementations should treat the parameter values as partial match patterns i.e. in RDMBS terms use LIKE. - * + *

* This method is used by the admin console search box * - * @param search - * @param realm - * @return - * @deprecated Use {@link #searchForUserStream(String, RealmModel) searchForUserStream} instead. + * @param search case insensitive list of string separated by whitespaces. + * @param realm realm to search within + * @return list of users that satisfies the given search condition + * + * @deprecated Use {@link #searchForUserStream(RealmModel, String) searchForUserStream} instead. */ @Deprecated List searchForUser(String search, RealmModel realm); /** - * Searches for users with username, email or first + last name that is like search string. If possible, implementations - * should treat the parameter values as partial match patterns (i.e. in RDMBS terms use LIKE). + * Searches for users whose username, email, first name or last name contain any of the strings in {@code search} separated by whitespace. + *

+ * If possible, implementations should treat the parameter values as partial match patterns (i.e. in RDMBS terms use LIKE). *

* This method is used by the admin console search box * - * @param search case sensitive search string. * @param realm a reference to the realm. + * @param search case insensitive list of string separated by whitespaces. * @return a non-null {@link Stream} of users that match the search string. */ - default Stream searchForUserStream(String search, RealmModel realm) { + default Stream searchForUserStream(RealmModel realm, String search) { List value = this.searchForUser(search, realm); return value != null ? value.stream() : Stream.empty(); } /** - * Search for users with username, email or first + last name that is like search string. - * + * Searches for users whose username, email, first name or last name contain any of the strings in {@code search} separated by whitespace. + * The resulting user list should be paginated with respect to parameters {@code firstResult} and {@code maxResults} + *

* If possible, implementations should treat the parameter values as partial match patterns i.e. in RDMBS terms use LIKE. - * + *

* This method is used by the admin console search box * - * @param search - * @param realm - * @param firstResult - * @param maxResults - * @return - * @deprecated Use {@link #searchForUserStream(String, RealmModel, Integer, Integer) searchForUserStream} instead. + * @param search case insensitive list of string separated by whitespaces. + * @param realm a reference to the realm + * @param firstResult first result to return. Ignored if negative or zero. + * @param maxResults maximum number of results to return. Ignored if negative. + * @return paginated list of users from the realm that satisfies given search + * + * @deprecated Use {@link #searchForUserStream(RealmModel, String, Integer, Integer) searchForUserStream} instead. */ @Deprecated List searchForUser(String search, RealmModel realm, int firstResult, int maxResults); /** - * Searches for users with username, email or first + last name that is like search string. If possible, implementations - * should treat the parameter values as partial match patterns (i.e. in RDMBS terms use LIKE). + * Searches for users whose username, email, first name or last name contain any of the strings in {@code search} separated by whitespace. + *

+ * If possible, implementations should treat the parameter values as partial match patterns (i.e. in RDMBS terms use LIKE). *

* This method is used by the admin console search box * - * @param search case sensitive search string. * @param realm a reference to the realm. - * @param firstResult first result to return. Ignored if negative. - * @param maxResults maximum number of results to return. Ignored if negative. + * @param search case insensitive list of string separated by whitespaces. + * @param firstResult first result to return. Ignored if negative, zero, or {@code null}. + * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @return a non-null {@link Stream} of users that match the search criteria. */ - default Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + default Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { List value = this.searchForUser(search, realm, firstResult == null ? -1 : firstResult, maxResults == null ? -1 : maxResults); return value != null ? value.stream() : Stream.empty(); } /** - * Search for user by parameter. Valid parameters are: - * "first" - first name - * "last" - last name - * "email" - email - * "username" - username + * Search for user by a map of parameters. + *

+ * Valid parameters are: + *

    + *
  • {@link UserModel#FIRST_NAME} - first name (case insensitive string)
  • + *
  • {@link UserModel#LAST_NAME} - last name (case insensitive string)
  • + *
  • {@link UserModel#EMAIL} - email (case insensitive string)
  • + *
  • {@link UserModel#USERNAME} - username (case insensitive string)
  • + *
  • {@link UserModel#EMAIL_VERIFIED} - search only for users with verified/non-verified email (true/false)
  • + *
  • {@link UserModel#ENABLED} - search only for enabled/disabled users (true/false)
  • + *
  • {@link UserModel#IDP_ALIAS} - search only for users that have a federated identity + * from idp with the given alias configured (case sensitive string)
  • + *
  • {@link UserModel#IDP_USER_ID} - search for users with federated identity with + * the given userId (case sensitive string)
  • + *
* * If possible, implementations should treat the parameter values as partial match patterns i.e. in RDMBS terms use LIKE. - * + *

* This method is used by the REST API when querying users. * + * @param params a map containing the search parameters + * @param realm a reference to the realm + * @return list of users that satisfies given search conditions * - * @param params - * @param realm - * @return - * @deprecated Use {@link #searchForUserStream(Map, RealmModel) searchForUserStream} instead. + * @deprecated Use {@link #searchForUserStream(RealmModel, Map) searchForUserStream} instead. */ @Deprecated List searchForUser(Map params, RealmModel realm); /** - * Searches for user by parameter. If possible, implementations should treat the parameter values as partial match patterns - * (i.e. in RDMBS terms use LIKE). Valid parameters are: + * Searches for user by parameter. + * If possible, implementations should treat the parameter values as partial match patterns (i.e. in RDMBS terms use LIKE). + *

+ * Valid parameters are: *

    - *
  • first - first name
  • - *
  • last - last name
  • - *
  • email - email
  • - *
  • username - username
  • - *
  • enabled - if user is enabled (true/false)
  • + *
  • {@link UserModel#FIRST_NAME} - first name (case insensitive string)
  • + *
  • {@link UserModel#LAST_NAME} - last name (case insensitive string)
  • + *
  • {@link UserModel#EMAIL} - email (case insensitive string)
  • + *
  • {@link UserModel#USERNAME} - username (case insensitive string)
  • + *
  • {@link UserModel#EMAIL_VERIFIED} - search only for users with verified/non-verified email (true/false)
  • + *
  • {@link UserModel#ENABLED} - search only for enabled/disabled users (true/false)
  • + *
  • {@link UserModel#IDP_ALIAS} - search only for users that have a federated identity + * from idp with the given alias configured (case sensitive string)
  • + *
  • {@link UserModel#IDP_USER_ID} - search for users with federated identity with + * the given userId (case sensitive string)
  • *
+ * * This method is used by the REST API when querying users. * - * @param params a map containing the search parameters. * @param realm a reference to the realm. + * @param params a map containing the search parameters. * @return a non-null {@link Stream} of users that match the search parameters. */ - default Stream searchForUserStream(Map params, RealmModel realm) { + default Stream searchForUserStream(RealmModel realm, Map params) { List value = this.searchForUser(params, realm); return value != null ? value.stream() : Stream.empty(); } /** - * Search for user by parameter. Valid parameters are: - * "first" - first name - * "last" - last name - * "email" - email - * "username" - username - * "enabled" - is user enabled (true/false) + * Search for user by parameter. + *

+ * Valid parameters are: + *

    + *
  • {@link UserModel#FIRST_NAME} - first name (case insensitive string)
  • + *
  • {@link UserModel#LAST_NAME} - last name (case insensitive string)
  • + *
  • {@link UserModel#EMAIL} - email (case insensitive string)
  • + *
  • {@link UserModel#USERNAME} - username (case insensitive string)
  • + *
  • {@link UserModel#EMAIL_VERIFIED} - search only for users with verified/non-verified email (true/false)
  • + *
  • {@link UserModel#ENABLED} - search only for enabled/disabled users (true/false)
  • + *
  • {@link UserModel#IDP_ALIAS} - search only for users that have a federated identity + * from idp with the given alias configured (case sensitive string)
  • + *
  • {@link UserModel#IDP_USER_ID} - search for users with federated identity with + * the given userId (case sensitive string)
  • + *
* * If possible, implementations should treat the parameter values as patterns i.e. in RDMBS terms use LIKE. + *

* This method is used by the REST API when querying users. * + * @param params a map containing the search parameters. + * @param realm a reference to the realm. + * @param firstResult first result to return. Ignored if negative. + * @param maxResults maximum number of results to return. Ignored if negative. + * @return a non-null {@link Stream} of users that match the search criteria. * - * @param params - * @param realm - * @param firstResult - * @param maxResults - * @return - * @deprecated Use {@link #searchForUserStream(Map, RealmModel, Integer, Integer) searchForUserStream} instead. + * @deprecated Use {@link #searchForUserStream(RealmModel, Map, Integer, Integer) searchForUserStream} instead. */ @Deprecated List searchForUser(Map params, RealmModel realm, int firstResult, int maxResults); /** * Searches for user by parameter. If possible, implementations should treat the parameter values as partial match patterns - * (i.e. in RDMBS terms use LIKE). Valid parameters are: + * (i.e. in RDMBS terms use LIKE). + *

+ * Valid parameters are: *

    - *
  • first - first name
  • - *
  • last - last name
  • - *
  • email - email
  • - *
  • username - username
  • - *
  • enabled - if user is enabled (true/false)
  • + *
  • {@link UserModel#FIRST_NAME} - first name (case insensitive string)
  • + *
  • {@link UserModel#LAST_NAME} - last name (case insensitive string)
  • + *
  • {@link UserModel#EMAIL} - email (case insensitive string)
  • + *
  • {@link UserModel#USERNAME} - username (case insensitive string)
  • + *
  • {@link UserModel#EMAIL_VERIFIED} - search only for users with verified/non-verified email (true/false)
  • + *
  • {@link UserModel#ENABLED} - search only for enabled/disabled users (true/false)
  • + *
  • {@link UserModel#IDP_ALIAS} - search only for users that have a federated identity + * from idp with the given alias configured (case sensitive string)
  • + *
  • {@link UserModel#IDP_USER_ID} - search for users with federated identity with + * the given userId (case sensitive string)
  • *
+ * * This method is used by the REST API when querying users. * - * @param params a map containing the search parameters. * @param realm a reference to the realm. - * @param firstResult first result to return. Ignored if negative. - * @param maxResults maximum number of results to return. Ignored if negative. + * @param params a map containing the search parameters. + * @param firstResult first result to return. Ignored if negative, zero, or {@code null}. + * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @return a non-null {@link Stream} of users that match the search criteria. */ - default Stream searchForUserStream(Map params, RealmModel realm, Integer firstResult, Integer maxResults) { + default Stream searchForUserStream(RealmModel realm, Map params, Integer firstResult, Integer maxResults) { List value = this.searchForUser(params, realm, firstResult == null ? -1 : firstResult, maxResults == null ? -1 : maxResults); return value != null ? value.stream() : Stream.empty(); } /** - * Get users that belong to a specific group. Implementations do not have to search in UserFederatedStorageProvider - * as this is done automatically. + * Get users that belong to a specific group. * - * @see org.keycloak.storage.federated.UserFederatedStorageProvider + * @param realm a reference to the realm + * @param group a reference to the group + * @return a list of all users that are members of the given group * - * @param realm - * @param group - * @return * @deprecated Use {@link #getGroupMembersStream(RealmModel, GroupModel) getGroupMembersStream} instead. */ @Deprecated List getGroupMembers(RealmModel realm, GroupModel group); /** - * Obtains users that belong to a specific group. Implementations do not have to search in {@code UserFederatedStorageProvider} - * as this is done automatically. - * - * @see org.keycloak.storage.federated.UserFederatedStorageProvider + * Obtains users that belong to a specific group. * * @param realm a reference to the realm. * @param group a reference to the group. @@ -352,31 +427,26 @@ public interface UserQueryProvider { } /** - * Get users that belong to a specific group. Implementations do not have to search in UserFederatedStorageProvider - * as this is done automatically. + * Gets paginated list of users that belong to a specific group. * - * @see org.keycloak.storage.federated.UserFederatedStorageProvider + * @param realm a reference to the realm + * @param group a reference to the group + * @param firstResult first result to return. Ignored if negative or zero. + * @param maxResults maximum number of results to return. Ignored if negative. + * @return paginated list of members of the given group * - * @param realm - * @param group - * @param firstResult - * @param maxResults - * @return * @deprecated Use {@link #getGroupMembersStream(RealmModel, GroupModel, Integer, Integer) getGroupMembersStream} instead. */ @Deprecated List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults); /** - * Obtains users that belong to a specific group. Implementations do not have to search in {@code UserFederatedStorageProvider} - * as this is done automatically. - * - * @see org.keycloak.storage.federated.UserFederatedStorageProvider + * Obtains users that belong to a specific group. * * @param realm a reference to the realm. * @param group a reference to the group. - * @param firstResult first result to return. Ignored if negative. - * @param maxResults maximum number of results to return. Ignored if negative. + * @param firstResult first result to return. Ignored if negative, zero, or {@code null}. + * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @return a non-null {@link Stream} of users that belong to the group. */ default Stream getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { @@ -387,9 +457,10 @@ public interface UserQueryProvider { /** * Get users that belong to a specific role. * - * @param realm - * @param role - * @return + * @param realm a reference to the realm + * @param role a reference to the role + * @return a list of users that has the given role assigned + * * @deprecated Use {@link #getRoleMembersStream(RealmModel, RoleModel) getRoleMembersStream} instead. */ @Deprecated @@ -411,15 +482,17 @@ public interface UserQueryProvider { /** * Search for users that have a specific role with a specific roleId. * - * @param role - * @param firstResult - * @param maxResults - * @return + * @param realm a reference to the realm + * @param role a reference to the role + * @param firstResult first result to return. Ignored if negative or zero. + * @param maxResults maximum number of results to return. Ignored if negative. + * @return a paginated list of users that has the given role assigned + * * @deprecated Use {@link #getRoleMembersStream(RealmModel, RoleModel, Integer, Integer) getRoleMembersStream} instead. */ @Deprecated default List getRoleMembers(RealmModel realm, RoleModel role, int firstResult, int maxResults) { - return this.getRoleMembersStream(realm, role, firstResult, maxResults).collect(Collectors.toList()); + return Collections.emptyList(); } /** @@ -432,38 +505,33 @@ public interface UserQueryProvider { * @return a non-null {@link Stream} of users that have the specified role. */ default Stream getRoleMembersStream(RealmModel realm, RoleModel role, Integer firstResult, Integer maxResults) { - return Stream.empty(); + return getRoleMembers(realm, role, firstResult == null ? -1 : firstResult, maxResults== null ? -1 : maxResults) + .stream(); } /** * Search for users that have a specific attribute with a specific value. - * Implementations do not have to search in UserFederatedStorageProvider - * as this is done automatically. * - * @see org.keycloak.storage.federated.UserFederatedStorageProvider + * @param attrName a name of the attribute that will be searched + * @param attrValue a value of the attribute that will be searched + * @param realm a reference to the realm + * @return list of users with the given attribute name and value * - * @param attrName - * @param attrValue - * @param realm - * @return - * @deprecated Use {@link #searchForUserByUserAttributeStream(String, String, RealmModel) searchForUserByUserAttributeStream} + * @deprecated Use {@link #searchForUserByUserAttributeStream(RealmModel, String, String) searchForUserByUserAttributeStream} * instead. */ @Deprecated List searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm); /** - * Searches for users that have a specific attribute with a specific value. Implementations do not have to search in - * {@code UserFederatedStorageProvider} as this is done automatically. - * - * @see org.keycloak.storage.federated.UserFederatedStorageProvider + * Searches for users that have a specific attribute with a specific value. * + * @param realm a reference to the realm. * @param attrName the attribute name. * @param attrValue the attribute value. - * @param realm a reference to the realm. * @return a non-null {@link Stream} of users that match the search criteria. */ - default Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + default Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { List value = this.searchForUserByUserAttribute(attrName, attrValue, realm); return value != null ? value.stream() : Stream.empty(); } @@ -476,13 +544,62 @@ public interface UserQueryProvider { * from the potential memory and performance optimizations of that approach. */ interface Streams extends UserQueryProvider { + + @Override + default int getUsersCount(RealmModel realm, String search) { + return (int) searchForUserStream(realm, search).count(); + } + + @Override + default int getUsersCount(String search, RealmModel realm) { + return getUsersCount(realm, search); + } + + @Override + default int getUsersCount(RealmModel realm, String search, Set groupIds) { + if (groupIds == null || groupIds.isEmpty()) { + return 0; + } + return countUsersInGroups(searchForUserStream(realm, search), groupIds); + } + + @Override + default int getUsersCount(String search, RealmModel realm, Set groupIds) { + return getUsersCount(realm, search, groupIds); + } + + @Override + default int getUsersCount(RealmModel realm, Map params) { + return (int) searchForUserStream(realm, params).count(); + } + + @Override + default int getUsersCount( Map params, RealmModel realm) { + return getUsersCount(realm, params); + } + + @Override + default int getUsersCount(RealmModel realm, Map params, Set groupIds) { + if (groupIds == null || groupIds.isEmpty()) { + return 0; + } + return countUsersInGroups(searchForUserStream(realm, params), groupIds); + } + + @Override + default int getUsersCount(Map params, RealmModel realm, Set groupIds) { + return getUsersCount(realm, params, groupIds); + } + @Override default List getUsers(RealmModel realm) { return this.getUsersStream(realm).collect(Collectors.toList()); } @Override - Stream getUsersStream(RealmModel realm); + default Stream getUsersStream(RealmModel realm) { + return getUsersStream(realm, null, null); + } @Override default List getUsers(RealmModel realm, int firstResult, int maxResults) { @@ -490,39 +607,43 @@ public interface UserQueryProvider { } @Override - Stream getUsersStream(RealmModel realm, int firstResult, int maxResults); + Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults); @Override default List searchForUser(String search, RealmModel realm) { - return this.searchForUserStream(search, realm).collect(Collectors.toList()); + return this.searchForUserStream(realm, search).collect(Collectors.toList()); } @Override - Stream searchForUserStream(String search, RealmModel realm); + default Stream searchForUserStream(RealmModel realm, String search) { + return searchForUserStream(realm, search, null, null); + } @Override default List searchForUser(String search, RealmModel realm, int firstResult, int maxResults) { - return this.searchForUserStream(search, realm, firstResult, maxResults).collect(Collectors.toList()); + return this.searchForUserStream(realm, search, firstResult, maxResults).collect(Collectors.toList()); } @Override - Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults); + Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults); @Override default List searchForUser(Map params, RealmModel realm) { - return this.searchForUserStream(params, realm).collect(Collectors.toList()); + return this.searchForUserStream(realm, params).collect(Collectors.toList()); } @Override - Stream searchForUserStream(Map params, RealmModel realm); + default Stream searchForUserStream(RealmModel realm, Map params) { + return searchForUserStream(realm, params, null, null); + } @Override default List searchForUser(Map params, RealmModel realm, int firstResult, int maxResults) { - return this.searchForUserStream(params, realm, firstResult, maxResults).collect(Collectors.toList()); + return this.searchForUserStream(realm, params, firstResult, maxResults).collect(Collectors.toList()); } @Override - Stream searchForUserStream(Map params, RealmModel realm, Integer firstResult, Integer maxResults); + Stream searchForUserStream(RealmModel realm, Map params, Integer firstResult, Integer maxResults); @Override default List getGroupMembers(RealmModel realm, GroupModel group) { @@ -530,7 +651,9 @@ public interface UserQueryProvider { } @Override - Stream getGroupMembersStream(RealmModel realm, GroupModel group); + default Stream getGroupMembersStream(RealmModel realm, GroupModel group) { + return this.getGroupMembersStream(realm, group, null, null); + } @Override default List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { @@ -542,10 +665,10 @@ public interface UserQueryProvider { @Override default List searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) { - return this.searchForUserByUserAttributeStream(attrName, attrValue, realm).collect(Collectors.toList()); + return this.searchForUserByUserAttributeStream(realm, attrName, attrValue).collect(Collectors.toList()); } @Override - Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm); + Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue); } } diff --git a/server-spi/src/main/java/org/keycloak/storage/user/UserRegistrationProvider.java b/server-spi/src/main/java/org/keycloak/storage/user/UserRegistrationProvider.java index 650f8b0c20..bd4dd5c4d8 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/UserRegistrationProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/user/UserRegistrationProvider.java @@ -21,8 +21,9 @@ import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; /** - * Optional capability interface implemented by UserStorageProviders. - * Implement this interface if your provider supports adding and removing users. + * This is an optional capability interface that is intended to be implemented by any + * {@link org.keycloak.storage.UserStorageProvider UserStorageProvider} that supports addition of new users. You must + * implement this interface if you want to use this storage for registering new users. * * @author Bill Burke * @version $Revision: 1 $ @@ -37,9 +38,9 @@ public interface UserRegistrationProvider { * Returning null is useful when you want optional support for adding users. For example, * our LDAP provider can enable and disable the ability to add users. * - * @param realm - * @param username - * @return + * @param realm a reference to the realm + * @param username a username the created user will be assigned + * @return a model of created user */ UserModel addUser(RealmModel realm, String username); @@ -54,9 +55,9 @@ public interface UserRegistrationProvider { * this method will be called before local storage's removeUser() method is invoked. Also, * you DO NOT need to remove the imported user. The runtime will handle this for you. * - * @param realm - * @param user - * @return + * @param realm a reference to the realm + * @param user a reference to the user that is removed + * @return true if the user was removed, false otherwise */ boolean removeUser(RealmModel realm, UserModel user); diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/broker/AbstractIdpAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/broker/AbstractIdpAuthenticator.java index 0402fedc50..12889cc1a1 100644 --- a/services/src/main/java/org/keycloak/authentication/authenticators/broker/AbstractIdpAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/broker/AbstractIdpAuthenticator.java @@ -123,7 +123,7 @@ public abstract class AbstractIdpAuthenticator implements Authenticator { ExistingUserInfo duplication = ExistingUserInfo.deserialize(existingUserId); - UserModel existingUser = session.users().getUserById(duplication.getExistingUserId(), realm); + UserModel existingUser = session.users().getUserById(realm, duplication.getExistingUserId()); if (existingUser == null) { throw new AuthenticationFlowException("User with ID '" + existingUserId + "' not found.", AuthenticationFlowError.INVALID_USER); } diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/broker/IdpCreateUserIfUniqueAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/broker/IdpCreateUserIfUniqueAuthenticator.java index e6ba64a492..0ffe4185bd 100644 --- a/services/src/main/java/org/keycloak/authentication/authenticators/broker/IdpCreateUserIfUniqueAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/broker/IdpCreateUserIfUniqueAuthenticator.java @@ -120,13 +120,13 @@ public class IdpCreateUserIfUniqueAuthenticator extends AbstractIdpAuthenticator protected ExistingUserInfo checkExistingUser(AuthenticationFlowContext context, String username, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) { if (brokerContext.getEmail() != null && !context.getRealm().isDuplicateEmailsAllowed()) { - UserModel existingUser = context.getSession().users().getUserByEmail(brokerContext.getEmail(), context.getRealm()); + UserModel existingUser = context.getSession().users().getUserByEmail(context.getRealm(), brokerContext.getEmail()); if (existingUser != null) { return new ExistingUserInfo(existingUser.getId(), UserModel.EMAIL, existingUser.getEmail()); } } - UserModel existingUser = context.getSession().users().getUserByUsername(username, context.getRealm()); + UserModel existingUser = context.getSession().users().getUserByUsername(context.getRealm(), username); if (existingUser != null) { return new ExistingUserInfo(existingUser.getId(), UserModel.USERNAME, existingUser.getUsername()); } diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnAuthenticator.java index d8bd647433..e9ff73cfcd 100644 --- a/services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnAuthenticator.java @@ -180,7 +180,7 @@ public class WebAuthnAuthenticator implements Authenticator, CredentialValidator String userVerificationRequirement = getWebAuthnPolicy(context).getUserVerificationRequirement(); if (WebAuthnConstants.OPTION_REQUIRED.equals(userVerificationRequirement)) isUVFlagChecked = true; - UserModel user = session.users().getUserById(userId, context.getRealm()); + UserModel user = session.users().getUserById(context.getRealm(), userId); AuthenticationRequest authenticationRequest = new AuthenticationRequest( credentialId, diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetCredentialChooseUser.java b/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetCredentialChooseUser.java index 8a31bf4e4a..acaffc3f85 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetCredentialChooseUser.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetCredentialChooseUser.java @@ -65,7 +65,7 @@ public class ResetCredentialChooseUser implements Authenticator, AuthenticatorFa String actionTokenUserId = context.getAuthenticationSession().getAuthNote(DefaultActionTokenKey.ACTION_TOKEN_USER_ID); if (actionTokenUserId != null) { - UserModel existingUser = context.getSession().users().getUserById(actionTokenUserId, context.getRealm()); + UserModel existingUser = context.getSession().users().getUserById(context.getRealm(), actionTokenUserId); // Action token logics handles checks for user ID validity and user being enabled @@ -96,9 +96,9 @@ public class ResetCredentialChooseUser implements Authenticator, AuthenticatorFa username = username.trim(); RealmModel realm = context.getRealm(); - UserModel user = context.getSession().users().getUserByUsername(username, realm); + UserModel user = context.getSession().users().getUserByUsername(realm, username); if (user == null && realm.isLoginWithEmailAllowed() && username.contains("@")) { - user = context.getSession().users().getUserByEmail(username, realm); + user = context.getSession().users().getUserByEmail(realm, username); } context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username); diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/x509/UserIdentityToModelMapper.java b/services/src/main/java/org/keycloak/authentication/authenticators/x509/UserIdentityToModelMapper.java index 74b061b6e6..c0286e6784 100644 --- a/services/src/main/java/org/keycloak/authentication/authenticators/x509/UserIdentityToModelMapper.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/x509/UserIdentityToModelMapper.java @@ -63,7 +63,7 @@ public abstract class UserIdentityToModelMapper { if (_customAttributes.isEmpty() || userIdentityValues.isEmpty() || (_customAttributes.size() != userIdentityValues.size())) { return null; } - Stream usersStream = session.users().searchForUserByUserAttributeStream(_customAttributes.get(0), userIdentityValues.get(0), context.getRealm()); + Stream usersStream = session.users().searchForUserByUserAttributeStream(context.getRealm(), _customAttributes.get(0), userIdentityValues.get(0)); for (int i = 1; i <_customAttributes.size(); ++i) { String customAttribute = _customAttributes.get(i); diff --git a/services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java b/services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java index cbfd6a9f7d..163d5a1209 100644 --- a/services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java +++ b/services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java @@ -244,10 +244,10 @@ public class PolicyEvaluationService { UserSessionModel userSession = null; if (subject != null) { - UserModel userModel = keycloakSession.users().getUserById(subject, realm); + UserModel userModel = keycloakSession.users().getUserById(realm, subject); if (userModel == null) { - userModel = keycloakSession.users().getUserByUsername(subject, realm); + userModel = keycloakSession.users().getUserByUsername(realm, subject); } if (userModel != null) { diff --git a/services/src/main/java/org/keycloak/authorization/admin/ResourceSetService.java b/services/src/main/java/org/keycloak/authorization/admin/ResourceSetService.java index 9b60d9d102..9052c385c4 100644 --- a/services/src/main/java/org/keycloak/authorization/admin/ResourceSetService.java +++ b/services/src/main/java/org/keycloak/authorization/admin/ResourceSetService.java @@ -387,7 +387,7 @@ public class ResourceSetService { if (clientModel != null) { owner = clientModel.getId(); } else { - UserModel user = authorization.getKeycloakSession().users().getUserByUsername(owner, realm); + UserModel user = authorization.getKeycloakSession().users().getUserByUsername(realm, owner); if (user != null) { owner = user.getId(); diff --git a/services/src/main/java/org/keycloak/authorization/admin/representation/PolicyEvaluationResponseBuilder.java b/services/src/main/java/org/keycloak/authorization/admin/representation/PolicyEvaluationResponseBuilder.java index c6fe22b952..bba1ace1b4 100644 --- a/services/src/main/java/org/keycloak/authorization/admin/representation/PolicyEvaluationResponseBuilder.java +++ b/services/src/main/java/org/keycloak/authorization/admin/representation/PolicyEvaluationResponseBuilder.java @@ -199,8 +199,8 @@ public class PolicyEvaluationResponseBuilder { KeycloakSession keycloakSession = authorization.getKeycloakSession(); RealmModel realm = authorization.getRealm(); PermissionTicket ticket = tickets.get(0); - UserModel userOwner = keycloakSession.users().getUserById(ticket.getOwner(), realm); - UserModel requester = keycloakSession.users().getUserById(ticket.getRequester(), realm); + UserModel userOwner = keycloakSession.users().getUserById(realm, ticket.getOwner()); + UserModel requester = keycloakSession.users().getUserById(realm, ticket.getRequester()); String resourceOwner; if (userOwner != null) { resourceOwner = getUserEmailOrUserName(userOwner); diff --git a/services/src/main/java/org/keycloak/authorization/protection/permission/PermissionTicketService.java b/services/src/main/java/org/keycloak/authorization/protection/permission/PermissionTicketService.java index 46389a1c0a..85f33cc69a 100644 --- a/services/src/main/java/org/keycloak/authorization/protection/permission/PermissionTicketService.java +++ b/services/src/main/java/org/keycloak/authorization/protection/permission/PermissionTicketService.java @@ -91,9 +91,9 @@ public class PermissionTicketService { UserModel user = null; if(representation.getRequester() != null) - user = this.authorization.getKeycloakSession().userStorageManager().getUserById(representation.getRequester(), this.authorization.getRealm()); + user = this.authorization.getKeycloakSession().userStorageManager().getUserById(this.authorization.getRealm(), representation.getRequester()); else - user = this.authorization.getKeycloakSession().userStorageManager().getUserByUsername(representation.getRequesterName(), this.authorization.getRealm()); + user = this.authorization.getKeycloakSession().userStorageManager().getUserByUsername(this.authorization.getRealm(), representation.getRequesterName()); if (user == null) throw new ErrorResponseException("invalid_permission", "Requester does not exists in this server as user.", Response.Status.BAD_REQUEST); @@ -229,13 +229,13 @@ public class PermissionTicketService { private String getUserId(String userIdOrName) { UserProvider userProvider = authorization.getKeycloakSession().users(); RealmModel realm = authorization.getRealm(); - UserModel userModel = userProvider.getUserById(userIdOrName, realm); + UserModel userModel = userProvider.getUserById(realm, userIdOrName); if (userModel != null) { return userModel.getId(); } - userModel = userProvider.getUserByUsername(userIdOrName, realm); + userModel = userProvider.getUserByUsername(realm, userIdOrName); if (userModel != null) { return userModel.getId(); diff --git a/services/src/main/java/org/keycloak/broker/oidc/AbstractOAuth2IdentityProvider.java b/services/src/main/java/org/keycloak/broker/oidc/AbstractOAuth2IdentityProvider.java index bb5365bc64..c75e39c8fe 100755 --- a/services/src/main/java/org/keycloak/broker/oidc/AbstractOAuth2IdentityProvider.java +++ b/services/src/main/java/org/keycloak/broker/oidc/AbstractOAuth2IdentityProvider.java @@ -250,7 +250,7 @@ public abstract class AbstractOAuth2IdentityProvider socialLinkReps = session.users().getFederatedIdentitiesStream(user, realm) + List socialLinkReps = session.users().getFederatedIdentitiesStream(realm, user) .map(ExportUtils::exportSocialLink).collect(Collectors.toList()); if (socialLinkReps.size() > 0) { userRep.setFederatedIdentities(socialLinkReps); diff --git a/services/src/main/java/org/keycloak/forms/account/freemarker/model/AccountFederatedIdentityBean.java b/services/src/main/java/org/keycloak/forms/account/freemarker/model/AccountFederatedIdentityBean.java index 86bda0dad1..6a46bd344a 100755 --- a/services/src/main/java/org/keycloak/forms/account/freemarker/model/AccountFederatedIdentityBean.java +++ b/services/src/main/java/org/keycloak/forms/account/freemarker/model/AccountFederatedIdentityBean.java @@ -54,7 +54,7 @@ public class AccountFederatedIdentityBean { .map(provider -> { String providerId = provider.getAlias(); - FederatedIdentityModel identity = getIdentity(session.users().getFederatedIdentitiesStream(user, realm), providerId); + FederatedIdentityModel identity = getIdentity(session.users().getFederatedIdentitiesStream(realm, user), providerId); if (identity != null) { availableIdentities.getAndIncrement(); diff --git a/services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthorizationBean.java b/services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthorizationBean.java index 0ae4ee7cc3..c0aba8acf2 100755 --- a/services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthorizationBean.java +++ b/services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthorizationBean.java @@ -150,7 +150,7 @@ public class AuthorizationBean { private boolean granted; public RequesterBean(PermissionTicket ticket, AuthorizationProvider authorization) { - this.requester = authorization.getKeycloakSession().users().getUserById(ticket.getRequester(), authorization.getRealm()); + this.requester = authorization.getKeycloakSession().users().getUserById(authorization.getRealm(), ticket.getRequester()); granted = ticket.isGranted(); createdTimestamp = ticket.getCreatedTimestamp(); grantedTimestamp = ticket.getGrantedTimestamp(); @@ -236,7 +236,7 @@ public class AuthorizationBean { RealmModel realm = authorization.getRealm(); resourceServer = new ResourceServerBean(realm.getClientById(resource.getResourceServer())); this.resource = resource; - userOwner = authorization.getKeycloakSession().users().getUserById(resource.getOwner(), realm); + userOwner = authorization.getKeycloakSession().users().getUserById(realm, resource.getOwner()); if (userOwner == null) { clientOwner = realm.getClientById(resource.getOwner()); ownerName = clientOwner.getClientId(); diff --git a/services/src/main/java/org/keycloak/forms/login/freemarker/LoginFormsUtil.java b/services/src/main/java/org/keycloak/forms/login/freemarker/LoginFormsUtil.java index 6de31c05ee..15d69a33ef 100755 --- a/services/src/main/java/org/keycloak/forms/login/freemarker/LoginFormsUtil.java +++ b/services/src/main/java/org/keycloak/forms/login/freemarker/LoginFormsUtil.java @@ -54,12 +54,12 @@ public class LoginFormsUtil { throw new IllegalStateException("USERNAME_EDIT_DISABLED but username not known"); } - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); if (user == null || !user.isEnabled()) { throw new IllegalStateException("User " + username + " not found or disabled"); } - Set federatedIdentities = session.users().getFederatedIdentitiesStream(user, realm) + Set federatedIdentities = session.users().getFederatedIdentitiesStream(realm, user) .map(federatedIdentityModel -> federatedIdentityModel.getIdentityProvider()) .collect(Collectors.toSet()); diff --git a/services/src/main/java/org/keycloak/partialimport/UsersPartialImport.java b/services/src/main/java/org/keycloak/partialimport/UsersPartialImport.java index c03f0bed3c..7820462cd1 100755 --- a/services/src/main/java/org/keycloak/partialimport/UsersPartialImport.java +++ b/services/src/main/java/org/keycloak/partialimport/UsersPartialImport.java @@ -59,10 +59,10 @@ public class UsersPartialImport extends AbstractPartialImport userSetter) throws VerificationException { - UserModel user = userId == null ? null : session.users().getUserById(userId, realm); + UserModel user = userId == null ? null : session.users().getUserById(realm, userId); if (user == null) { throw new ExplainedVerificationException(Errors.USER_NOT_FOUND, Messages.INVALID_USER); diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountFormService.java b/services/src/main/java/org/keycloak/services/resources/account/AccountFormService.java index f943a7e793..269da3969b 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountFormService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountFormService.java @@ -709,11 +709,11 @@ public class AccountFormService extends AbstractSecuredLocalService { return account.setError(Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_REDIRECT_ERROR).createResponse(AccountPages.FEDERATED_IDENTITY); } case REMOVE: - FederatedIdentityModel link = session.users().getFederatedIdentity(user, providerId, realm); + FederatedIdentityModel link = session.users().getFederatedIdentity(realm, user, providerId); if (link != null) { // Removing last social provider is not possible if you don't have other possibility to authenticate - if (session.users().getFederatedIdentitiesStream(user, realm).count() > 1 || user.getFederationLink() != null || isPasswordSet(session, realm, user)) { + if (session.users().getFederatedIdentitiesStream(realm, user).count() > 1 || user.getFederationLink() != null || isPasswordSet(session, realm, user)) { session.users().removeFederatedIdentity(realm, user, providerId); logger.debugv("Social provider {0} removed successfully from user {1}", providerId, user.getUsername()); @@ -833,7 +833,7 @@ public class AccountFormService extends AbstractSecuredLocalService { Map filters = new HashMap<>(); filters.put(PermissionTicket.RESOURCE, resource.getId()); - filters.put(PermissionTicket.REQUESTER, session.users().getUserByUsername(requester, realm).getId()); + filters.put(PermissionTicket.REQUESTER, session.users().getUserByUsername(realm, requester).getId()); if (isRevoke) { filters.put(PermissionTicket.GRANTED, Boolean.TRUE.toString()); @@ -909,14 +909,14 @@ public class AccountFormService extends AbstractSecuredLocalService { } for (String id : userIds) { - UserModel user = session.users().getUserById(id, realm); + UserModel user = session.users().getUserById(realm, id); if (user == null) { - user = session.users().getUserByUsername(id, realm); + user = session.users().getUserByUsername(realm, id); } if (user == null) { - user = session.users().getUserByEmail(id, realm); + user = session.users().getUserByEmail(realm, id); } if (user == null) { diff --git a/services/src/main/java/org/keycloak/services/resources/account/LinkedAccountsResource.java b/services/src/main/java/org/keycloak/services/resources/account/LinkedAccountsResource.java index 9665ab5be6..866e84d2d2 100644 --- a/services/src/main/java/org/keycloak/services/resources/account/LinkedAccountsResource.java +++ b/services/src/main/java/org/keycloak/services/resources/account/LinkedAccountsResource.java @@ -119,7 +119,7 @@ public class LinkedAccountsResource { public SortedSet getLinkedAccounts(KeycloakSession session, RealmModel realm, UserModel user) { Set socialIds = findSocialIds(); return realm.getIdentityProvidersStream().filter(IdentityProviderModel::isEnabled) - .map(provider -> toLinkedAccountRepresentation(provider, socialIds, session.users().getFederatedIdentitiesStream(user, realm))) + .map(provider -> toLinkedAccountRepresentation(provider, socialIds, session.users().getFederatedIdentitiesStream(realm, user))) .collect(Collectors.toCollection(TreeSet::new)); } @@ -209,13 +209,13 @@ public class LinkedAccountsResource { return ErrorResponse.error(errorMessage, Response.Status.BAD_REQUEST); } - FederatedIdentityModel link = session.users().getFederatedIdentity(user, providerId, realm); + FederatedIdentityModel link = session.users().getFederatedIdentity(realm, user, providerId); if (link == null) { return ErrorResponse.error(Messages.FEDERATED_IDENTITY_NOT_ACTIVE, Response.Status.BAD_REQUEST); } // Removing last social provider is not possible if you don't have other possibility to authenticate - if (!(session.users().getFederatedIdentitiesStream(user, realm).count() > 1 || user.getFederationLink() != null || isPasswordSet())) { + if (!(session.users().getFederatedIdentitiesStream(realm, user).count() > 1 || user.getFederationLink() != null || isPasswordSet())) { return ErrorResponse.error(Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER, Response.Status.BAD_REQUEST); } diff --git a/services/src/main/java/org/keycloak/services/resources/account/resources/AbstractResourceService.java b/services/src/main/java/org/keycloak/services/resources/account/resources/AbstractResourceService.java index 447bff7674..5588bc6857 100644 --- a/services/src/main/java/org/keycloak/services/resources/account/resources/AbstractResourceService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/resources/AbstractResourceService.java @@ -149,7 +149,7 @@ public abstract class AbstractResourceService { } Permission(String userId, AuthorizationProvider provider) { - UserModel user = provider.getKeycloakSession().users().getUserById(userId, provider.getRealm()); + UserModel user = provider.getKeycloakSession().users().getUserById(provider.getRealm(), userId); setUsername(user.getUsername()); setFirstName(user.getFirstName()); diff --git a/services/src/main/java/org/keycloak/services/resources/account/resources/ResourceService.java b/services/src/main/java/org/keycloak/services/resources/account/resources/ResourceService.java index 451048458c..d9d70fb18a 100644 --- a/services/src/main/java/org/keycloak/services/resources/account/resources/ResourceService.java +++ b/services/src/main/java/org/keycloak/services/resources/account/resources/ResourceService.java @@ -220,10 +220,10 @@ public class ResourceService extends AbstractResourceService { private UserModel getUser(String requester) { UserProvider users = provider.getKeycloakSession().users(); - UserModel user = users.getUserByUsername(requester, provider.getRealm()); + UserModel user = users.getUserByUsername(provider.getRealm(), requester); if (user == null) { - user = users.getUserByEmail(requester, provider.getRealm()); + user = users.getUserByEmail(provider.getRealm(), requester); } if (user == null) { diff --git a/services/src/main/java/org/keycloak/services/resources/admin/AttackDetectionResource.java b/services/src/main/java/org/keycloak/services/resources/admin/AttackDetectionResource.java index 743e994638..ca374c1e72 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/AttackDetectionResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/AttackDetectionResource.java @@ -79,7 +79,7 @@ public class AttackDetectionResource { @NoCache @Produces(MediaType.APPLICATION_JSON) public Map bruteForceUserStatus(@PathParam("userId") String userId) { - UserModel user = session.users().getUserById(userId, realm); + UserModel user = session.users().getUserById(realm, userId); if (user == null) { auth.users().requireView(); } else { @@ -123,7 +123,7 @@ public class AttackDetectionResource { @Path("brute-force/users/{userId}") @DELETE public void clearBruteForceForUser(@PathParam("userId") String userId) { - UserModel user = session.users().getUserById(userId, realm); + UserModel user = session.users().getUserById(realm, userId); if (user == null) { auth.users().requireManage(); } else { diff --git a/services/src/main/java/org/keycloak/services/resources/admin/ClientScopeEvaluateResource.java b/services/src/main/java/org/keycloak/services/resources/admin/ClientScopeEvaluateResource.java index 61c5629785..c007f73e52 100644 --- a/services/src/main/java/org/keycloak/services/resources/admin/ClientScopeEvaluateResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/ClientScopeEvaluateResource.java @@ -160,7 +160,7 @@ public class ClientScopeEvaluateResource { throw new NotFoundException("No userId provided"); } - UserModel user = session.users().getUserById(userId, realm); + UserModel user = session.users().getUserById(realm, userId); if (user == null) { throw new NotFoundException("No user found"); } diff --git a/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java b/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java index 9835345490..7dee2ca66e 100644 --- a/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java @@ -215,7 +215,7 @@ public class IdentityProviderResource { private static void updateUsersAfterProviderAliasChange(Stream users, String oldProviderId, String newProviderId, RealmModel realm, KeycloakSession session) { users.forEach(user -> { - FederatedIdentityModel federatedIdentity = session.users().getFederatedIdentity(user, oldProviderId, realm); + FederatedIdentityModel federatedIdentity = session.users().getFederatedIdentity(realm, user, oldProviderId); if (federatedIdentity != null) { // Remove old link first session.users().removeFederatedIdentity(realm, user, oldProviderId); diff --git a/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java b/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java index 32dfaff595..e8962ddecd 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java @@ -380,7 +380,7 @@ public class UserResource { private Stream getFederatedIdentities(UserModel user) { Set idps = realm.getIdentityProvidersStream().map(IdentityProviderModel::getAlias).collect(Collectors.toSet()); - return session.users().getFederatedIdentitiesStream(user, realm) + return session.users().getFederatedIdentitiesStream(realm, user) .filter(identity -> idps.contains(identity.getIdentityProvider())) .map(ModelToRepresentation::toRepresentation); } @@ -397,7 +397,7 @@ public class UserResource { @NoCache public Response addFederatedIdentity(final @PathParam("provider") String provider, FederatedIdentityRepresentation rep) { auth.users().requireManage(user); - if (session.users().getFederatedIdentity(user, provider, realm) != null) { + if (session.users().getFederatedIdentity(realm, user, provider) != null) { return ErrorResponse.exists("User is already linked with provider"); } diff --git a/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java b/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java index 4560214528..375eaa5e92 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java @@ -133,12 +133,12 @@ public class UsersResource { } // Double-check duplicated username and email here due to federation - if (session.users().getUserByUsername(username, realm) != null) { + if (session.users().getUserByUsername(realm, username) != null) { return ErrorResponse.exists("User exists with same username"); } if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) { try { - if(session.users().getUserByEmail(rep.getEmail(), realm) != null) { + if(session.users().getUserByEmail(realm, rep.getEmail()) != null) { return ErrorResponse.exists("User exists with same email"); } } catch (ModelDuplicateException e) { @@ -192,7 +192,7 @@ public class UsersResource { */ @Path("{id}") public UserResource user(final @PathParam("id") String id) { - UserModel user = session.users().getUserById(id, realm); + UserModel user = session.users().getUserById(realm, id); if (user == null) { // we do this to make sure somebody can't phish ids if (auth.users().canQuery()) throw new NotFoundException("User not found"); @@ -251,7 +251,7 @@ public class UsersResource { if (search != null) { if (search.startsWith(SEARCH_ID_PARAMETER)) { UserModel userModel = - session.users().getUserById(search.substring(SEARCH_ID_PARAMETER.length()).trim(), realm); + session.users().getUserById(realm, search.substring(SEARCH_ID_PARAMETER.length()).trim()); if (userModel != null) { userModels = Stream.of(userModel); } @@ -341,12 +341,12 @@ public class UsersResource { if (search != null) { if (search.startsWith(SEARCH_ID_PARAMETER)) { - UserModel userModel = session.users().getUserById(search.substring(SEARCH_ID_PARAMETER.length()).trim(), realm); + UserModel userModel = session.users().getUserById(realm, search.substring(SEARCH_ID_PARAMETER.length()).trim()); return userModel != null && userPermissionEvaluator.canView(userModel) ? 1 : 0; } else if (userPermissionEvaluator.canView()) { - return session.users().getUsersCount(search.trim(), realm); + return session.users().getUsersCount(realm, search.trim()); } else { - return session.users().getUsersCount(search.trim(), realm, auth.groups().getGroupsWithViewPermission()); + return session.users().getUsersCount(realm, search.trim(), auth.groups().getGroupsWithViewPermission()); } } else if (last != null || first != null || email != null || username != null || emailVerified != null) { Map parameters = new HashMap<>(); @@ -366,9 +366,9 @@ public class UsersResource { parameters.put(UserModel.EMAIL_VERIFIED, emailVerified.toString()); } if (userPermissionEvaluator.canView()) { - return session.users().getUsersCount(parameters, realm); + return session.users().getUsersCount(realm, parameters); } else { - return session.users().getUsersCount(parameters, realm, auth.groups().getGroupsWithViewPermission()); + return session.users().getUsersCount(realm, parameters, auth.groups().getGroupsWithViewPermission()); } } else if (userPermissionEvaluator.canView()) { return session.users().getUsersCount(realm); @@ -388,7 +388,7 @@ public class UsersResource { } } - Stream userModels = session.users().searchForUserStream(attributes, realm, firstResult, maxResults); + Stream userModels = session.users().searchForUserStream(realm, attributes, firstResult, maxResults); return toRepresentation(realm, usersEvaluator, briefRepresentation, userModels); } diff --git a/services/src/main/java/org/keycloak/social/twitter/TwitterIdentityProvider.java b/services/src/main/java/org/keycloak/social/twitter/TwitterIdentityProvider.java index 680865b9aa..dba58ae7b7 100755 --- a/services/src/main/java/org/keycloak/social/twitter/TwitterIdentityProvider.java +++ b/services/src/main/java/org/keycloak/social/twitter/TwitterIdentityProvider.java @@ -122,7 +122,7 @@ public class TwitterIdentityProvider extends AbstractIdentityProviderBill Burke @@ -136,7 +137,7 @@ public class UserStorageManager extends AbstractStorageManager { RealmModel realmModel = session.realms().getRealm(realm.getId()); if (realmModel == null) return; - UserModel deletedUser = session.userLocalStorage().getUserById(userId, realmModel); + UserModel deletedUser = session.userLocalStorage().getUserById(realmModel, userId); if (deletedUser != null) { try { new UserManager(session).removeUser(realmModel, deletedUser, session.userLocalStorage()); @@ -161,10 +162,8 @@ public class UserStorageManager extends AbstractStorageManager query(Object provider); } - protected Stream query(PaginatedQuery pagedQuery, RealmModel realm, int firstResult, int maxResults) { - if (maxResults == 0) return Stream.empty(); - if (firstResult < 0) firstResult = 0; - if (maxResults < 0) maxResults = Integer.MAX_VALUE - 1; + protected Stream query(PaginatedQuery pagedQuery, RealmModel realm, Integer firstResult, Integer maxResults) { + if (maxResults != null && maxResults == 0) return Stream.empty(); Stream providersStream = Stream.concat(Stream.of((Object) localStorage()), getEnabledStorageProviders(realm, UserQueryProvider.class)); @@ -173,9 +172,7 @@ public class UserStorageManager extends AbstractStorageManager provider.getUserByUsername(username, realm)).findFirst().orElse(null); + provider -> provider.getUserByUsername(realm, username)).findFirst().orElse(null); } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { - UserModel user = localStorage().getUserByEmail(email, realm); + public UserModel getUserByEmail(RealmModel realm, String email) { + UserModel user = localStorage().getUserByEmail(realm, email); if (user != null) { user = importValidation(realm, user); // Case when email was changed directly in the userStorage and doesn't correspond anymore to the email from local DB @@ -268,17 +265,12 @@ public class UserStorageManager extends AbstractStorageManager provider.getUserByEmail(email, realm)).findFirst().orElse(null); + provider -> provider.getUserByEmail(realm, email)).findFirst().orElse(null); } /** {@link UserLookupProvider} methods implementations end here {@link UserQueryProvider} methods implementation start here */ - @Override - public Stream getGroupMembersStream(RealmModel realm, GroupModel group) { - return getGroupMembersStream(realm, group, -1, -1); - } - @Override public Stream getGroupMembersStream(final RealmModel realm, final GroupModel group, Integer firstResult, Integer maxResults) { Stream results = query((provider) -> { @@ -287,7 +279,7 @@ public class UserStorageManager extends AbstractStorageManager getUserById(id, realm)); + map(id -> getUserById(realm, id)); } return Stream.empty(); }, realm, firstResult, maxResults); @@ -295,11 +287,6 @@ public class UserStorageManager extends AbstractStorageManager getRoleMembersStream(RealmModel realm, RoleModel role) { - return getRoleMembersStream(realm, role, -1, -1); - } - @Override public Stream getRoleMembersStream(final RealmModel realm, final RoleModel role, Integer firstResult, Integer maxResults) { Stream results = query((provider) -> { @@ -314,19 +301,14 @@ public class UserStorageManager extends AbstractStorageManager getUsersStream(RealmModel realm) { - return getUsersStream(realm, false); + return getUsersStream(realm, null, null, false); } @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { return getUsersStream(realm, firstResult, maxResults, false); } - @Override - public Stream getUsersStream(RealmModel realm, boolean includeServiceAccounts) { - return getUsersStream(realm, 0, Integer.MAX_VALUE - 1, includeServiceAccounts); - } - @Override public Stream getUsersStream(final RealmModel realm, Integer firstResult, Integer maxResults, final boolean includeServiceAccounts) { Stream results = query((provider) -> { @@ -362,35 +344,30 @@ public class UserStorageManager extends AbstractStorageManager groupIds) { - return localStorage().getUsersCount(search, realm, groupIds); + public int getUsersCount(RealmModel realm, String search, Set groupIds) { + return localStorage().getUsersCount(realm, search, groupIds); } @Override // TODO: missing storageProviders count? - public int getUsersCount(Map params, RealmModel realm) { - return localStorage().getUsersCount(params, realm); + public int getUsersCount(RealmModel realm, Map params) { + return localStorage().getUsersCount(realm, params); } @Override // TODO: missing storageProviders count? - public int getUsersCount(Map params, RealmModel realm, Set groupIds) { - return localStorage().getUsersCount(params, realm, groupIds); + public int getUsersCount(RealmModel realm, Map params, Set groupIds) { + return localStorage().getUsersCount(realm, params, groupIds); } @Override - public Stream searchForUserStream(String search, RealmModel realm) { - return searchForUserStream(search, realm, 0, Integer.MAX_VALUE - 1); - } - - @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { Stream results = query((provider) -> { if (provider instanceof UserQueryProvider) { - return ((UserQueryProvider)provider).searchForUserStream(search, realm); + return ((UserQueryProvider)provider).searchForUserStream(realm, search); } return Stream.empty(); }, realm, firstResult, maxResults); @@ -398,18 +375,13 @@ public class UserStorageManager extends AbstractStorageManager searchForUserStream(Map attributes, RealmModel realm) { - return searchForUserStream(attributes, realm, 0, Integer.MAX_VALUE - 1); - } - - @Override - public Stream searchForUserStream(Map attributes, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, Map attributes, Integer firstResult, Integer maxResults) { Stream results = query((provider) -> { if (provider instanceof UserQueryProvider) { if (attributes.containsKey(UserModel.SEARCH)) { - return ((UserQueryProvider)provider).searchForUserStream(attributes.get(UserModel.SEARCH), realm); + return ((UserQueryProvider)provider).searchForUserStream(realm, attributes.get(UserModel.SEARCH)); } else { - return ((UserQueryProvider)provider).searchForUserStream(attributes, realm); + return ((UserQueryProvider)provider).searchForUserStream(realm, attributes); } } return Stream.empty(); @@ -419,18 +391,18 @@ public class UserStorageManager extends AbstractStorageManager searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { Stream results = query((provider) -> { if (provider instanceof UserQueryProvider) { - return ((UserQueryProvider)provider).searchForUserByUserAttributeStream(attrName, attrValue, realm); + return ((UserQueryProvider)provider).searchForUserByUserAttributeStream(realm, attrName, attrValue); } else if (provider instanceof UserFederatedStorageProvider) { return ((UserFederatedStorageProvider)provider).getUsersByUserAttributeStream(realm, attrName, attrValue) - .map(id -> getUserById(id, realm)) + .map(id -> getUserById(realm, id)) .filter(Objects::nonNull); } return Stream.empty(); - }, realm,0, Integer.MAX_VALUE - 1); + }, realm,null, null); // removeDuplicates method may cause concurrent issues, it should not be used on parallel streams results = removeDuplicates(results); @@ -594,14 +566,14 @@ public class UserStorageManager extends AbstractStorageManager getFederatedIdentitiesStream(UserModel user, RealmModel realm) { + public Stream getFederatedIdentitiesStream(RealmModel realm, UserModel user) { if (user == null) throw new IllegalStateException("Federated user no longer valid"); Stream stream = StorageId.isLocalStorage(user) ? - localStorage().getFederatedIdentitiesStream(user, realm) : Stream.empty(); + localStorage().getFederatedIdentitiesStream(realm, user) : Stream.empty(); if (getFederatedStorage() != null) stream = Stream.concat(stream, getFederatedStorage().getFederatedIdentitiesStream(user.getId(), realm)); return stream.distinct(); } @Override - public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) { + public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { if (user == null) throw new IllegalStateException("Federated user no longer valid"); if (StorageId.isLocalStorage(user)) { - FederatedIdentityModel model = localStorage().getFederatedIdentity(user, socialProvider, realm); + FederatedIdentityModel model = localStorage().getFederatedIdentity(realm, user, socialProvider); if (model != null) return model; } if (getFederatedStorage() != null) return getFederatedStorage().getFederatedIdentity(user.getId(), socialProvider, realm); diff --git a/services/src/main/java/org/keycloak/userprofile/LegacyUserProfileProvider.java b/services/src/main/java/org/keycloak/userprofile/LegacyUserProfileProvider.java index 2a52c4355b..562cbe05cf 100644 --- a/services/src/main/java/org/keycloak/userprofile/LegacyUserProfileProvider.java +++ b/services/src/main/java/org/keycloak/userprofile/LegacyUserProfileProvider.java @@ -95,7 +95,7 @@ public class LegacyUserProfileProvider implements UserProfileProvider { builder.addAttributeValidator().forAttribute(UserModel.USERNAME) .addSingleAttributeValueValidationFunction(Messages.MISSING_USERNAME, StaticValidators.isBlank()) .addSingleAttributeValueValidationFunction(Messages.USERNAME_EXISTS, - (value, o) -> session.users().getUserByUsername(value, realm) == null) + (value, o) -> session.users().getUserByUsername(realm, value) == null) .build(); } } diff --git a/services/src/main/java/org/keycloak/userprofile/validation/StaticValidators.java b/services/src/main/java/org/keycloak/userprofile/validation/StaticValidators.java index 7c3597cbde..4b98d9c6ed 100644 --- a/services/src/main/java/org/keycloak/userprofile/validation/StaticValidators.java +++ b/services/src/main/java/org/keycloak/userprofile/validation/StaticValidators.java @@ -55,7 +55,7 @@ public class StaticValidators { if (Validation.isBlank(value)) return true; return !(context.getCurrentProfile() != null && !value.equals(context.getCurrentProfile().getAttributes().getFirstAttribute(UserModel.USERNAME)) - && session.users().getUserByUsername(value, session.getContext().getRealm()) != null); + && session.users().getUserByUsername(session.getContext().getRealm(), value) != null); }; } @@ -80,7 +80,7 @@ public class StaticValidators { if (Validation.isBlank(value)) return true; RealmModel realm = session.getContext().getRealm(); if (!realm.isDuplicateEmailsAllowed()) { - UserModel userByEmail = session.users().getUserByEmail(value, realm); + UserModel userByEmail = session.users().getUserByEmail(realm, value); return !(realm.isRegistrationEmailAsUsername() && userByEmail != null && context.getCurrentProfile() != null && !userByEmail.getId().equals(context.getCurrentProfile().getId())); } return true; @@ -92,7 +92,7 @@ public class StaticValidators { if (Validation.isBlank(value)) return true; RealmModel realm = session.getContext().getRealm(); if (!realm.isDuplicateEmailsAllowed()) { - UserModel userByEmail = session.users().getUserByEmail(value, realm); + UserModel userByEmail = session.users().getUserByEmail(realm, value); // check for duplicated email return !(userByEmail != null && (context.getCurrentProfile() == null || !userByEmail.getId().equals(context.getCurrentProfile().getId()))); } @@ -104,7 +104,7 @@ public class StaticValidators { return (value, context) -> !(value != null && !session.getContext().getRealm().isDuplicateEmailsAllowed() - && session.users().getUserByEmail(value, session.getContext().getRealm()) != null); + && session.users().getUserByEmail(session.getContext().getRealm(), value) != null); } public static BiFunction, UserProfileContext, Boolean> isAttributeUnchanged(String attributeName) { diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/authentication/ExpectedParamAuthenticator.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/authentication/ExpectedParamAuthenticator.java index 08b475fbbb..dcb90821d0 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/authentication/ExpectedParamAuthenticator.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/authentication/ExpectedParamAuthenticator.java @@ -49,7 +49,7 @@ public class ExpectedParamAuthenticator implements Authenticator { if (loggedUser == null) { logger.info("Successfully authenticated, but don't set any authenticated user"); } else { - UserModel user = context.getSession().users().getUserByUsername(loggedUser, context.getRealm()); + UserModel user = context.getSession().users().getUserByUsername(context.getRealm(), loggedUser); logger.info("Successfully authenticated as user " + user.getUsername()); context.setUser(user); } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/BackwardsCompatibilityUserStorage.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/BackwardsCompatibilityUserStorage.java index 5c9ab87b59..a494e46775 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/BackwardsCompatibilityUserStorage.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/BackwardsCompatibilityUserStorage.java @@ -342,7 +342,7 @@ public class BackwardsCompatibilityUserStorage implements UserLookupProvider, Us @Override public List searchForUser(String search, RealmModel realm, int firstResult, int maxResults) { - UserModel user = getUserByUsername(search, realm); + UserModel user = getUserByUsername(realm, search); return user == null ? Collections.emptyList() : Arrays.asList(user); } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java index e0795ed775..4fcb221127 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java @@ -20,12 +20,10 @@ package org.keycloak.testsuite.federation; import org.keycloak.component.ComponentModel; import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialInputValidator; -import org.keycloak.credential.CredentialModel; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; -import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; import org.keycloak.models.credential.OTPCredentialModel; import org.keycloak.models.credential.PasswordCredentialModel; @@ -34,7 +32,6 @@ import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserRegistrationProvider; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -44,7 +41,7 @@ import java.util.Set; * @version $Revision: 1 $ */ public class DummyUserFederationProvider implements UserStorageProvider, - UserLookupProvider, + UserLookupProvider.Streams, UserRegistrationProvider, CredentialInputValidator { @@ -83,17 +80,17 @@ public class DummyUserFederationProvider implements UserStorageProvider, } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { return null; } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { return users.get(username); } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { return null; } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/FailableHardcodedStorageProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/FailableHardcodedStorageProvider.java index fc50470e60..6be7d93022 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/FailableHardcodedStorageProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/FailableHardcodedStorageProvider.java @@ -41,7 +41,7 @@ import java.util.stream.Stream; * @author Bill Burke * @version $Revision: 1 $ */ -public class FailableHardcodedStorageProvider implements UserStorageProvider, UserLookupProvider, UserQueryProvider.Streams, +public class FailableHardcodedStorageProvider implements UserStorageProvider, UserLookupProvider.Streams, UserQueryProvider.Streams, ImportedUserValidation, CredentialInputUpdater.Streams, CredentialInputValidator { public static String username = "billb"; @@ -172,16 +172,16 @@ public class FailableHardcodedStorageProvider implements UserStorageProvider, Us } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { checkForceFail(); throw new RuntimeException("THIS IMPORTS SHOULD NEVER BE CALLED"); } @Override - public UserModel getUserByUsername(String uname, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String uname) { checkForceFail(); if (!username.equals(uname)) return null; - UserModel local = session.userLocalStorage().getUserByUsername(uname, realm); + UserModel local = session.userLocalStorage().getUserByUsername(realm, uname); if (local != null && !model.getId().equals(local.getFederationLink())) { throw new RuntimeException("local storage has wrong federation link"); } @@ -201,7 +201,7 @@ public class FailableHardcodedStorageProvider implements UserStorageProvider, Us } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { checkForceFail(); return null; } @@ -223,46 +223,46 @@ public class FailableHardcodedStorageProvider implements UserStorageProvider, Us @Override public Stream getUsersStream(RealmModel realm) { checkForceFail(); - UserModel model = getUserByUsername(username, realm); + UserModel model = getUserByUsername(realm, username); return model != null ? Stream.of(model) : Stream.empty(); } @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { checkForceFail(); - UserModel model = getUserByUsername(username, realm); + UserModel model = getUserByUsername(realm, username); return model != null ? Stream.of(model) : Stream.empty(); } @Override - public Stream searchForUserStream(String search, RealmModel realm) { + public Stream searchForUserStream(RealmModel realm, String search) { checkForceFail(); if (!search.equals(username)) return Stream.empty(); - UserModel model = getUserByUsername(username, realm); + UserModel model = getUserByUsername(realm, username); return model != null ? Stream.of(model) : Stream.empty(); } @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { checkForceFail(); if (!search.equals(username)) return Stream.empty(); - UserModel model = getUserByUsername(username, realm); + UserModel model = getUserByUsername(realm, username); return model != null ? Stream.of(model) : Stream.empty(); } @Override - public Stream searchForUserStream(Map params, RealmModel realm) { + public Stream searchForUserStream(RealmModel realm, Map params) { checkForceFail(); if (!username.equals(params.get("username")))return Stream.empty(); - UserModel model = getUserByUsername(username, realm); + UserModel model = getUserByUsername(realm, username); return model != null ? Stream.of(model) : Stream.empty(); } @Override - public Stream searchForUserStream(Map params, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, Map params, Integer firstResult, Integer maxResults) { checkForceFail(); if (!username.equals(params.get("username")))return Stream.empty(); - UserModel model = getUserByUsername(username, realm); + UserModel model = getUserByUsername(realm, username); return model != null ? Stream.of(model) : Stream.empty(); } @@ -279,7 +279,7 @@ public class FailableHardcodedStorageProvider implements UserStorageProvider, Us } @Override - public Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { checkForceFail(); return Stream.empty(); } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/PassThroughFederatedUserStorageProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/PassThroughFederatedUserStorageProvider.java index 810310971d..2dcd7271c6 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/PassThroughFederatedUserStorageProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/PassThroughFederatedUserStorageProvider.java @@ -45,7 +45,7 @@ import java.util.stream.Collectors; */ public class PassThroughFederatedUserStorageProvider implements UserStorageProvider, - UserLookupProvider, + UserLookupProvider.Streams, CredentialInputValidator, CredentialInputUpdater { @@ -130,20 +130,20 @@ public class PassThroughFederatedUserStorageProvider implements } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { if (!StorageId.externalId(id).equals(PASSTHROUGH_USERNAME)) return null; return getUserModel(realm); } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { if (!PASSTHROUGH_USERNAME.equals(username)) return null; return getUserModel(realm); } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { Optional result = session.userFederatedStorage() .getUsersByUserAttributeStream(realm, AbstractUserAdapterFederatedStorage.EMAIL_ATTRIBUTE, email) .map(StorageId::new) diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserMapStorage.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserMapStorage.java index b8d538db77..793509436b 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserMapStorage.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserMapStorage.java @@ -48,12 +48,13 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.jboss.logging.Logger; import static org.keycloak.storage.UserStorageProviderModel.IMPORT_ENABLED; +import static org.keycloak.utils.StreamsUtil.paginatedStream; /** * @author Bill Burke * @version $Revision: 1 $ */ -public class UserMapStorage implements UserLookupProvider, UserStorageProvider, UserRegistrationProvider, CredentialInputUpdater.Streams, +public class UserMapStorage implements UserLookupProvider.Streams, UserStorageProvider, UserRegistrationProvider, CredentialInputUpdater.Streams, CredentialInputValidator, UserGroupMembershipFederatedStorage.Streams, UserQueryProvider.Streams, ImportedUserValidation { private static final Logger log = Logger.getLogger(UserMapStorage.class); @@ -91,7 +92,7 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, } @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { StorageId storageId = new StorageId(id); final String username = storageId.getExternalId(); if (!userPasswords.containsKey(translateUserName(username))) { @@ -199,7 +200,7 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, } @Override - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { if (!userPasswords.containsKey(translateUserName(username))) { return null; } @@ -208,7 +209,7 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { return null; } @@ -296,17 +297,14 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, } @Override - public Stream getUsersStream(RealmModel realm, int firstResult, int maxResults) { + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { Stream userStream = userPasswords.keySet().stream().sorted(); - if (firstResult > 0) - userStream = userStream.skip(firstResult); - if (maxResults >= 0) - userStream = userStream.limit(maxResults); - return userStream.map(userName -> createUser(realm, userName)); + + return paginatedStream(userStream, firstResult, maxResults).map(userName -> createUser(realm, userName)); } @Override - public Stream searchForUserStream(String search, RealmModel realm) { + public Stream searchForUserStream(RealmModel realm, String search) { String tSearch = translateUserName(search); return userPasswords.keySet().stream() .sorted() @@ -315,25 +313,17 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, } @Override - public Stream searchForUserStream(String search, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { String tSearch = translateUserName(search); Stream userStream = userPasswords.keySet().stream() .sorted() .filter(userName -> translateUserName(userName).contains(search)); - if (firstResult != null && firstResult > 0) - userStream = userStream.skip(firstResult); - if (maxResults != null && maxResults >= 0) - userStream = userStream.limit(maxResults); - return userStream.map(userName -> createUser(realm, userName)); + + return paginatedStream(userStream, firstResult, maxResults).map(userName -> createUser(realm, userName)); } @Override - public Stream searchForUserStream(Map params, RealmModel realm) { - return searchForUserStream(params, realm, 0, Integer.MAX_VALUE - 1); - } - - @Override - public Stream searchForUserStream(Map params, RealmModel realm, Integer firstResult, Integer maxResults) { + public Stream searchForUserStream(RealmModel realm, Map params, Integer firstResult, Integer maxResults) { Stream userStream = userPasswords.keySet().stream() .sorted(); @@ -356,28 +346,19 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, } } - if (firstResult != null && firstResult > 0) - userStream = userStream.skip(firstResult); - if (maxResults != null && maxResults >= 0) - userStream = userStream.limit(maxResults); - return userStream.map(userName -> createUser(realm, userName)); + return paginatedStream(userStream, firstResult, maxResults).map(userName -> createUser(realm, userName)); } @Override public Stream getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { - return getMembershipStream(realm, group, firstResult, maxResults) + return getMembershipStream(realm, group, firstResult == null ? -1 : firstResult, maxResults == null ? -1 : maxResults) .map(userName -> createUser(realm, userName)); } @Override - public Stream getGroupMembersStream(RealmModel realm, GroupModel group) { - return getGroupMembersStream(realm, group, 0, Integer.MAX_VALUE - 1); - } - - @Override - public Stream searchForUserByUserAttributeStream(String attrName, String attrValue, RealmModel realm) { + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { if (isImportEnabled()) { - return session.userLocalStorage().searchForUserByUserAttributeStream(attrName, attrValue, realm); + return session.userLocalStorage().searchForUserByUserAttributeStream(realm, attrName, attrValue); } else { return session.userFederatedStorage().getUsersByUserAttributeStream(realm, attrName, attrValue) .map(userName -> createUser(realm, userName)); @@ -409,15 +390,12 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, @Override public Stream getMembershipStream(RealmModel realm, GroupModel group, int firstResult, int max) { - Stream userStream = userGroups.entrySet().stream() + Stream userStream = paginatedStream(userGroups.entrySet().stream(), firstResult, max) .filter(me -> me.getValue().contains(group.getId())) .map(Map.Entry::getKey) .filter(realmUser -> realmUser.startsWith(realm.getId())) .map(realmUser -> realmUser.substring(realmUser.indexOf("/") + 1)); - if (firstResult > 0) - userStream = userStream.skip(firstResult); - if (max >= 0) - userStream = userStream.limit(max); + return userStream; } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserPropertyFileStorage.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserPropertyFileStorage.java index 25eabfc4b0..5e14a36822 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserPropertyFileStorage.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/UserPropertyFileStorage.java @@ -40,12 +40,15 @@ import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.function.Predicate; +import java.util.stream.Stream; + +import static org.keycloak.utils.StreamsUtil.paginatedStream; /** * @author Bill Burke * @version $Revision: 1 $ */ -public class UserPropertyFileStorage implements UserLookupProvider, UserStorageProvider, UserQueryProvider, CredentialInputValidator { +public class UserPropertyFileStorage implements UserLookupProvider.Streams, UserStorageProvider, UserQueryProvider.Streams, CredentialInputValidator { protected Properties userPasswords; protected ComponentModel model; @@ -61,7 +64,7 @@ public class UserPropertyFileStorage implements UserLookupProvider, UserStorageP @Override - public UserModel getUserById(String id, RealmModel realm) { + public UserModel getUserById(RealmModel realm, String id) { StorageId storageId = new StorageId(id); final String username = storageId.getExternalId(); if (!userPasswords.containsKey(username)) return null; @@ -92,14 +95,14 @@ public class UserPropertyFileStorage implements UserLookupProvider, UserStorageP } } - public UserModel getUserByUsername(String username, RealmModel realm) { + public UserModel getUserByUsername(RealmModel realm, String username) { if (!userPasswords.containsKey(username)) return null; return createUser(realm, username); } @Override - public UserModel getUserByEmail(String email, RealmModel realm) { + public UserModel getUserByEmail(RealmModel realm, String email) { return null; } @@ -145,67 +148,47 @@ public class UserPropertyFileStorage implements UserLookupProvider, UserStorageP } @Override - public List getUsers(RealmModel realm) { - List users = new LinkedList<>(); - for (Object username : userPasswords.keySet()) { - users.add(createUser(realm, (String)username)); - } - return users; + public Stream getUsersStream(RealmModel realm) { + return userPasswords.keySet().stream() + .map(username -> createUser(realm, (String) username)); } @Override - public List searchForUser(Map attributes, RealmModel realm) { - return searchForUser(attributes, realm, 0, Integer.MAX_VALUE - 1); + public Stream getUsersStream(RealmModel realm, Integer firstResult, Integer maxResults) { + if (maxResults != null && maxResults == 0) return Stream.empty(); + return paginatedStream(userPasswords.keySet().stream(), firstResult, maxResults) + .map(username -> createUser(realm, (String) username)); } @Override - public List getUsers(RealmModel realm, int firstResult, int maxResults) { - if (maxResults == 0) return Collections.EMPTY_LIST; - List users = new LinkedList<>(); - int count = 0; - for (Object un : userPasswords.keySet()) { - if (count++ < firstResult) continue; - String username = (String)un; - users.add(createUser(realm, username)); - if (users.size() + 1 > maxResults) break; - } - return users; + public Stream searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { + return searchForUser(realm, search, firstResult, maxResults, username -> username.contains(search)); } @Override - public List searchForUser(String search, RealmModel realm, int firstResult, int maxResults) { - return searchForUser(search, realm, firstResult, maxResults, username -> username.contains(search)); - } - - @Override - public List searchForUser(Map attributes, RealmModel realm, int firstResult, int maxResults) { + public Stream searchForUserStream(RealmModel realm, Map attributes, Integer firstResult, Integer maxResults) { String search = Optional.ofNullable(attributes.get(UserModel.USERNAME)) .orElseGet(()-> attributes.get(UserModel.SEARCH)); - if (search == null) return Collections.EMPTY_LIST; + if (search == null) return Stream.empty(); Predicate p = Boolean.valueOf(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString())) ? username -> username.equals(search) : username -> username.contains(search); - return searchForUser(search, realm, firstResult, maxResults, p); + return searchForUser(realm, search, firstResult, maxResults, p); } @Override - public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { - return Collections.EMPTY_LIST; + public Stream getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { + return Stream.empty(); } @Override - public List getGroupMembers(RealmModel realm, GroupModel group) { - return Collections.EMPTY_LIST; + public Stream getGroupMembersStream(RealmModel realm, GroupModel group) { + return Stream.empty(); } @Override - public List searchForUser(String search, RealmModel realm) { - return searchForUser(search, realm, 0, Integer.MAX_VALUE - 1); - } - - @Override - public List searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) { - return Collections.EMPTY_LIST; + public Stream searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { + return Stream.empty(); } @Override @@ -213,20 +196,11 @@ public class UserPropertyFileStorage implements UserLookupProvider, UserStorageP } - private List searchForUser(String search, RealmModel realm, int firstResult, int maxResults, Predicate matcher) { - if (maxResults == 0) return Collections.EMPTY_LIST; - List users = new LinkedList<>(); - int count = 0; - for (Object un : userPasswords.keySet()) { - String username = (String)un; - if (matcher.test(username)) { - if (count++ < firstResult) { - continue; - } - users.add(createUser(realm, username)); - if (users.size() + 1 > maxResults) break; - } - } - return users; + private Stream searchForUser(RealmModel realm, String search, Integer firstResult, Integer maxResults, Predicate matcher) { + if (maxResults != null && maxResults == 0) return Stream.empty(); + return paginatedStream(userPasswords.keySet().stream(), firstResult, maxResults) + .map(String.class::cast) + .filter(matcher) + .map(username -> createUser(realm, username)); } } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/sync/SyncDummyUserFederationProviderFactory.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/sync/SyncDummyUserFederationProviderFactory.java index ef3008b2a4..3486832c38 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/sync/SyncDummyUserFederationProviderFactory.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/sync/SyncDummyUserFederationProviderFactory.java @@ -90,7 +90,7 @@ public class SyncDummyUserFederationProviderFactory extends DummyUserFederationP // KEYCLOAK-2412 : Just remove and add some users for testing purposes for (int i = 0; i < 10; i++) { String username = "dummyuser-" + i; - UserModel user = session.userLocalStorage().getUserByUsername(username, realm); + UserModel user = session.userLocalStorage().getUserByUsername(realm, username); if (user != null) { session.userLocalStorage().removeUser(realm, user); diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java index 92cc19cf58..f86e15155f 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java @@ -592,7 +592,7 @@ public class TestingResourceProvider implements RealmResourceProvider { RealmModel realm = session.realms().getRealm(realmName); if (realm == null) return false; UserProvider userProvider = session.getProvider(UserProvider.class); - UserModel user = userProvider.getUserByUsername(userName, realm); + UserModel user = userProvider.getUserByUsername(realm, userName); return session.userCredentialManager().isValid(realm, user, UserCredentialModel.password(password)); } @@ -604,7 +604,7 @@ public class TestingResourceProvider implements RealmResourceProvider { @QueryParam("userId") String userId, @QueryParam("userName") String userName) { RealmModel realm = getRealmByName(realmName); - UserModel foundFederatedUser = session.users().getUserByFederatedIdentity(new FederatedIdentityModel(identityProvider, userId, userName), realm); + UserModel foundFederatedUser = session.users().getUserByFederatedIdentity(realm, new FederatedIdentityModel(identityProvider, userId, userName)); if (foundFederatedUser == null) return null; return ModelToRepresentation.toRepresentation(session, realm, foundFederatedUser); } @@ -616,7 +616,7 @@ public class TestingResourceProvider implements RealmResourceProvider { @QueryParam("userName") String userName) { RealmModel realm = getRealmByName(realmName); DummyUserFederationProviderFactory factory = (DummyUserFederationProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, "dummy"); - UserModel user = factory.create(session, null).getUserByUsername(userName, realm); + UserModel user = factory.create(session, null).getUserByUsername(realm, userName); if (user == null) return null; return ModelToRepresentation.toRepresentation(session, realm, user); } diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/runonserver/RunHelpers.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/runonserver/RunHelpers.java index ed5824cfcf..4187a9768c 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/runonserver/RunHelpers.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/runonserver/RunHelpers.java @@ -55,7 +55,7 @@ public class RunHelpers { public FetchOnServer getRunOnServer() { return (FetchOnServer) session -> { RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); List storedCredentialsByType = session.userCredentialManager() .getStoredCredentialsByTypeStream(realm, user, CredentialRepresentation.PASSWORD) .collect(Collectors.toList()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountFormServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountFormServiceTest.java index 5099d2b449..a1dd3cc995 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountFormServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountFormServiceTest.java @@ -481,7 +481,7 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest { final String uId = userId; // Needed for run-on-server testingClient.server("test").run(session -> { RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserById(uId, realm); + UserModel user = session.users().getUserById(realm, uId); assertThat(user, Matchers.notNullValue()); List storedCredentials = session.userCredentialManager() .getStoredCredentialsStream(realm, user).collect(Collectors.toList()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java index 5432226ad9..80a11ad1ae 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/FineGrainAdminUnitTest.java @@ -65,7 +65,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; @@ -331,7 +330,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { // test authorized { - UserModel user = session.users().getUserByUsername("authorized", realm); + UserModel user = session.users().getUserByUsername(realm, "authorized"); AdminPermissionEvaluator permissionsForAdmin = AdminPermissions.evaluator(session, realm, realm, user); Assert.assertTrue(permissionsForAdmin.users().canManage()); Assert.assertTrue(permissionsForAdmin.roles().canMapRole(realmRole)); @@ -340,7 +339,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { } // test composite role { - UserModel user = session.users().getUserByUsername("authorizedComposite", realm); + UserModel user = session.users().getUserByUsername(realm, "authorizedComposite"); AdminPermissionEvaluator permissionsForAdmin = AdminPermissions.evaluator(session, realm, realm, user); Assert.assertTrue(permissionsForAdmin.users().canManage()); Assert.assertTrue(permissionsForAdmin.roles().canMapRole(realmRole)); @@ -350,7 +349,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { // test unauthorized { - UserModel user = session.users().getUserByUsername("unauthorized", realm); + UserModel user = session.users().getUserByUsername(realm, "unauthorized"); AdminPermissionEvaluator permissionsForAdmin = AdminPermissions.evaluator(session, realm, realm, user); Assert.assertFalse(permissionsForAdmin.users().canManage()); Assert.assertFalse(permissionsForAdmin.roles().canMapRole(realmRole)); @@ -359,7 +358,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { } // test unauthorized mapper { - UserModel user = session.users().getUserByUsername("unauthorizedMapper", realm); + UserModel user = session.users().getUserByUsername(realm, "unauthorizedMapper"); AdminPermissionEvaluator permissionsForAdmin = AdminPermissions.evaluator(session, realm, realm, user); Assert.assertTrue(permissionsForAdmin.users().canManage()); Assert.assertFalse(permissionsForAdmin.roles().canMapRole(realmRole)); @@ -369,12 +368,12 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { } // test group management { - UserModel admin = session.users().getUserByUsername("groupManager", realm); + UserModel admin = session.users().getUserByUsername(realm, "groupManager"); AdminPermissionEvaluator permissionsForAdmin = AdminPermissions.evaluator(session, realm, realm, admin); - UserModel user = session.users().getUserByUsername("authorized", realm); + UserModel user = session.users().getUserByUsername(realm, "authorized"); Assert.assertFalse(permissionsForAdmin.users().canManage(user)); Assert.assertFalse(permissionsForAdmin.users().canView(user)); - UserModel member = session.users().getUserByUsername("groupMember", realm); + UserModel member = session.users().getUserByUsername(realm, "groupMember"); Assert.assertTrue(permissionsForAdmin.users().canManage(member)); Assert.assertTrue(permissionsForAdmin.users().canManageGroupMembership(member)); Assert.assertTrue(permissionsForAdmin.users().canView(member)); @@ -385,9 +384,9 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest { } // test client.mapRoles { - UserModel admin = session.users().getUserByUsername("clientMapper", realm); + UserModel admin = session.users().getUserByUsername(realm, "clientMapper"); AdminPermissionEvaluator permissionsForAdmin = AdminPermissions.evaluator(session, realm, realm, admin); - UserModel user = session.users().getUserByUsername("authorized", realm); + UserModel user = session.users().getUserByUsername(realm, "authorized"); Assert.assertTrue(permissionsForAdmin.users().canManage(user)); Assert.assertFalse(permissionsForAdmin.roles().canMapRole(realmRole)); Assert.assertTrue(permissionsForAdmin.roles().canMapRole(clientRole)); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java index aa718c73c9..977ac18e31 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ImpersonationTest.java @@ -281,7 +281,7 @@ public class ImpersonationTest extends AbstractKeycloakTest { final String userId = impersonatedUserId; final UserSessionNotesHolder notesHolder = testingClient.server("test").fetch(session -> { final RealmModel realm = session.realms().getRealmByName("test"); - final UserModel user = session.users().getUserById(userId, realm); + final UserModel user = session.users().getUserById(realm, userId); final UserSessionModel userSession = session.sessions().getUserSessionsStream(realm, user).findFirst().get(); return new UserSessionNotesHolder(userSession.getNotes()); }, UserSessionNotesHolder.class); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java index b76e76502a..d23b877427 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java @@ -563,7 +563,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest { public static void testCheckUserAttributes(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("authz-test"); - UserModel jdoe = session.users().getUserByUsername("jdoe", realm); + UserModel jdoe = session.users().getUserByUsername(realm, "jdoe"); jdoe.setAttribute("a1", Arrays.asList("1", "2")); jdoe.setSingleAttribute("a2", "3"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaRepresentationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaRepresentationTest.java index dc050c721f..a4747c9bbe 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaRepresentationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaRepresentationTest.java @@ -1,6 +1,5 @@ package org.keycloak.testsuite.authz; -import org.jboss.resteasy.spi.ResteasyUriInfo; import org.junit.Assert; import org.junit.Test; import org.keycloak.admin.client.resource.RealmResource; @@ -16,8 +15,6 @@ import org.keycloak.representations.idm.authorization.*; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer; -import java.net.URI; -import java.net.URISyntaxException; import java.util.List; @AuthServerContainerExclude(AuthServer.REMOTE) @@ -141,7 +138,7 @@ public class UmaRepresentationTest extends AbstractResourceServerTest { AuthorizationBean authorizationBean = new AuthorizationBean(session, null, session.getContext().getUri()); ClientModel client = session.getContext().getRealm().getClientByClientId("resource-server-test"); - UserModel user = session.userStorageManager().getUserByUsername("marta", session.getContext().getRealm()); + UserModel user = session.userStorageManager().getUserByUsername(session.getContext().getRealm(), "marta"); ResourceBean resourceBean = authorizationBean.new ResourceBean( authorization.getStoreFactory().getResourceStore().findByName( "Resource A", user.getId(), client.getId() diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java index cc57f31142..28fce3e61a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java @@ -169,9 +169,9 @@ public class AccountLinkTest extends AbstractKeycloakTest { private static void checkEmptyFederatedIdentities(KeycloakSession session) { RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserByUsername("child", realm); - assertEquals(0, session.users().getFederatedIdentitiesStream(user, realm).count()); - assertNull(session.users().getFederatedIdentity(user, PARENT_IDP, realm)); + UserModel user = session.users().getUserByUsername(realm, "child"); + assertEquals(0, session.users().getFederatedIdentitiesStream(realm, user).count()); + assertNull(session.users().getFederatedIdentity(realm, user, PARENT_IDP)); } protected void testAccountLink(String childUsername, String childPassword, String childIdp) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java index 3ea2533f35..21a5979792 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java @@ -83,7 +83,7 @@ final class BrokerRunOnServerUtil { RealmModel realm = session.getContext().getRealm(); ClientModel brokerClient = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID); RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE); - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); user.grantRole(readTokenRole); }; } @@ -93,7 +93,7 @@ final class BrokerRunOnServerUtil { RealmModel realm = session.getContext().getRealm(); ClientModel brokerClient = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID); RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE); - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); user.deleteRoleMapping(readTokenRole); }; } @@ -134,7 +134,7 @@ final class BrokerRunOnServerUtil { static RunOnServer assertHardCodedSessionNote() { return (session) -> { RealmModel realm = session.realms().getRealmByName("consumer"); - UserModel user = session.users().getUserByUsername("testuser", realm); + UserModel user = session.users().getUserByUsername(realm, "testuser"); UserSessionModel sessions = session.sessions().getUserSessionsStream(realm, user).findFirst().get(); assertEquals("sessionvalue", sessions.getNote("user-session-attr")); }; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java index f8ed6f6e76..3e26dff8ae 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/KcinitTest.java @@ -28,7 +28,6 @@ import org.keycloak.authentication.requiredactions.TermsAndConditions; import org.keycloak.authorization.model.Policy; import org.keycloak.authorization.model.ResourceServer; import org.keycloak.common.Profile; -import org.keycloak.credential.CredentialModel; import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationFlowBindings; import org.keycloak.models.AuthenticationFlowModel; @@ -294,7 +293,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { public void testBrowserContinueRequiredAction() throws Exception { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); user.addRequiredAction("dummy"); }); testInstall(); @@ -439,7 +438,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { public void testTerms() throws Exception { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); user.addRequiredAction(TermsAndConditions.PROVIDER_ID); }); @@ -466,7 +465,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { // expects that updateProfile is a passthrough testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE); }); @@ -496,7 +495,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); user.removeRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE); }); } @@ -507,7 +506,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { public void testUpdatePassword() throws Exception { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); }); @@ -548,7 +547,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password")); }); } @@ -562,7 +561,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { public void testConfigureTOTP() throws Exception { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP); }); @@ -631,7 +630,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { } finally { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("wburke", realm); + UserModel user = session.users().getUserByUsername(realm, "wburke"); session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, OTPCredentialModel.TYPE) .collect(Collectors.toList()) .forEach(model -> session.userCredentialManager().removeStoredCredential(realm, user, model.getId())); @@ -648,7 +647,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest { public void testVerifyEmail() throws Exception { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("test-user@localhost", realm); + UserModel user = session.users().getUserByUsername(realm, "test-user@localhost"); user.addRequiredAction(UserModel.RequiredAction.VERIFY_EMAIL); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java index 3290039b4a..d10c81edf0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java @@ -162,7 +162,7 @@ public class LDAPBinaryAttributesTest extends AbstractLDAPTest { String joeId = joe.getId(); testingClient.server().run(session -> { RealmModel test = session.realms().getRealmByName("test"); - UserModel userById = session.userLocalStorage().getUserById(joeId, test); + UserModel userById = session.userLocalStorage().getUserById(test, joeId); assertThat(userById.getAttributes().get(LDAPConstants.JPEG_PHOTO), is(nullValue())); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java index 907838d35e..fd672a9169 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java @@ -48,7 +48,6 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import javax.ws.rs.BadRequestException; import java.util.Date; -import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -338,7 +337,7 @@ public class LDAPGroupMapperSyncTest extends AbstractLDAPTest { Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group12")); // Load user from LDAP to Keycloak DB - UserModel john = session.users().getUserByUsername("johnkeycloak", realm); + UserModel john = session.users().getUserByUsername(realm, "johnkeycloak"); Set johnGroups = john.getGroupsStream().collect(Collectors.toSet()); // Assert just those groups, which john was memberOf exists because they were lazily created diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java index 73d8336856..96efa0cf1a 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java @@ -87,8 +87,8 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.MODE, LDAPGroupMapperMode.LDAP_ONLY.toString()); appRealm.updateComponent(mapperModel); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // 1 - Grant some groups in LDAP @@ -127,7 +127,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel johnDb = session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm); + UserModel johnDb = session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertEquals(2, johnDb.getGroupsStream().count()); Assert.assertEquals(2, johnDb.getGroupsStream("Gr", 0, 10).count()); Assert.assertEquals(1, johnDb.getGroupsStream("Gr", 1, 10).count()); @@ -150,8 +150,8 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12"); GroupModel groupTeam20162017 = KeycloakModelUtils.findGroupByPath(appRealm, "Team 2016/2017"); GroupModel groupTeamChild20182019 = KeycloakModelUtils.findGroupByPath(appRealm, "defaultGroup1/Team Child 2018/2019"); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); Set johnGroups = john.getGroupsStream().collect(Collectors.toSet()); Assert.assertEquals(4, johnGroups.size()); @@ -239,7 +239,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1"); GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12"); @@ -267,7 +267,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12"); // Add some group mapping to model. This should fail with no-import mode for LDAP provider READ_ONLY mode for the group mapper @@ -284,7 +284,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1"); GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12"); @@ -316,7 +316,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12"); - UserModel maryDB = session.userLocalStorage().getUserByUsername("marykeycloak", appRealm); + UserModel maryDB = session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak"); Set maryDBGroups = maryDB.getGroupsStream().collect(Collectors.toSet()); Assert.assertFalse(maryDBGroups.contains(group1)); @@ -337,7 +337,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { Assert.assertEquals(1, group12Members.size()); Assert.assertEquals("marykeycloak", group12Members.get(0).getUsername()); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); mary.leaveGroup(group12); }); } else { @@ -362,8 +362,8 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1"); GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12"); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "groupsMapper"); GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), appRealm); @@ -417,7 +417,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { groupMapper.addGroupMappingInLDAP(appRealm, group12, robLdap); // Get user and check that he has requested groups from LDAP - UserModel rob = session.users().getUserByUsername("robkeycloak", appRealm); + UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); Set robGroups = rob.getGroupsStream().collect(Collectors.toSet()); Assert.assertFalse(robGroups.contains(group1)); @@ -563,7 +563,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { RealmModel appRealm = ctx.getRealm(); // Get user in Keycloak. Ensure that he is member of requested group - UserModel carlos = session.users().getUserByUsername("carloskeycloak", appRealm); + UserModel carlos = session.users().getUserByUsername(appRealm, "carloskeycloak"); Set carlosGroups = carlos.getGroupsStream().collect(Collectors.toSet()); GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1"); @@ -608,7 +608,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); GroupModel group4 = KeycloakModelUtils.findGroupByPath(appRealm, "/group4"); john.joinGroup(group4); @@ -628,7 +628,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); GroupModel group14 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group14"); GroupModel group3 = KeycloakModelUtils.findGroupByPath(appRealm, "/group3"); @@ -747,7 +747,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { GroupModel kcBigGroup = KeycloakModelUtils.findGroupByPath(appRealm, "/biggroup"); // check all the users have the group assigned for (int i = 0; i < membersToTest; i++) { - UserModel kcUser = session.users().getUserByUsername(String.format("user%02d", i), appRealm); + UserModel kcUser = session.users().getUserByUsername(appRealm, String.format("user%02d", i)); Assert.assertTrue("User contains biggroup " + i, kcUser.getGroupsStream().collect(Collectors.toSet()).contains(kcBigGroup)); } // check the group contains all the users as member @@ -794,7 +794,7 @@ public class LDAPGroupMapperTest extends AbstractLDAPTest { // check everything is OK GroupModel kcDeleteGroup = KeycloakModelUtils.findGroupByPath(appRealm, "/deletegroup"); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); List groupMembers = session.users().getGroupMembersStream(appRealm, kcDeleteGroup, 0, 5) .collect(Collectors.toList()); Assert.assertEquals(1, groupMembers.size()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java index b513cd9d7f..c7b550a185 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java @@ -84,7 +84,7 @@ public class LDAPHardcodedAttributeTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(user); Assert.assertTrue(user.isEmailVerified()); Assert.assertEquals("en", user.getFirstAttribute("locale")); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java index 02b005eeab..62036d2bb8 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java @@ -120,7 +120,7 @@ public class LDAPMSADFullNameTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(john.getFederationLink()); assertDnStartsWith(session, ctx, john, "cn=johnkeycloak"); @@ -143,7 +143,7 @@ public class LDAPMSADFullNameTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); assertUser(session, ctx, john, "johnkeycloak", "Johny", "Anthony", true, "cn=Johny Anthony"); session.users().removeUser(appRealm, john); @@ -167,7 +167,7 @@ public class LDAPMSADFullNameTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); assertUser(session, ctx, john, "johnkeycloak", "Johnyyy", "", true, "cn=Johnyyy"); session.users().removeUser(appRealm, john); @@ -191,7 +191,7 @@ public class LDAPMSADFullNameTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); assertUser(session, ctx, john, "johnkeycloak", "", "Anthonyy", true, "cn=Anthonyy"); session.users().removeUser(appRealm, john); @@ -213,7 +213,7 @@ public class LDAPMSADFullNameTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); assertUser(session, ctx, john, "johnkeycloak", "Jož,o", "Baříč", true, "cn=Jož\\,o Baříč"); session.users().removeUser(appRealm, john); @@ -257,16 +257,16 @@ public class LDAPMSADFullNameTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel existingKc = session.users().getUserByUsername("existingkc", appRealm); + UserModel existingKc = session.users().getUserByUsername(appRealm, "existingkc"); assertUser(session, ctx, existingKc, "existingkc", "John", "Existing", true, "cn=John Existing"); - UserModel existingKc1 = session.users().getUserByUsername("existingkc1", appRealm); + UserModel existingKc1 = session.users().getUserByUsername(appRealm, "existingkc1"); assertUser(session, ctx, existingKc1, "existingkc1", "", "", true, "cn=existingkc1"); - UserModel existingKc2 = session.users().getUserByUsername("existingkc2", appRealm); + UserModel existingKc2 = session.users().getUserByUsername(appRealm, "existingkc2"); assertUser(session, ctx, existingKc2, "existingkc2", "John", "Existing", true, "cn=John Existing0"); - UserModel existingKc3 = session.users().getUserByUsername("existingkc3", appRealm); + UserModel existingKc3 = session.users().getUserByUsername(appRealm, "existingkc3"); assertUser(session, ctx, existingKc3, "existingkc3", "John", "Existing", true, "cn=John Existing1"); session.users().removeUser(appRealm, existingKc); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java index 132c570ef4..a40299759f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java @@ -131,7 +131,7 @@ public class LDAPMSADMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("registerUserSuccess2", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "registerUserSuccess2"); Assert.assertNotNull(user); Assert.assertNotNull(user.getFederationLink()); Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java index 22bd245cdc..e2d3dd06f6 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java @@ -111,8 +111,8 @@ public class LDAPMultipleAttributesTest extends AbstractLDAPTest { RealmModel appRealm = ctx.getRealm(); // Test user imported in local storage now - UserModel user = session.users().getUserByUsername("jbrown", appRealm); - Assert.assertNotNull(session.userLocalStorage().getUserById(user.getId(), appRealm)); + UserModel user = session.users().getUserByUsername(appRealm, "jbrown"); + Assert.assertNotNull(session.userLocalStorage().getUserById(appRealm, user.getId())); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441"); }); } @@ -125,7 +125,7 @@ public class LDAPMultipleAttributesTest extends AbstractLDAPTest { session.userCache().clear(); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("bwilson", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "bwilson"); Assert.assertEquals("bwilson@keycloak.org", user.getEmail()); Assert.assertEquals("Bruce", user.getFirstName()); @@ -147,7 +147,7 @@ public class LDAPMultipleAttributesTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("bwilson", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "bwilson"); List postalCodes = user.getAttributeStream("postal_code").collect(Collectors.toList()); assertPostalCodes(postalCodes, "88441"); List tmp = new LinkedList<>(); @@ -161,7 +161,7 @@ public class LDAPMultipleAttributesTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("bwilson", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "bwilson"); assertPostalCodes(user.getAttributeStream("postal_code").collect(Collectors.toList()), "88441", "77332"); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java index bb67ab4ad4..ffe58622be 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java @@ -228,20 +228,20 @@ public class LDAPNoCacheTest extends AbstractLDAPTest { LDAPStorageProvider ldapProvider = ctx.getLdapProvider(); // assume no user imported - UserModel user = localStorage.getUserByUsername("johnkeycloak", realm); + UserModel user = localStorage.getUserByUsername(realm, "johnkeycloak"); assumeThat(user, is(nullValue())); // trigger import - List byEmail = ldapProvider.searchForUserByUserAttributeStream("email", "john_old@email.org", realm) + List byEmail = ldapProvider.searchForUserByUserAttributeStream(realm, "email", "john_old@email.org") .collect(Collectors.toList()); assumeThat(byEmail, hasSize(1)); // assume that user has been imported - user = localStorage.getUserByUsername("johnkeycloak", realm); + user = localStorage.getUserByUsername(realm, "johnkeycloak"); assumeThat(user, is(not(nullValue()))); // search a second time - byEmail = ldapProvider.searchForUserByUserAttributeStream("email", "john_old@email.org", realm) + byEmail = ldapProvider.searchForUserByUserAttributeStream(realm, "email", "john_old@email.org") .collect(Collectors.toList()); assertThat(byEmail, hasSize(1)); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java index 509da8ac80..d48144300b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java @@ -126,7 +126,7 @@ public class LDAPNoMSADTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel johnkeycloak2 = session.users().getUserByUsername("johnkeycloak2", appRealm); + UserModel johnkeycloak2 = session.users().getUserByUsername(appRealm, "johnkeycloak2"); Assert.assertNotNull(johnkeycloak2); johnkeycloak2.setFirstName("foo2"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java index ce91485917..2b45ae82de 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java @@ -67,7 +67,7 @@ public class LDAPProvidersFullNameMapperTest extends AbstractLDAPTest { appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true); // assert that user "fullnameUser" is not in local DB - Assert.assertNull(session.users().getUserByUsername("fullname", appRealm)); + Assert.assertNull(session.users().getUserByUsername(appRealm, "fullname")); // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName) ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(appRealm); @@ -104,7 +104,7 @@ public class LDAPProvidersFullNameMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm); + UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); fullnameUser.setFirstName("James2"); fullnameUser.setLastName("Dee2"); }); @@ -118,7 +118,7 @@ public class LDAPProvidersFullNameMapperTest extends AbstractLDAPTest { LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James2", "Dee2", "fullname@email.org", "4578"); // Remove "fullnameUser" to assert he is removed from LDAP. - UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm); + UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); session.users().removeUser(appRealm, fullnameUser); }); } @@ -141,7 +141,7 @@ public class LDAPProvidersFullNameMapperTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm); + UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); fullnameUser.setAttribute("myAttribute", Collections.singletonList("test")); fullnameUser.setAttribute("myEmptyAttribute", new ArrayList<>()); fullnameUser.setAttribute("myNullAttribute", null); @@ -155,7 +155,7 @@ public class LDAPProvidersFullNameMapperTest extends AbstractLDAPTest { // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James", "Dee", "fullname@email.org", "4578"); - UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm); + UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); assertThat(fullnameUser.getAttributeStream("myAttribute").collect(Collectors.toList()), contains("test")); assertThat(fullnameUser.getAttributeStream("myEmptyAttribute").collect(Collectors.toList()), is(empty())); assertThat(fullnameUser.getAttributeStream("myNullAttribute").collect(Collectors.toList()), is(empty())); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java index e4a3a4c7d7..8a165e0522 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java @@ -148,7 +148,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { public void testRemoveImportedUsers() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); - UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm()); + UserModel user = session.users().getUserByUsername(ctx.getRealm(), "johnkeycloak"); Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink()); }); @@ -157,7 +157,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmManager manager = new RealmManager(session); RealmModel appRealm = manager.getRealm("test"); - UserModel user = session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm); + UserModel user = session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNull(user); }); } @@ -167,7 +167,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { public void zzTestUnlinkUsers() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); - UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm()); + UserModel user = session.users().getUserByUsername(ctx.getRealm(), "johnkeycloak"); Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink()); }); @@ -175,7 +175,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); - UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm()); + UserModel user = session.users().getUserByUsername(ctx.getRealm(), "johnkeycloak"); Assert.assertNotNull(user); Assert.assertNull(user.getFederationLink()); }); @@ -468,7 +468,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), ctx.getRealm(), config, "maryjane"); // Make sure the deletion took place. - Assert.assertEquals(0, session.users().searchForUserStream("mary yram", ctx.getRealm()).count()); + Assert.assertEquals(0, session.users().searchForUserStream(ctx.getRealm(), "mary yram").count()); }); } @@ -515,7 +515,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.addUserAttributeMapper(appRealm, ldapModel, "zipCodeMapper-cs", "postal_code", "POstalCode"); // Fetch user from LDAP and check that postalCode is filled - UserModel user = session.users().getUserByUsername("johnzip", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johnzip"); String postalCode = user.getFirstAttribute("postal_code"); Assert.assertEquals("12398", postalCode); @@ -598,10 +598,10 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - session.userCache().evict(appRealm, session.users().getUserByUsername("register123", appRealm)); + session.userCache().evict(appRealm, session.users().getUserByUsername(appRealm, "register123")); // See that user don't yet have any description - UserModel user = session.users().getUserByUsername("register123", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "register123"); Assert.assertNull(user.getFirstAttribute("description")); Assert.assertNotNull(user.getFirstAttribute("desc")); String desc = user.getFirstAttribute("desc"); @@ -623,7 +623,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { RoleModel hardcodedRole = appRealm.addRole("hardcoded-role"); // assert that user "johnkeycloak" doesn't have hardcoded role - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertFalse(john.hasRole(hardcodedRole)); ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded role", ctx.getLdapModel().getId(), @@ -639,7 +639,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { RoleModel hardcodedRole = appRealm.getRole("hardcoded-role"); // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertTrue(john.hasRole(hardcodedRole)); // Can't remove user from hardcoded role @@ -665,7 +665,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { GroupModel hardcodedGroup = appRealm.createGroup(uuid, "hardcoded-group"); // assert that user "johnkeycloak" doesn't have hardcoded group - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertFalse(john.isMemberOf(hardcodedGroup)); ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded group", @@ -681,7 +681,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { GroupModel hardcodedGroup = appRealm.getGroupById(uuid); // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertTrue(john.isMemberOf(hardcodedGroup)); // Can't remove user from hardcoded role @@ -739,7 +739,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(user); try { user.setEmail("error@error.com"); @@ -811,25 +811,25 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124"); // Users are not at local store at this moment - Assert.assertNull(session.userLocalStorage().getUserByUsername("username1", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("username2", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("username3", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("username4", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username1")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username2")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username3")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username4")); // search by username (we use a terminal operation on the stream to ensure it is consumed) - session.users().searchForUserStream("username1", appRealm).count(); + session.users().searchForUserStream(appRealm, "username1").count(); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username1", "John1", "Doel1", "user1@email.org", "121"); // search by email (we use a terminal operation on the stream to ensure it is consumed) - session.users().searchForUserStream("user2@email.org", appRealm).count(); + session.users().searchForUserStream(appRealm, "user2@email.org").count(); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username2", "John2", "Doel2", "user2@email.org", "122"); // search by lastName (we use a terminal operation on the stream to ensure it is consumed) - session.users().searchForUserStream("Doel3", appRealm).count(); + session.users().searchForUserStream(appRealm, "Doel3").count(); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username3", "John3", "Doel3", "user3@email.org", "123"); // search by firstName + lastName (we use a terminal operation on the stream to ensure it is consumed) - session.users().searchForUserStream("John4 Doel4", appRealm).count(); + session.users().searchForUserStream(appRealm, "John4 Doel4").count(); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username4", "John4", "Doel4", "user4@email.org", "124"); }); } @@ -854,15 +854,15 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127"); // search by email (we use a terminal operation on the stream to ensure it is consumed) - session.users().searchForUserStream("user5@email.org", appRealm).count(); + session.users().searchForUserStream(appRealm, "user5@email.org").count(); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username5", "John5", "Doel5", "user5@email.org", "125"); - session.users().searchForUserStream("John6 Doel6", appRealm).count(); + session.users().searchForUserStream(appRealm, "John6 Doel6").count(); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username6", "John6", "Doel6", "user6@email.org", "126"); - session.users().searchForUserStream("user7@email.org", appRealm).count(); - session.users().searchForUserStream("John7 Doel7", appRealm).count(); - Assert.assertNull(session.userLocalStorage().getUserByUsername("username7", appRealm)); + session.users().searchForUserStream(appRealm, "user7@email.org").count(); + session.users().searchForUserStream(appRealm, "John7 Doel7").count(); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username7")); // Remove custom filter ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER); @@ -885,7 +885,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(user); Assert.assertNotNull(user.getFederationLink()); Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); @@ -924,14 +924,14 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); // User is deleted just locally Assert.assertTrue(session.users().removeUser(appRealm, user)); // Assert user not available locally, but will be reimported from LDAP once searched - Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm)); - Assert.assertNotNull(session.users().getUserByUsername("johnkeycloak", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak")); + Assert.assertNotNull(session.users().getUserByUsername(appRealm, "johnkeycloak")); }); // Revert @@ -962,12 +962,12 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username10", "John10", "Doel10", "user10@email.org", null, "1210"); // Users are not at local store at this moment - Assert.assertNull(session.userLocalStorage().getUserByUsername("username8", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("username9", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("username10", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username8")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username9")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username10")); // search for user by attribute - List users = ctx.getLdapProvider().searchForUserByUserAttributeStream(ATTRIBUTE, ATTRIBUTE_VALUE, appRealm) + List users = ctx.getLdapProvider().searchForUserByUserAttributeStream(appRealm, ATTRIBUTE, ATTRIBUTE_VALUE) .collect(Collectors.toList()); assertEquals(2, users.size()); List attrList = users.get(0).getAttributeStream(ATTRIBUTE).collect(Collectors.toList()); @@ -982,7 +982,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username8", "John8", "Doel8", "user8@email.org", ATTRIBUTE_VALUE); LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username9", "John9", "Doel9", "user9@email.org", ATTRIBUTE_VALUE); // but the one not looked up is not - Assert.assertNull(session.userLocalStorage().getUserByUsername("username10", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "username10")); }); } @@ -1000,7 +1000,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(user); user.getAttributes(); @@ -1029,7 +1029,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.addLDAPUser(ldapProvider, appRealm, "johndirect", "John", "Direct", "johndirect@email.org", null, "1234"); // Fetch user from LDAP and check that postalCode is filled - UserModel user = session.users().getUserByUsername("johndirect", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johndirect"); String postalCode = user.getFirstAttribute("postal_code"); Assert.assertEquals("1234", postalCode); @@ -1040,7 +1040,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmModel appRealm = new RealmManager(session).getRealmByName("test"); - CachedUserModel user = (CachedUserModel) session.users().getUserByUsername("johndirect", appRealm); + CachedUserModel user = (CachedUserModel) session.users().getUserByUsername(appRealm, "johndirect"); String postalCode = user.getFirstAttribute("postal_code"); String email = user.getEmail(); Assert.assertEquals("1234", postalCode); @@ -1051,7 +1051,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmModel appRealm = new RealmManager(session).getRealmByName("test"); - UserModel user = session.users().getUserByUsername("johndirect", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "johndirect"); Assert.assertNull(user); }); @@ -1068,7 +1068,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "testCacheUser", "John", "Cached", "johndirect@test.com", null, "1234"); // Fetch user from LDAP and check that postalCode is filled - UserModel testedUser = session.users().getUserByUsername("testCacheUser", ctx.getRealm()); + UserModel testedUser = session.users().getUserByUsername(ctx.getRealm(), "testCacheUser"); String usserId = testedUser.getId(); Assert.assertNotNull(usserId); @@ -1080,7 +1080,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); - UserModel testedUser = session.users().getUserById(userId, appRealm); + UserModel testedUser = session.users().getUserById(appRealm, userId); Assert.assertFalse(testedUser instanceof CachedUserModel); }); @@ -1096,21 +1096,21 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); - UserModel testedUser = session.users().getUserById(userId, appRealm); + UserModel testedUser = session.users().getUserById(appRealm, userId); Assert.assertTrue(testedUser instanceof CachedUserModel); }); setTimeOffset(60 * 5); // 5 minutes in future, should be cached still testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); - UserModel testedUser = session.users().getUserById(userId, appRealm); + UserModel testedUser = session.users().getUserById(appRealm, userId); Assert.assertTrue(testedUser instanceof CachedUserModel); }); setTimeOffset(60 * 10); // 10 minutes into future, cache will be invalidated testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); - UserModel testedUser = session.users().getUserByUsername("thor", appRealm); + UserModel testedUser = session.users().getUserByUsername(appRealm, "thor"); Assert.assertFalse(testedUser instanceof CachedUserModel); }); @@ -1132,7 +1132,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); - Optional userVerified = session.users().searchForUserStream("john@test.com", appRealm).findFirst(); + Optional userVerified = session.users().searchForUserStream(appRealm, "john@test.com").findFirst(); Assert.assertTrue(userVerified.get().isEmailVerified()); }); @@ -1149,7 +1149,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); - Optional userNotVerified = session.users().searchForUserStream("john2@test.com", appRealm).findFirst(); + Optional userNotVerified = session.users().searchForUserStream(appRealm, "john2@test.com").findFirst(); Assert.assertFalse(userNotVerified.get().isEmailVerified()); }); } @@ -1162,7 +1162,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel johnkeycloak = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel johnkeycloak = session.users().getUserByUsername(appRealm, "johnkeycloak"); // If the username was case sensitive in the username-cn mapper, then this would throw an exception johnkeycloak.setSingleAttribute(UserModel.USERNAME, "JohnKeycloak"); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java index 7eb8cfd9fd..361b3f8a19 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java @@ -60,16 +60,16 @@ public class LDAPRoleMapperTest extends AbstractLDAPTest { RealmModel appRealm = ctx.getRealm(); // check users - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(john); Assert.assertThat(john.getRealmRoleMappingsStream().map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); Assert.assertNotNull(mary); Assert.assertThat(mary.getRealmRoleMappingsStream().map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); - UserModel rob = session.users().getUserByUsername("robkeycloak", appRealm); + UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); Assert.assertNotNull(rob); Assert.assertThat(rob.getRealmRoleMappingsStream().map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1")); - UserModel james = session.users().getUserByUsername("jameskeycloak", appRealm); + UserModel james = session.users().getUserByUsername(appRealm, "jameskeycloak"); Assert.assertNotNull(james); Assert.assertThat(james.getRealmRoleMappingsStream().collect(Collectors.toSet()), Matchers.empty()); @@ -108,16 +108,16 @@ public class LDAPRoleMapperTest extends AbstractLDAPTest { new RoleLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(appRealm); // check users - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertNotNull(john); Assert.assertThat(john.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); Assert.assertNotNull(mary); Assert.assertThat(mary.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); - UserModel rob = session.users().getUserByUsername("robkeycloak", appRealm); + UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); Assert.assertNotNull(rob); Assert.assertThat(rob.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1")); - UserModel james = session.users().getUserByUsername("jameskeycloak", appRealm); + UserModel james = session.users().getUserByUsername(appRealm, "jameskeycloak"); Assert.assertNotNull(james); Assert.assertThat(james.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.empty()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java index 03e3cbb353..53c2a6f668 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java @@ -126,8 +126,8 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // 1 - Grant some roles in LDAP @@ -156,7 +156,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { // 2 - Check that role mappings are not in local Keycloak DB (They are in LDAP). - UserModel johnDb = session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm); + UserModel johnDb = session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak"); Set johnDbRoles = johnDb.getRoleMappingsStream().collect(Collectors.toSet()); Assert.assertFalse(johnDbRoles.contains(realmRole1)); Assert.assertFalse(johnDbRoles.contains(realmRole2)); @@ -207,7 +207,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.READ_ONLY); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); @@ -235,7 +235,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { Assert.assertTrue(maryRoles.contains(realmRole3)); // Assert that access through DB will have just DB mapped role - UserModel maryDB = session.userLocalStorage().getUserByUsername("marykeycloak", appRealm); + UserModel maryDB = session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak"); Set maryDBRoles = maryDB.getRealmRoleMappingsStream().collect(Collectors.toSet()); Assert.assertFalse(maryDBRoles.contains(realmRole1)); Assert.assertFalse(maryDBRoles.contains(realmRole2)); @@ -257,7 +257,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // Assert role mappings is not available Set maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet()); @@ -286,7 +286,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { roleMapper.addRoleMappingInLDAP("realmRole2", robLdap); // Get user and check that he has requested roles from LDAP - UserModel rob = session.users().getUserByUsername("robkeycloak", appRealm); + UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); RoleModel realmRole3 = appRealm.getRole("realmRole3"); @@ -352,7 +352,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { RealmModel appRealm = ctx.getRealm(); // make sure user is cached. - UserModel johnRoleMapper = session.users().getUserByUsername("johnrolemapper", appRealm); + UserModel johnRoleMapper = session.users().getUserByUsername(appRealm, "johnrolemapper"); Assert.assertNotNull(johnRoleMapper); Assert.assertEquals(0, johnRoleMapper.getRealmRoleMappingsStream().count()); @@ -372,7 +372,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { roleMapper.addRoleMappingInLDAP("realmRole2", johnLdap); // Get user and check that he has requested roles from LDAP - UserModel johnRoleMapper = session.users().getUserByUsername("johnrolemapper", appRealm); + UserModel johnRoleMapper = session.users().getUserByUsername(appRealm, "johnrolemapper"); RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); @@ -407,7 +407,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { RealmModel appRealm = ctx.getRealm(); // Get user and check that he has requested roles from LDAP - UserModel johnRoleMapper = session.users().getUserByUsername("johnrolemapper", appRealm); + UserModel johnRoleMapper = session.users().getUserByUsername(appRealm, "johnrolemapper"); RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); @@ -457,7 +457,7 @@ public class LDAPRoleMappingsTest extends AbstractLDAPTest { RealmModel appRealm = ctx.getRealm(); // Get user in Keycloak. Ensure that he is member of requested group - UserModel carlos = session.users().getUserByUsername("carloskeycloak", appRealm); + UserModel carlos = session.users().getUserByUsername(appRealm, "carloskeycloak"); Set carlosRoles = carlos.getRealmRoleMappingsStream().collect(Collectors.toSet()); RoleModel realmRole1 = appRealm.getRole("realmRole1"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java index 813a6ab47a..995ff00414 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java @@ -145,7 +145,7 @@ public class LDAPSpecialCharsTest extends AbstractLDAPTest { LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.MODE, LDAPGroupMapperMode.LDAP_ONLY.toString()); appRealm.updateComponent(mapperModel); - UserModel specialUser = session.users().getUserByUsername("jamees,key*cložak)ppp", appRealm); + UserModel specialUser = session.users().getUserByUsername(appRealm, "jamees,key*cložak)ppp"); Assert.assertNotNull(specialUser); // 1 - Grant some groups in LDAP diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java index 2dab45d088..aa0936db65 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java @@ -169,7 +169,7 @@ public class LDAPSyncTest extends AbstractLDAPTest { // Assert still old users in local provider LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125"); - Assert.assertNull(userProvider.getUserByUsername("user6", testRealm)); + Assert.assertNull(userProvider.getUserByUsername(testRealm, "user6")); // Trigger partial sync KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); @@ -221,7 +221,7 @@ public class LDAPSyncTest extends AbstractLDAPTest { // Assert syncing from LDAP fails due to duplicated email SynchronizationResult result = new UserStorageSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ctx.getLdapModel()); Assert.assertEquals(1, result.getFailed()); - Assert.assertNull(session.userLocalStorage().getUserByUsername("user7-something", ctx.getRealm())); + Assert.assertNull(session.userLocalStorage().getUserByUsername(ctx.getRealm(), "user7-something")); // Update LDAP user to avoid duplicated email LDAPObject duplicatedLdapUser = ctx.getLdapProvider().loadLDAPUserByUsername(ctx.getRealm(), "user7-something"); @@ -280,7 +280,7 @@ public class LDAPSyncTest extends AbstractLDAPTest { // Assert users imported with correct LDAP_ID LDAPTestAsserts.assertUserImported(session.users(), ctx.getRealm(), "user1", "User1FN", "User1LN", "user1@email.org", "121"); LDAPTestAsserts.assertUserImported(session.users(), ctx.getRealm(), "user2", "User2FN", "User2LN", "user2@email.org", "122"); - UserModel user1 = session.users().getUserByUsername("user1", ctx.getRealm()); + UserModel user1 = session.users().getUserByUsername(ctx.getRealm(), "user1"); Assert.assertEquals("user1", user1.getFirstAttribute(LDAPConstants.LDAP_ID)); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java index 51250799f8..3ffe719be9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java @@ -32,7 +32,7 @@ import org.keycloak.storage.user.SynchronizationResult; public class LDAPTestAsserts { public static UserModel assertUserImported(UserProvider userProvider, RealmModel realm, String username, String expectedFirstName, String expectedLastName, String expectedEmail, String expectedPostalCode) { - UserModel user = userProvider.getUserByUsername(username, realm); + UserModel user = userProvider.getUserByUsername(realm, username); assertLoaded(user, username, expectedFirstName, expectedLastName, expectedEmail, expectedPostalCode); return user; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java index e41389f221..8b52a1aed6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java @@ -69,7 +69,7 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johndow", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johndow"); Assert.assertNotNull(john); Assert.assertNotNull(john.getFederationLink()); Assert.assertEquals("johndow", john.getUsername()); @@ -85,7 +85,7 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johndow", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johndow"); john.setUsername("johndow2"); john.setEmail("johndow2@email.cz"); john.setFirstName("johndow2"); @@ -95,8 +95,8 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - Assert.assertNull(session.users().getUserByUsername("johndow", appRealm)); - UserModel john2 = session.users().getUserByUsername("johndow2", appRealm); + Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow")); + UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2"); Assert.assertNotNull(john2); Assert.assertNotNull(john2.getFederationLink()); Assert.assertEquals("johndow2", john2.getUsername()); @@ -109,7 +109,7 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { Assert.assertEquals("johndow2", firstRdnEntry.getAttrValue(firstRdnEntry.getAllKeys().get(0))); session.users().removeUser(appRealm, john2); - Assert.assertNull(session.users().getUserByUsername("johndow2", appRealm)); + Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow2")); }); } @@ -132,10 +132,10 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johndow", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johndow"); Assert.assertNotNull(john); Assert.assertNotNull(john.getFederationLink()); - UserModel john2 = session.users().getUserByUsername("johndow2", appRealm); + UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2"); Assert.assertNotNull(john2); Assert.assertNotNull(john2.getFederationLink()); }); @@ -144,7 +144,7 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johndow", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johndow"); john.setUsername("johndow2"); }); Assert.assertFalse("Model exception is expected here, so it should not reach this point", true); @@ -156,14 +156,14 @@ public class LdapUsernameAttributeTest extends AbstractLDAPTest { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johndow", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johndow"); Assert.assertNotNull(john); - UserModel john2 = session.users().getUserByUsername("johndow2", appRealm); + UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2"); Assert.assertNotNull(john2); session.users().removeUser(appRealm, john); session.users().removeUser(appRealm, john2); - Assert.assertNull(session.users().getUserByUsername("johndow", appRealm)); - Assert.assertNull(session.users().getUserByUsername("johndow2", appRealm)); + Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow")); + Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow2")); }); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java index 2505df8946..174e30bc60 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java @@ -48,9 +48,9 @@ public class LDAPMultipleAttributesNoImportTest extends LDAPMultipleAttributesTe RealmModel appRealm = ctx.getRealm(); // Test user NOT imported in local storage now. He is available just through "session.users()" - UserModel user = session.users().getUserByUsername("jbrown", appRealm); + UserModel user = session.users().getUserByUsername(appRealm, "jbrown"); Assert.assertNotNull(user); - Assert.assertNull(session.userLocalStorage().getUserById(user.getId(), appRealm)); + Assert.assertNull(session.userLocalStorage().getUserById(appRealm, user.getId())); LDAPTestAsserts.assertUserImported(session.users(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441"); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java index b2eaed571a..fb2e21ff1c 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java @@ -97,19 +97,19 @@ public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrati LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124"); // search by username - UserModel user = session.users().searchForUserStream("username1", appRealm).findFirst().get(); + UserModel user = session.users().searchForUserStream(appRealm, "username1").findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username1", "John1", "Doel1", "user1@email.org", "121"); // search by email - user = session.users().searchForUserStream("user2@email.org", appRealm).findFirst().get(); + user = session.users().searchForUserStream(appRealm, "user2@email.org").findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username2", "John2", "Doel2", "user2@email.org", "122"); // search by lastName - user = session.users().searchForUserStream("Doel3", appRealm).findFirst().get(); + user = session.users().searchForUserStream(appRealm, "Doel3").findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username3", "John3", "Doel3", "user3@email.org", "123"); // search by firstName + lastName - user = session.users().searchForUserStream("John4 Doel4", appRealm).findFirst().get(); + user = session.users().searchForUserStream(appRealm, "John4 Doel4").findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username4", "John4", "Doel4", "user4@email.org", "124"); }); } @@ -144,14 +144,14 @@ public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrati LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127"); // search by email - UserModel user = session.users().searchForUserStream("user5@email.org", appRealm).findFirst().get(); + UserModel user = session.users().searchForUserStream(appRealm, "user5@email.org").findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username5", "John5", "Doel5", "user5@email.org", "125"); - user = session.users().searchForUserStream("John6 Doel6", appRealm).findFirst().get(); + user = session.users().searchForUserStream(appRealm, "John6 Doel6").findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username6", "John6", "Doel6", "user6@email.org", "126"); - Assert.assertEquals(0, session.users().searchForUserStream("user7@email.org", appRealm).count()); - Assert.assertEquals(0, session.users().searchForUserStream("John7 Doel7", appRealm).count()); + Assert.assertEquals(0, session.users().searchForUserStream(appRealm, "user7@email.org").count()); + Assert.assertEquals(0, session.users().searchForUserStream(appRealm, "John7 Doel7").count()); // Remove custom filter ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER); @@ -198,7 +198,7 @@ public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrati RealmModel appRealm = ctx.getRealm(); // assert that user "fullnameUser" is not in local DB - Assert.assertNull(session.users().getUserByUsername("fullname", appRealm)); + Assert.assertNull(session.users().getUserByUsername(appRealm, "fullname")); // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName) ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(appRealm); @@ -238,7 +238,7 @@ public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrati LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm); + UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); fullnameUser.setFirstName("James2"); fullnameUser.setLastName("Dee2"); }); @@ -252,7 +252,7 @@ public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrati LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", null, "Dee2", "fullname@email.org", "4578"); // Remove "fullnameUser" to assert he is removed from LDAP. Revert mappers to previous state - UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm); + UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); session.users().removeUser(appRealm, fullnameUser); // Revert mappers diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java index 3b23c6ccb9..e5289ba1ba 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java @@ -143,9 +143,9 @@ public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // make sure we are in no-import mode! - Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak")); // This role should already exists as it was imported from LDAP RoleModel realmRole1 = appRealm.getRole("realmRole1"); @@ -172,7 +172,7 @@ public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // This role should already exists as it was imported from LDAP RoleModel realmRole1 = appRealm.getRole("realmRole1"); @@ -195,12 +195,12 @@ public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest { LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // make sure we are in no-import mode - Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak")); // 1 - Grant some roles in LDAP @@ -235,12 +235,12 @@ public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); - UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); + UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // make sure we are in no-import mode - Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm)); - Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak")); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak")); RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); @@ -300,7 +300,7 @@ public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest { UserModel david = session.users().addUser(appRealm, "davidkeycloak"); // make sure we are in no-import mode - Assert.assertNull(session.userLocalStorage().getUserByUsername("davidkeycloak", appRealm)); + Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "davidkeycloak")); RoleModel defaultRole = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); @@ -320,9 +320,9 @@ public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest { // but david should have the role as effective Assert.assertTrue(david.hasRole(defaultRole)); Assert.assertFalse(david.hasRole(realmRole2)); - + // Make sure john has not received the default role - UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm); + UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Assert.assertFalse(john.hasRole(defaultRole)); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java index e05e76d6b3..2cc9e5123f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java @@ -23,7 +23,6 @@ import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; import javax.ws.rs.core.Response; @@ -292,7 +291,7 @@ public class BackwardsCompatibilityUserStorageTest extends AbstractAuthTest { private void assertUserDontHaveDBCredentials() { testingClient.server().run(session -> { RealmModel realm1 = session.realms().getRealmByName("test"); - UserModel user1 = session.users().getUserByUsername("otp1", realm1); + UserModel user1 = session.users().getUserByUsername(realm1, "otp1"); Assert.assertEquals(0, session.userCredentialManager() .getStoredCredentialsStream(realm1, user1).count()); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java index 4161ceb11f..ddf61741a9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java @@ -185,7 +185,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); try { - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.fail(); } catch (Exception e) { Assert.assertEquals("FORCED FAILURE", e.getMessage()); @@ -214,7 +214,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { protected void evictUser(final String username) { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); session.userCache().evict(realm, user); }); } @@ -262,7 +262,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel user = session.userLocalStorage().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.userLocalStorage().getUserByUsername(realm, FailableHardcodedStorageProvider.username); if (user != null) { session.userLocalStorage().removeUser(realm, user); } @@ -272,7 +272,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.assertNotNull(user); }); @@ -286,11 +286,11 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel local = session.users().getUserByUsername(LOCAL_USER, realm); + UserModel local = session.users().getUserByUsername(realm, LOCAL_USER); Assert.assertNotNull(local); // assert that lookup of user storage user fails try { - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.fail(); } catch (Exception e) { Assert.assertEquals("FORCED FAILURE", e.getMessage()); @@ -307,36 +307,36 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel local = session.users().getUserByUsername(LOCAL_USER, realm); + UserModel local = session.users().getUserByUsername(realm, LOCAL_USER); Assert.assertNotNull(local); Stream result; - result = session.users().searchForUserStream(LOCAL_USER, realm); + result = session.users().searchForUserStream(realm, LOCAL_USER); Assert.assertEquals(1, result.count()); - result = session.users().searchForUserStream(FailableHardcodedStorageProvider.username, realm); + result = session.users().searchForUserStream(realm, FailableHardcodedStorageProvider.username); Assert.assertEquals(1, result.count()); - result = session.users().searchForUserStream(LOCAL_USER, realm, 0, 2); + result = session.users().searchForUserStream(realm, LOCAL_USER, 0, 2); Assert.assertEquals(1, result.count()); - result = session.users().searchForUserStream(FailableHardcodedStorageProvider.username, realm, 0, 2); + result = session.users().searchForUserStream(realm, FailableHardcodedStorageProvider.username, 0, 2); Assert.assertEquals(1, result.count()); Map localParam = new HashMap<>(); localParam.put("username", LOCAL_USER); Map hardcodedParam = new HashMap<>(); hardcodedParam.put("username", FailableHardcodedStorageProvider.username); - result = session.users().searchForUserStream(localParam, realm); + result = session.users().searchForUserStream(realm, localParam); Assert.assertEquals(1, result.count()); - result = session.users().searchForUserStream(hardcodedParam, realm); + result = session.users().searchForUserStream(realm, hardcodedParam); Assert.assertEquals(1, result.count()); - result = session.users().searchForUserStream(localParam, realm, 0, 2); + result = session.users().searchForUserStream(realm, localParam, 0, 2); Assert.assertEquals(1, result.count()); - result = session.users().searchForUserStream(hardcodedParam, realm, 0, 2); + result = session.users().searchForUserStream(realm, hardcodedParam, 0, 2); Assert.assertEquals(1, result.count()); // we run a terminal operation on the stream to make sure it is consumed. session.users().getUsersStream(realm).count(); session.users().getUsersCount(realm); - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.assertFalse(user instanceof CachedUserModel); Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); @@ -353,7 +353,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.assertFalse(user instanceof CachedUserModel); Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); @@ -363,7 +363,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.assertFalse(user instanceof CachedUserModel); Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); @@ -378,7 +378,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); - UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm); + UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); Assert.assertTrue(user instanceof CachedUserModel); Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java index 36d6053c91..6618bc5e29 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java @@ -160,7 +160,7 @@ public class UserStorageTest extends AbstractAuthTest { return; } - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); if (user != null) { session.userLocalStorage().removeUser(realm, user); session.userCache().clear(); @@ -467,10 +467,10 @@ public class UserStorageTest extends AbstractAuthTest { System.out.println("search by single attribute"); RealmModel realm = session.realms().getRealmByName("test"); - UserModel userModel = session.users().getUserByUsername("thor", realm); + UserModel userModel = session.users().getUserByUsername(realm, "thor"); userModel.setSingleAttribute("weapon", "hammer"); - List userModels = session.users().searchForUserByUserAttributeStream("weapon", "hammer", realm) + List userModels = session.users().searchForUserByUserAttributeStream(realm, "weapon", "hammer") .peek(System.out::println).collect(Collectors.toList()); Assert.assertEquals(1, userModels.size()); Assert.assertEquals("thor", userModels.get(0).getUsername()); @@ -526,7 +526,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached }); @@ -536,7 +536,7 @@ public class UserStorageTest extends AbstractAuthTest { // lookup user again - make sure it's returned from cache testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache }); @@ -545,21 +545,21 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertFalse(user instanceof CachedUserModel); // should have been invalidated }); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should have been newly cached }); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache }); @@ -568,7 +568,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache }); @@ -579,7 +579,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache - it's still good for almost the whole day }); @@ -589,7 +589,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache - it's still good until 23:45 }); @@ -598,7 +598,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertFalse(user instanceof CachedUserModel); // should be invalidated }); @@ -606,7 +606,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached }); @@ -615,7 +615,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache }); @@ -623,19 +623,19 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertFalse(user instanceof CachedUserModel); // should be invalidated }); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached }); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache }); } @@ -657,7 +657,7 @@ public class UserStorageTest extends AbstractAuthTest { // now testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertTrue(user instanceof CachedUserModel); // should still be cached }); @@ -667,7 +667,7 @@ public class UserStorageTest extends AbstractAuthTest { // now testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertTrue(user instanceof CachedUserModel); // should still be cached }); @@ -676,7 +676,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertFalse(user instanceof CachedUserModel); // should be evicted }); @@ -696,7 +696,7 @@ public class UserStorageTest extends AbstractAuthTest { // now testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertTrue(user instanceof CachedUserModel); // should still be cached }); @@ -705,7 +705,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertTrue(user instanceof CachedUserModel); // should still be cached }); @@ -714,7 +714,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertFalse(user instanceof CachedUserModel); // should be evicted }); @@ -732,7 +732,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); Assert.assertFalse(user instanceof CachedUserModel); // should be evicted }); @@ -740,7 +740,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel thor2 = session.users().getUserByUsername("thor", realm); + UserModel thor2 = session.users().getUserByUsername(realm, "thor"); Assert.assertFalse(thor2 instanceof CachedUserModel); }); @@ -753,7 +753,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel thor = session.users().getUserByUsername("thor", realm); + UserModel thor = session.users().getUserByUsername(realm, "thor"); System.out.println("Foo"); }); } @@ -768,13 +768,13 @@ public class UserStorageTest extends AbstractAuthTest { RealmModel realm = session.realms().getRealmByName("test"); UserModel user = session.users().addUser(realm, "memuser"); Assert.assertNotNull(user); - user = session.users().getUserByUsername("nonexistent", realm); + user = session.users().getUserByUsername(realm, "nonexistent"); Assert.assertNull(user); Assert.assertEquals(1, UserMapStorage.allocations.get()); Assert.assertEquals(0, UserMapStorage.closings.get()); - session.users().removeUser(realm,session.users().getUserByUsername("memuser",realm)); + session.users().removeUser(realm,session.users().getUserByUsername(realm, "memuser")); }); testingClient.server().run(session -> { @@ -877,7 +877,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); Assert.assertFalse(StorageId.isLocalStorage(user)); Stream credentials = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user); @@ -900,7 +900,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); // Assert priorities: password, otp1, otp2 List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -919,7 +919,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); // Assert priorities: password, otp2, otp1 List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -932,7 +932,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); // Assert priorities: otp2, password, otp1 List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -945,7 +945,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); // Assert priorities: otp2, otp1, password List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -958,7 +958,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); // Assert priorities: otp2, otp1, password List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -971,7 +971,7 @@ public class UserStorageTest extends AbstractAuthTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("thor", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "thor"); // Assert priorities: otp2, password List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -986,7 +986,7 @@ public class UserStorageTest extends AbstractAuthTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("thor", realm); + UserModel user = session.users().getUserByUsername(realm, "thor"); Assert.assertFalse(StorageId.isLocalStorage(user)); CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java index 962a1c3430..ea620d6fda 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java @@ -241,7 +241,7 @@ public class PasswordHashingTest extends AbstractTestRealmKeycloakTest { private CredentialModel fetchCredentials(String username) { return testingClient.server("test").fetch(session -> { RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); return session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, CredentialRepresentation.PASSWORD) .findFirst().orElse(null); }, CredentialModel.class); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java index ac2981cdd6..e0e359e1cf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java @@ -551,7 +551,7 @@ public class ResetCredentialsAlternativeFlowsTest extends AbstractTestRealmKeycl // Remove the within test registered 'bwilson' user testingClient.server("test").run(session -> { UserManager um = new UserManager(session); - UserModel user = session.users().getUserByUsername("bwilson", session.getContext().getRealm()); + UserModel user = session.users().getUserByUsername(session.getContext().getRealm(), "bwilson"); if (user != null) { um.removeUser(session.getContext().getRealm(), user); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/LoginTimeoutValidationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/LoginTimeoutValidationTest.java index bb93c45854..14bd05cf34 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/LoginTimeoutValidationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/LoginTimeoutValidationTest.java @@ -60,7 +60,7 @@ public class LoginTimeoutValidationTest extends AbstractTestRealmKeycloakTest { testingClient.server().run( session -> { RealmModel realm = session.realms().getRealmByName("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); UserManager um = new UserManager(session); if (user1 != null) { @@ -78,7 +78,7 @@ public class LoginTimeoutValidationTest extends AbstractTestRealmKeycloakTest { UserSessionModel userSession = keycloakSession.sessions().createUserSession( realm, - keycloakSession.users().getUserByUsername("user1", realm), + keycloakSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null ); ClientModel client = realm.getClientByClientId("account"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/AuthenticationSessionProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/AuthenticationSessionProviderTest.java index fa3cc347c4..b6110b9549 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/AuthenticationSessionProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/AuthenticationSessionProviderTest.java @@ -70,8 +70,8 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak RealmModel realm = session.realms().getRealm("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); UserManager um = new UserManager(session); if (user1 != null) { @@ -121,13 +121,13 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak // Update and commit authSession.setAction("foo-updated"); rootAuthSession.setTimestamp(200); - authSession.setAuthenticatedUser(currentSession.users().getUserByUsername("user1", realm)); + authSession.setAuthenticatedUser(currentSession.users().getUserByUsername(realm, "user1")); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD3) -> { KeycloakSession currentSession = sessionCRUD3; RealmModel realm = currentSession.realms().getRealm("test"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); // Ensure currentSession was updated RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, rootAuthSessionID.get()); @@ -162,7 +162,7 @@ public class AuthenticationSessionProviderTest extends AbstractTestRealmKeycloak RealmModel realm = currentSession.realms().getRealm("test"); ClientModel client1 = realm.getClientByClientId("test-app"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); AuthenticationSessionModel authSession = currentSession.authenticationSessions().createRootAuthenticationSession(realm) .createAuthenticationSession(client1); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java index 6158b9e413..b4cab0be7b 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java @@ -136,14 +136,14 @@ public class CacheTest extends AbstractTestRealmKeycloakTest { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("joel", realm); + UserModel user = session.users().getUserByUsername(realm, "joel"); long grantedRolesCount = user.getRoleMappingsStream().count(); ClientModel client = realm.getClientByClientId("foo"); realm.removeClient(client.getId()); realm = session.realms().getRealmByName("test"); - user = session.users().getUserByUsername("joel", realm); + user = session.users().getUserByUsername(realm, "joel"); Set roles = user.getRoleMappingsStream().collect(Collectors.toSet()); for (RoleModel role : roles) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CompositeRolesModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CompositeRolesModelTest.java index d963ea710b..fca0c66cf1 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CompositeRolesModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CompositeRolesModelTest.java @@ -127,7 +127,7 @@ public class CompositeRolesModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = session5.realms().getRealm("TestComposites"); - Set requestedRoles = getRequestedRoles(realm.getClientByClientId("APP_COMPOSITE_APPLICATION"), session.users().getUserByUsername("APP_COMPOSITE_USER", realm)); + Set requestedRoles = getRequestedRoles(realm.getClientByClientId("APP_COMPOSITE_APPLICATION"), session.users().getUserByUsername(realm, "APP_COMPOSITE_USER")); Assert.assertEquals(5, requestedRoles.size()); assertContains(realm, "APP_COMPOSITE_APPLICATION", "APP_COMPOSITE_ROLE", requestedRoles); @@ -136,25 +136,25 @@ public class CompositeRolesModelTest extends AbstractTestRealmKeycloakTest { assertContains(realm, "APP_ROLE_APPLICATION", "APP_ROLE_1", requestedRoles); assertContains(realm, "realm", "REALM_ROLE_1", requestedRoles); - Set requestedRoles2 = getRequestedRoles(realm.getClientByClientId("APP_COMPOSITE_APPLICATION"), session5.users().getUserByUsername("REALM_APP_COMPOSITE_USER", realm)); + Set requestedRoles2 = getRequestedRoles(realm.getClientByClientId("APP_COMPOSITE_APPLICATION"), session5.users().getUserByUsername(realm, "REALM_APP_COMPOSITE_USER")); Assert.assertEquals(4, requestedRoles2.size()); assertContains(realm, "APP_ROLE_APPLICATION", "APP_ROLE_1", requestedRoles2); - requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_COMPOSITE_1_APPLICATION"), session5.users().getUserByUsername("REALM_COMPOSITE_1_USER", realm)); + requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_COMPOSITE_1_APPLICATION"), session5.users().getUserByUsername(realm, "REALM_COMPOSITE_1_USER")); Assert.assertEquals(1, requestedRoles.size()); assertContains(realm, "realm", "REALM_COMPOSITE_1", requestedRoles); - requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_COMPOSITE_2_APPLICATION"), session5.users().getUserByUsername("REALM_COMPOSITE_1_USER", realm)); + requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_COMPOSITE_2_APPLICATION"), session5.users().getUserByUsername(realm, "REALM_COMPOSITE_1_USER")); Assert.assertEquals(3, requestedRoles.size()); assertContains(realm, "realm", "REALM_COMPOSITE_1", requestedRoles); assertContains(realm, "realm", "REALM_COMPOSITE_CHILD", requestedRoles); assertContains(realm, "realm", "REALM_ROLE_4", requestedRoles); - requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_ROLE_1_APPLICATION"), session5.users().getUserByUsername("REALM_COMPOSITE_1_USER", realm)); + requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_ROLE_1_APPLICATION"), session5.users().getUserByUsername(realm, "REALM_COMPOSITE_1_USER")); Assert.assertEquals(1, requestedRoles.size()); assertContains(realm, "realm", "REALM_ROLE_1", requestedRoles); - requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_COMPOSITE_1_APPLICATION"), session5.users().getUserByUsername("REALM_ROLE_1_USER", realm)); + requestedRoles = getRequestedRoles(realm.getClientByClientId("REALM_COMPOSITE_1_APPLICATION"), session5.users().getUserByUsername(realm, "REALM_ROLE_1_USER")); Assert.assertEquals(1, requestedRoles.size()); assertContains(realm, "realm", "REALM_ROLE_1", requestedRoles); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java index 6e929316dc..ee40452954 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/ConcurrentTransactionsTest.java @@ -222,10 +222,10 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { try { // Read user attribute RealmModel realm = session1.realms().getRealmByName("original"); - UserModel john = session1.users().getUserByUsername("john", realm); + UserModel john = session1.users().getUserByUsername(realm, "john"); String attrVal = john.getFirstAttribute("foo"); - UserModel john2 = session1.users().getUserByUsername("john2", realm); + UserModel john2 = session1.users().getUserByUsername(realm, "john2"); String attrVal2 = john2.getFirstAttribute("foo"); // Wait until it's read in both threads @@ -277,8 +277,8 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel realmUser1 = currentSession.users().getUserByUsername(user1, realm); - UserModel realmUser2 = currentSession.users().getUserByUsername(user2, realm); + UserModel realmUser1 = currentSession.users().getUserByUsername(realm, user1); + UserModel realmUser2 = currentSession.users().getUserByUsername(realm, user2); UserManager um = new UserManager(currentSession); if (realmUser1 != null) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CredentialModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CredentialModelTest.java index 60e455b51b..65f6461e5a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CredentialModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CredentialModelTest.java @@ -41,7 +41,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) .collect(Collectors.toList()); Assert.assertEquals(1, list.size()); @@ -59,7 +59,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); // Assert priorities: password, otp1, otp2 List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -78,7 +78,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); // Assert priorities: password, otp2, otp1 List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -91,7 +91,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); // Assert priorities: otp2, password, otp1 List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -104,7 +104,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); // Assert priorities: otp2, otp1, password List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -117,7 +117,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); // Assert priorities: otp2, otp1, password List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) @@ -130,7 +130,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { RealmModel realm = currentSession.realms().getRealmByName("test"); - UserModel user = currentSession.users().getUserByUsername("test-user@localhost", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); // Assert priorities: otp2, password List list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java index bade400d3f..c666daa761 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java @@ -77,8 +77,8 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest { createObjects(currentSession, realm1); createObjects(currentSession, realm2); - UserModel r1user1 = currentSession.users().getUserByUsername("user1", realm1); - UserModel r2user1 = currentSession.users().getUserByUsername("user1", realm2); + UserModel r1user1 = currentSession.users().getUserByUsername(realm1, "user1"); + UserModel r2user1 = currentSession.users().getUserByUsername(realm2, "user1"); r1user1Atomic.set(r1user1); @@ -95,7 +95,7 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest { Assert.assertTrue(currentSession.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass2"))); // Test searching - Assert.assertEquals(2, currentSession.users().searchForUserStream("user", realm1).count()); + Assert.assertEquals(2, currentSession.users().searchForUserStream(realm1, "user").count()); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser2) -> { @@ -107,14 +107,14 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest { UserModel r1user1 = r1user1Atomic.get(); currentSession.users().removeUser(realm1, r1user1); - UserModel user2 = currentSession.users().getUserByUsername("user2", realm1); + UserModel user2 = currentSession.users().getUserByUsername(realm1, "user2"); currentSession.users().removeUser(realm1, user2); - Assert.assertEquals(0, currentSession.users().searchForUserStream("user", realm1).count()); - Assert.assertEquals(2, currentSession.users().searchForUserStream("user", realm2).count()); + Assert.assertEquals(0, currentSession.users().searchForUserStream(realm1, "user").count()); + Assert.assertEquals(2, currentSession.users().searchForUserStream(realm2, "user").count()); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm1); - UserModel user1a = currentSession.users().getUserByUsername("user1", realm2); + UserModel user1 = currentSession.users().getUserByUsername(realm1, "user1"); + UserModel user1a = currentSession.users().getUserByUsername(realm2, "user1"); UserManager um = new UserManager(currentSession); if (user1 != null) { @@ -174,8 +174,8 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest { Assert.assertEquals(r2Role1, realm2.getRoleById(r2Role1.getId())); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm1); - UserModel user1a = currentSession.users().getUserByUsername("user1", realm2); + UserModel user1 = currentSession.users().getUserByUsername(realm1, "user1"); + UserModel user1a = currentSession.users().getUserByUsername(realm2, "user1"); UserManager um = new UserManager(currentSession); if (user1 != null) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/OwnerReplacementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/OwnerReplacementTest.java index 0522529d0b..1db1276b13 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/OwnerReplacementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/OwnerReplacementTest.java @@ -417,7 +417,7 @@ public class OwnerReplacementTest extends AbstractKeycloakTest { // Get ID of some object from realm1 ((session, realm1) -> { - UserModel user = session.users().getUserByUsername("test-user@localhost", realm1); + UserModel user = session.users().getUserByUsername(realm1, "test-user@localhost"); UserSessionModel userSession = session.sessions().createUserSession(realm1, user, user.getUsername(), "1.2.3.4", "bar", false, null, null); return userSession.getId(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java index 58360ffe64..30c3577bce 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentModelTest.java @@ -71,10 +71,10 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { if (realm != null) { session.sessions().removeUserSessions(realm); - UserModel user = session.users().getUserByUsername("user", realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); - UserModel user3 = session.users().getUserByUsername("user3", realm); + UserModel user = session.users().getUserByUsername(realm, "user"); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); + UserModel user3 = session.users().getUserByUsername(realm, "user3"); UserManager um = new UserManager(session); if (user != null) { @@ -163,8 +163,8 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { ClientModel fooClient = realm.getClientByClientId("foo-client"); ClientModel barClient = realm.getClientByClientId("bar-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); UserConsentModel johnFooConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnFooConsent.getGrantedClientScopes().size(), 1); @@ -205,8 +205,8 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); Assert.assertEquals(2, currentSession.users().getConsentsStream(realm, john.getId()).count()); @@ -240,7 +240,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealm("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(1, johnConsent.getGrantedClientScopes().size()); @@ -257,7 +257,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealm("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0); @@ -274,8 +274,8 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealm("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); currentSession.users().revokeConsentForClient(realm, john.getId(), fooClient.getId()); ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); @@ -289,9 +289,9 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { ClientModel fooClient = realm.getClientByClientId("foo-client"); ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId())); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); Assert.assertNull(currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId())); }); } @@ -304,9 +304,9 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sessionUT; RealmModel realm = currentSession.realms().getRealm("original"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); currentSession.users().removeUser(realm, john); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); currentSession.users().removeUser(realm, mary); }); } @@ -329,7 +329,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0); @@ -359,7 +359,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { ClientModel fooClient = realm.getClientByClientId("foo-client"); Assert.assertNull(realm.getClientByClientId("bar-client")); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); ClientModel barClient = realm.getClientByClientId("bar-client"); UserConsentModel johnFooConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); @@ -388,7 +388,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest { ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); Assert.assertNull(hardcodedClient); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); Assert.assertEquals(1, currentSession.users().getConsentsStream(realm, mary.getId()).count()); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java index 00e711cf61..5ea8735b83 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserConsentWithUserStorageModelTest.java @@ -72,10 +72,10 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo if (realm != null) { session.sessions().removeUserSessions(realm); - UserModel user = session.users().getUserByUsername("user", realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); - UserModel user3 = session.users().getUserByUsername("user3", realm); + UserModel user = session.users().getUserByUsername(realm, "user"); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); + UserModel user3 = session.users().getUserByUsername(realm, "user3"); UserManager um = new UserManager(session); if (user != null) { @@ -171,8 +171,8 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo ClientModel fooClient = realm.getClientByClientId("foo-client"); ClientModel barClient = realm.getClientByClientId("bar-client"); - UserModel john = currentSessionCT.users().getUserByUsername("john", realm); - UserModel mary = currentSessionCT.users().getUserByUsername("mary", realm); + UserModel john = currentSessionCT.users().getUserByUsername(realm, "john"); + UserModel mary = currentSessionCT.users().getUserByUsername(realm, "mary"); UserConsentModel johnFooConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnFooConsent.getGrantedClientScopes().size(), 1); @@ -213,8 +213,8 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSessionACT.users().getUserByUsername("john", realm); - UserModel mary = currentSessionACT.users().getUserByUsername("mary", realm); + UserModel john = currentSessionACT.users().getUserByUsername(realm, "john"); + UserModel mary = currentSessionACT.users().getUserByUsername(realm, "mary"); Assert.assertEquals(2, currentSession.users().getConsentsStream(realm, john.getId()).count()); @@ -248,7 +248,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo RealmModel realm = currentSession.realms().getRealmByName("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(1, johnConsent.getGrantedClientScopes().size()); @@ -265,7 +265,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo RealmModel realm = currentSession.realms().getRealmByName("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0); @@ -282,8 +282,8 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo RealmModel realm = currentSession.realms().getRealmByName("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); currentSession.users().revokeConsentForClient(realm, john.getId(), fooClient.getId()); ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); @@ -297,10 +297,10 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo ClientModel fooClient = realm.getClientByClientId("foo-client"); ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId())); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); Assert.assertNull(currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId())); }); } @@ -314,9 +314,9 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo KeycloakSession currentSession = sessionDelete; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); currentSession.users().removeUser(realm, john); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); currentSession.users().removeUser(realm, mary); }); } @@ -339,7 +339,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo RealmModel realm = currentSession.realms().getRealmByName("original"); ClientModel fooClient = realm.getClientByClientId("foo-client"); - UserModel john = currentSession.users().getUserByUsername("john", realm); + UserModel john = currentSession.users().getUserByUsername(realm, "john"); UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0); @@ -370,7 +370,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo ClientModel fooClient = realm.getClientByClientId("foo-client"); Assert.assertNull(realm.getClientByClientId("bar-client")); - UserModel john = realmManager.getSession().users().getUserByUsername("john", realm); + UserModel john = realmManager.getSession().users().getUserByUsername(realm, "john"); UserConsentModel johnFooConsent = realmManager.getSession().users().getConsentByClient(realm, john.getId(), fooClient.getId()); Assert.assertEquals(johnFooConsent.getGrantedClientScopes().size(), 1); @@ -398,7 +398,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client"); Assert.assertNull(hardcodedClient); - UserModel mary = currentSession.users().getUserByUsername("mary", realm); + UserModel mary = currentSession.users().getUserByUsername(realm, "mary"); Assert.assertEquals(1, currentSession.users().getConsentsStream(realm, mary.getId()).count()); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserModelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserModelTest.java index ebda71b0a4..7039eae89f 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserModelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserModelTest.java @@ -90,24 +90,24 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { user.addRequiredAction(RequiredAction.UPDATE_PASSWORD); RealmModel searchRealm = currentSession.realms().getRealm(realm.getId()); - UserModel persisted = currentSession.users().getUserByUsername("user", searchRealm); + UserModel persisted = currentSession.users().getUserByUsername(searchRealm, "user"); assertUserModel(user, persisted); searchRealm = currentSession.realms().getRealm(realm.getId()); - UserModel persisted2 = currentSession.users().getUserById(user.getId(), searchRealm); + UserModel persisted2 = currentSession.users().getUserById(searchRealm, user.getId()); assertUserModel(user, persisted2); Map attributes = new HashMap<>(); attributes.put(UserModel.LAST_NAME, "last-name"); - List search = currentSession.users().searchForUserStream(attributes, realm) + List search = currentSession.users().searchForUserStream(realm, attributes) .collect(Collectors.toList()); Assert.assertThat(search, hasSize(1)); Assert.assertThat(search.get(0).getUsername(), equalTo("user")); attributes.clear(); attributes.put(UserModel.EMAIL, "email"); - search = currentSession.users().searchForUserStream(attributes, realm) + search = currentSession.users().searchForUserStream(realm, attributes) .collect(Collectors.toList()); Assert.assertThat(search, hasSize(1)); Assert.assertThat(search.get(0).getUsername(), equalTo("user")); @@ -115,7 +115,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { attributes.clear(); attributes.put(UserModel.LAST_NAME, "last-name"); attributes.put(UserModel.EMAIL, "email"); - search = currentSession.users().searchForUserStream(attributes, realm).collect(Collectors.toList()); + search = currentSession.users().searchForUserStream(realm, attributes).collect(Collectors.toList()); Assert.assertThat(search, hasSize(1)); Assert.assertThat(search.get(0).getUsername(), equalTo("user")); }); @@ -179,21 +179,21 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { String id = realm.getId(); realm = currentSession.realms().getRealm(id); - user = currentSession.users().getUserByUsername("user", realm); + user = currentSession.users().getUserByUsername(realm, "user"); requiredActions = user.getRequiredActionsStream().collect(Collectors.toList()); Assert.assertThat(requiredActions, hasSize(1)); Assert.assertThat(requiredActions, contains(RequiredAction.CONFIGURE_TOTP.name())); user.addRequiredAction(RequiredAction.CONFIGURE_TOTP); - user = currentSession.users().getUserByUsername("user", realm); + user = currentSession.users().getUserByUsername(realm, "user"); requiredActions = user.getRequiredActionsStream().collect(Collectors.toList()); Assert.assertThat(requiredActions, hasSize(1)); Assert.assertThat(requiredActions, contains(RequiredAction.CONFIGURE_TOTP.name())); user.addRequiredAction(RequiredAction.VERIFY_EMAIL.name()); - user = currentSession.users().getUserByUsername("user", realm); + user = currentSession.users().getUserByUsername(realm, "user"); requiredActions = user.getRequiredActionsStream().collect(Collectors.toList()); Assert.assertThat(requiredActions, hasSize(2)); @@ -203,14 +203,14 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { ); user.removeRequiredAction(RequiredAction.CONFIGURE_TOTP.name()); - user = currentSession.users().getUserByUsername("user", realm); + user = currentSession.users().getUserByUsername(realm, "user"); requiredActions = user.getRequiredActionsStream().collect(Collectors.toList()); Assert.assertThat(requiredActions, hasSize(1)); Assert.assertThat(requiredActions, contains(RequiredAction.VERIFY_EMAIL.name())); user.removeRequiredAction(RequiredAction.VERIFY_EMAIL.name()); - user = currentSession.users().getUserByUsername("user", realm); + user = currentSession.users().getUserByUsername(realm, "user"); requiredActions = user.getRequiredActionsStream().collect(Collectors.toList()); Assert.assertThat(requiredActions, empty()); @@ -242,7 +242,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealmByName("original"); // Test read attributes - UserModel user = currentSession.users().getUserByUsername("user", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "user"); List attrVals = user.getAttributeStream("key1").collect(Collectors.toList()); Assert.assertThat(attrVals, hasSize(1)); @@ -272,7 +272,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesMultipleAtr3; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user = currentSession.users().getUserByUsername("user", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "user"); Assert.assertThat(user.getFirstAttribute("key1"), nullValue()); List attrVals = user.getAttributeStream("key2").collect(Collectors.toList()); @@ -300,7 +300,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesUpdateAtr2; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user = currentSession.users().getUserByUsername("user", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "user"); // Update attribute List attrVals = new ArrayList<>(Arrays.asList("val2")); @@ -352,7 +352,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm = currentSession.realms().getRealmByName("original"); Map> expected = expectedAtomic.get(); - Assert.assertThat(currentSession.users().getUserByUsername("user", realm).getAttributes(), equalTo(expected)); + Assert.assertThat(currentSession.users().getUserByUsername(realm, "user").getAttributes(), equalTo(expected)); }); } @@ -371,9 +371,9 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesSearchString1; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); - List users = currentSession.users().searchForUserStream("user", realm, 0, 7) + List users = currentSession.users().searchForUserStream(realm, "user", 0, 7) .collect(Collectors.toList()); Assert.assertThat(users, hasSize(1)); Assert.assertThat(users, contains(user1)); @@ -409,26 +409,26 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesSearchAtr2; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); - UserModel user2 = currentSession.users().getUserByUsername("user2", realm); - UserModel user3 = currentSession.users().getUserByUsername("user3", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); + UserModel user2 = currentSession.users().getUserByUsername(realm, "user2"); + UserModel user3 = currentSession.users().getUserByUsername(realm, "user3"); - List users = currentSession.users().searchForUserByUserAttributeStream("key1", "value1", realm) + List users = currentSession.users().searchForUserByUserAttributeStream(realm, "key1", "value1") .collect(Collectors.toList()); Assert.assertThat(users, hasSize(2)); Assert.assertThat(users, containsInAnyOrder(user1, user2)); - users = currentSession.users().searchForUserByUserAttributeStream("key2", "value21", realm) + users = currentSession.users().searchForUserByUserAttributeStream(realm, "key2", "value21") .collect(Collectors.toList()); Assert.assertThat(users, hasSize(2)); Assert.assertThat(users, containsInAnyOrder(user1, user3)); - users = currentSession.users().searchForUserByUserAttributeStream("key2", "value22", realm) + users = currentSession.users().searchForUserByUserAttributeStream(realm, "key2", "value22") .collect(Collectors.toList()); Assert.assertThat(users, hasSize(1)); Assert.assertThat(users, contains(user2)); - users = currentSession.users().searchForUserByUserAttributeStream("key3", "value3", realm) + users = currentSession.users().searchForUserByUserAttributeStream(realm, "key3", "value3") .collect(Collectors.toList()); Assert.assertThat(users, empty()); }); @@ -454,7 +454,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { // Search Assert.assertThat(currentSession.users().getServiceAccount(client), nullValue()); - List users = currentSession.users().searchForUserStream("John Doe", realm) + List users = currentSession.users().searchForUserStream(realm, "John Doe") .collect(Collectors.toList()); Assert.assertThat(users, hasSize(2)); Assert.assertThat(users, containsInAnyOrder(user1, user2)); @@ -467,14 +467,14 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesServiceLink2; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); - UserModel user2 = currentSession.users().getUserByUsername("user2", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); + UserModel user2 = currentSession.users().getUserByUsername(realm, "user2"); // Search and assert service account user not found ClientModel client = realm.getClientByClientId("foo"); UserModel searched = currentSession.users().getServiceAccount(client); Assert.assertThat(searched, equalTo(user1)); - List users = currentSession.users().searchForUserStream("John Doe", realm) + List users = currentSession.users().searchForUserStream(realm, "John Doe") .collect(Collectors.toList()); Assert.assertThat(users, hasSize(1)); Assert.assertThat(users, contains(user2)); @@ -501,7 +501,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesServiceLink3; RealmModel realm = currentSession.realms().getRealmByName("original"); // Assert service account removed as well - Assert.assertThat(currentSession.users().getUserByUsername("user1", realm), nullValue()); + Assert.assertThat(currentSession.users().getUserByUsername(realm, "user1"), nullValue()); }); } @@ -535,13 +535,13 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { RealmModel realm1 = currentSession.realms().getRealmByName("realm1"); RoleModel role1 = realm1.getRole("role1"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm1); - UserModel user2 = currentSession.users().getUserByUsername("user2", realm1); + UserModel user1 = currentSession.users().getUserByUsername(realm1, "user1"); + UserModel user2 = currentSession.users().getUserByUsername(realm1, "user2"); Assert.assertTrue(user1.hasRole(role1)); Assert.assertTrue(user2.hasRole(role1)); RealmModel realm2 = currentSession.realms().getRealmByName("realm2"); - UserModel realm2User1 = currentSession.users().getUserByUsername("user1", realm2); + UserModel realm2User1 = currentSession.users().getUserByUsername(realm2, "user1"); Assert.assertFalse(realm2User1.hasRole(role1)); currentSession.realms().removeRealm(realm1.getId()); @@ -565,7 +565,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesUserNotBefore2; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); int notBefore = currentSession.users().getNotBeforeOfUser(realm, user1); Assert.assertThat(notBefore, equalTo(10)); @@ -577,7 +577,7 @@ public class UserModelTest extends AbstractTestRealmKeycloakTest { KeycloakSession currentSession = sesUserNotBefore3; RealmModel realm = currentSession.realms().getRealmByName("original"); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); int notBefore = currentSession.users().getNotBeforeOfUser(realm, user1); Assert.assertThat(notBefore, equalTo(20)); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java index 38a9e4321f..f37ede6c5e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionInitializerTest.java @@ -71,8 +71,8 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest { RealmModel realm = session.realms().getRealmByName("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); UserManager um = new UserManager(session); if (user1 != null) @@ -121,9 +121,9 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest { .collect(Collectors.toList()); UserSessionProviderTest.assertSessions(loadedSessions, origSessions); - assertSessionLoaded(loadedSessions, origSessions[0].getId(), currentSession.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party"); - assertSessionLoaded(loadedSessions, origSessions[1].getId(), currentSession.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app"); - assertSessionLoaded(loadedSessions, origSessions[2].getId(), currentSession.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app"); + assertSessionLoaded(loadedSessions, origSessions[0].getId(), currentSession.users().getUserByUsername(realm, "user1"), "127.0.0.1", started, started, "test-app", "third-party"); + assertSessionLoaded(loadedSessions, origSessions[1].getId(), currentSession.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app"); + assertSessionLoaded(loadedSessions, origSessions[2].getId(), currentSession.users().getUserByUsername(realm, "user2"), "127.0.0.3", started, started, "test-app"); }); } @@ -172,7 +172,7 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest { .collect(Collectors.toList()); assertThat("Size of loaded Sessions", loadedSessions.size(), is(1)); - assertSessionLoaded(loadedSessions, origSessions[0].getId(), currentSession.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "third-party"); + assertSessionLoaded(loadedSessions, origSessions[0].getId(), currentSession.users().getUserByUsername(realm, "user1"), "127.0.0.1", started, started, "third-party"); // Revert client realm.addClient("test-app"); @@ -246,15 +246,15 @@ public class UserSessionInitializerTest extends AbstractTestRealmKeycloakTest { RealmModel realm = session.realms().getRealmByName(realmName); UserSessionModel[] sessions = new UserSessionModel[3]; - sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state"); createClientSession(session, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state"); - sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state"); - sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.3", "form", true, null, null); + sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.3", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state"); return sessions; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionPersisterProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionPersisterProviderTest.java index 78ecf46d76..47754c5da8 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionPersisterProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionPersisterProviderTest.java @@ -75,8 +75,8 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT testingClient.server().run(session -> { RealmModel realm = session.realms().getRealm("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); UserManager um = new UserManager(session); if (user1 != null) { @@ -118,7 +118,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionWL3) -> {// Assert online session RealmModel realm = sessionWL3.realms().getRealm("test"); List loadedSessions = loadPersistedSessionsPaginated(sessionWL3, false, 1, 1, 1); - UserSessionProviderTest.assertSession(loadedSessions.get(0), sessionWL3.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party"); + UserSessionProviderTest.assertSession(loadedSessions.get(0), sessionWL3.users().getUserByUsername(realm, "user1"), "127.0.0.1", started, started, "test-app", "third-party"); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionWL4) -> { @@ -127,9 +127,9 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT List loadedSessions = loadPersistedSessionsPaginated(sessionWL4, true, 2, 2, 3); UserSessionProviderTest.assertSessions(loadedSessions, origSessions[0]); - assertSessionLoaded(loadedSessions, origSessions[0][0].getId(), sessionWL4.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party"); - assertSessionLoaded(loadedSessions, origSessions[0][1].getId(), sessionWL4.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app"); - assertSessionLoaded(loadedSessions, origSessions[0][2].getId(), sessionWL4.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app"); + assertSessionLoaded(loadedSessions, origSessions[0][0].getId(), sessionWL4.users().getUserByUsername(realm, "user1"), "127.0.0.1", started, started, "test-app", "third-party"); + assertSessionLoaded(loadedSessions, origSessions[0][1].getId(), sessionWL4.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app"); + assertSessionLoaded(loadedSessions, origSessions[0][2].getId(), sessionWL4.users().getUserByUsername(realm, "user2"), "127.0.0.3", started, started, "test-app"); }); } @@ -177,7 +177,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT UserSessionModel persistedSession = loadedSessions.get(0); persistedSessionAt.set(persistedSession); - UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app"); + UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app"); // create new clientSession AuthenticatedClientSessionModel clientSession = createClientSession(currentSession, realm.getClientByClientId("third-party"), currentSession.sessions().getUserSession(realm, persistedSession.getId()), @@ -208,7 +208,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT // Assert clientSession removed loadedSessions = loadPersistedSessionsPaginated(currentSession, true, 10, 1, 1); persistedSession = loadedSessions.get(0); - UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app"); + UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app"); // Remove userSession persister.removeUserSession(persistedSession.getId(), true); @@ -234,7 +234,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT fooRealm.addClient("foo-app"); currentSession.users().addUser(fooRealm, "user3"); - UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername("user3", fooRealm), "user3", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null); userSessionID.set(userSession.getId()); createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state"); @@ -283,7 +283,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT fooRealm.addClient("bar-app"); currentSession.users().addUser(fooRealm, "user3"); - UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername("user3", fooRealm), "user3", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null); userSessionID.set(userSession.getId()); createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state"); @@ -308,7 +308,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT // Assert session was persisted with both clientSessions UserSessionModel persistedSession = loadPersistedSessionsPaginated(currentSession, true, 10, 1, 1).get(0); - UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername("user3", fooRealm), "127.0.0.1", started, started, "foo-app", "bar-app"); + UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app"); // Remove foo-app client ClientModel client = fooRealm.getClientByClientId("foo-app"); @@ -323,7 +323,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT // Assert just one bar-app clientSession persisted now UserSessionModel persistedSession = loadPersistedSessionsPaginated(currentSession, true, 10, 1, 1).get(0); - UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername("user3", fooRealm), "127.0.0.1", started, started, "bar-app"); + UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "bar-app"); // Remove bar-app client ClientModel client = fooRealm.getClientByClientId("bar-app"); @@ -377,7 +377,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT loadPersistedSessionsPaginated(currentSession, true, 10, 1, 2); // Properly delete user and assert his offlineSession removed - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); new UserManager(currentSession).removeUser(realm, user1); }); @@ -390,11 +390,11 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT List loadedSessions = loadPersistedSessionsPaginated(currentSession, true, 10, 1, 1); UserSessionModel persistedSession = loadedSessions.get(0); - UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app"); + UserSessionProviderTest.assertSession(persistedSession, currentSession.users().getUserByUsername(realm, "user2"), "127.0.0.3", started, started, "test-app"); // KEYCLOAK-2431 Assert that userSessionPersister is resistent even to situation, when users are deleted "directly". // No exception will happen. However session will be still there - UserModel user2 = currentSession.users().getUserByUsername("user2", realm); + UserModel user2 = currentSession.users().getUserByUsername(realm, "user2"); currentSession.users().removeUser(realm, user2); loadedSessions = loadPersistedSessionsPaginated(currentSession, true, 10, 1, 1); @@ -428,7 +428,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT // Create 10 userSessions - each having 1 clientSession List userSessions = new ArrayList<>(); - UserModel user = currentSession.users().getUserByUsername("user1", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "user1"); for (int i = 0; i < 20; i++) { // Having different offsets for each session (to ensure that lastSessionRefresh is also different) @@ -459,7 +459,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT RealmModel realm = currentSession.realms().getRealm("test"); List loadedSessions = loadPersistedSessionsPaginated(currentSession, true, 2, 10, 20); - UserModel user = currentSession.users().getUserByUsername("user1", realm); + UserModel user = currentSession.users().getUserByUsername(realm, "user1"); ClientModel testApp = realm.getClientByClientId("test-app"); for (UserSessionModel loadedSession : loadedSessions) { @@ -514,7 +514,7 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT // Test the updated session is still in persister. Not updated session is not there anymore List loadedSessions = loadPersistedSessionsPaginated(sessionES3, true, 10, 1, 1); UserSessionModel persistedSession = loadedSessions.get(0); - UserSessionProviderTest.assertSession(persistedSession, sessionES3.users().getUserByUsername("user1", realm), "127.0.0.2", started, lastSessionRefresh, "test-app"); + UserSessionProviderTest.assertSession(persistedSession, sessionES3.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, lastSessionRefresh, "test-app"); } finally { // Cleanup @@ -535,15 +535,15 @@ public class UserSessionPersisterProviderTest extends AbstractTestRealmKeycloakT private UserSessionModel[] createSessions(KeycloakSession session) { RealmModel realm = session.realms().getRealm("test"); UserSessionModel[] sessions = new UserSessionModel[3]; - sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state"); createClientSession(session, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state"); - sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state"); - sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.3", "form", true, null, null); + sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.3", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state"); return sessions; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderOfflineTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderOfflineTest.java index ae9bfbe2a7..0ed1d24e63 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderOfflineTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderOfflineTest.java @@ -81,8 +81,8 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); UserManager um = new UserManager(session); if (user1 != null) { @@ -132,7 +132,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes } // Find clients with offline token - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); Set clients = sessionManager.findClientsWithOfflineToken(realm, user1); Assert.assertEquals(clients.size(), 2); @@ -140,7 +140,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes Assert.assertTrue(client.getClientId().equals("test-app") || client.getClientId().equals("third-party")); } - UserModel user2 = currentSession.users().getUserByUsername("user2", realm); + UserModel user2 = currentSession.users().getUserByUsername(realm, "user2"); clients = sessionManager.findClientsWithOfflineToken(realm, user2); Assert.assertEquals(clients.size(), 1); @@ -176,8 +176,8 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes Assert.assertEquals("127.0.0.1", thirdpartySessions.get(0).getIpAddress()); Assert.assertEquals("user1", thirdpartySessions.get(0).getUser().getUsername()); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); - UserModel user2 = currentSession.users().getUserByUsername("user2", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); + UserModel user2 = currentSession.users().getUserByUsername(realm, "user2"); Set clients = sessionManager.findClientsWithOfflineToken(realm, user1); Assert.assertEquals(1, clients.size()); @@ -211,7 +211,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes Assert.assertEquals("127.0.0.3", testAppSessions.get(0).getIpAddress()); Assert.assertEquals("user2", testAppSessions.get(0).getUser().getUsername()); - UserModel user1 = currentSession.users().getUserByUsername("user1", realm); + UserModel user1 = currentSession.users().getUserByUsername(realm, "user1"); Set clients = sessionManager.findClientsWithOfflineToken(realm, user1); Assert.assertEquals(0, clients.size()); @@ -231,7 +231,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes fooRealm.addClient("foo-app"); currentSession.users().addUser(fooRealm, "user3"); - UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername("user3", fooRealm), "user3", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null); userSessionID.set(userSession.getId()); createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state"); @@ -298,7 +298,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes fooRealm.addClient("bar-app"); currentSession.users().addUser(fooRealm, "user3"); - UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername("user3", fooRealm), "user3", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null); userSessionID.set(userSession.getId()); createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state"); @@ -321,7 +321,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes // Assert currentSession was persisted with both clientSessions UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get()); - assertSession(offlineSession, currentSession.users().getUserByUsername("user3", fooRealm), "127.0.0.1", started, started, "foo-app", "bar-app"); + assertSession(offlineSession, currentSession.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app"); // Remove foo-app client ClientModel client = fooRealm.getClientByClientId("foo-app"); @@ -360,7 +360,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes currentSession = sessionTearDown; RealmManager realmMgr = new RealmManager(currentSession); RealmModel fooRealm = realmMgr.getRealm("foo"); - UserModel user3 = currentSession.users().getUserByUsername("user3", fooRealm); + UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3"); // Remove user3 new UserManager(currentSession).removeUser(fooRealm, user3); @@ -389,7 +389,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes fooRealm.addClient("foo-app"); currentSession.users().addUser(fooRealm, "user3"); - UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername("user3", fooRealm), "user3", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null); userSessionID.set(userSession.getId()); createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state"); @@ -409,7 +409,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes RealmManager realmMgr = new RealmManager(currentSession); RealmModel fooRealm = realmMgr.getRealm("foo"); - UserModel user3 = currentSession.users().getUserByUsername("user3", fooRealm); + UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3"); // Assert session was persisted with both clientSessions UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get()); @@ -424,7 +424,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes RealmManager realmMgr = new RealmManager(currentSession); RealmModel fooRealm = realmMgr.getRealm("foo"); - UserModel user3 = currentSession.users().getUserByUsername("user3", fooRealm); + UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3"); // Remove user3 new UserManager(currentSession).removeUser(fooRealm, user3); @@ -615,7 +615,7 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes private static UserSessionModel[] createSessions(KeycloakSession session) { UserSessionModel[] sessions = new UserSessionModel[3]; - sessions[0] = session.sessions().createUserSession(realm, currentSession.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + sessions[0] = session.sessions().createUserSession(realm, currentSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); Set roles = new HashSet(); roles.add("one"); @@ -628,10 +628,10 @@ public class UserSessionProviderOfflineTest extends AbstractTestRealmKeycloakTes createClientSession(session, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state"); createClientSession(session, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state"); - sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state"); - sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.3", "form", true, null, null); + sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.3", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state"); return sessions; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java index a850384b82..8709e9d799 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/UserSessionProviderTest.java @@ -86,8 +86,8 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { testingClient.server().run( session -> { RealmModel realm = session.realms().getRealmByName("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); UserManager um = new UserManager(session); if (user1 != null) { @@ -106,9 +106,9 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { RealmModel realm = session.realms().getRealmByName("test"); UserSessionModel[] sessions = createSessions(session); - assertSession(session.sessions().getUserSession(realm, sessions[0].getId()), session.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party"); - assertSession(session.sessions().getUserSession(realm, sessions[1].getId()), session.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app"); - assertSession(session.sessions().getUserSession(realm, sessions[2].getId()), session.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app"); + assertSession(session.sessions().getUserSession(realm, sessions[0].getId()), session.users().getUserByUsername(realm, "user1"), "127.0.0.1", started, started, "test-app", "third-party"); + assertSession(session.sessions().getUserSession(realm, sessions[1].getId()), session.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app"); + assertSession(session.sessions().getUserSession(realm, sessions[2].getId()), session.users().getUserByUsername(realm, "user2"), "127.0.0.3", started, started, "test-app"); } @Test @@ -140,12 +140,12 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { Time.setOffset(100); UserSessionModel userSession = session.sessions().getUserSession(realm, sessions[0].getId()); - assertSession(userSession, session.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party"); + assertSession(userSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.1", started, started, "test-app", "third-party"); - userSession.restartSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.6", "form", true, null, null); + userSession.restartSession(realm, session.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.6", "form", true, null, null); userSession = session.sessions().getUserSession(realm, sessions[0].getId()); - assertSession(userSession, session.users().getUserByUsername("user2", realm), "127.0.0.6", started + 100, started + 100); + assertSession(userSession, session.users().getUserByUsername(realm, "user2"), "127.0.0.6", started + 100, started + 100); Time.setOffset(0); } @@ -251,9 +251,9 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { } - assertSessions(session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername("user1", realm)) + assertSessions(session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername(realm, "user1")) .collect(Collectors.toList()), sessions[0], sessions[1]); - assertSessions(session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername("user2", realm)) + assertSessions(session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername(realm, "user2")) .collect(Collectors.toList()), sessions[2]); } @@ -267,17 +267,17 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { createSessions(kcSession); }); Map clientSessionsKept = session.sessions().getUserSessionsStream(realm, - session.users().getUserByUsername("user2", realm)) + session.users().getUserByUsername(realm, "user2")) .collect(Collectors.toMap(model -> model.getId(), model -> model.getAuthenticatedClientSessions().keySet().size())); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> { - kcSession.sessions().removeUserSessions(realm, kcSession.users().getUserByUsername("user1", realm)); + kcSession.sessions().removeUserSessions(realm, kcSession.users().getUserByUsername(realm, "user1")); }); - assertEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername("user1", realm)) + assertEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername(realm, "user1")) .count()); List userSessions = session.sessions().getUserSessionsStream(realm, - session.users().getUserByUsername("user2", realm)).collect(Collectors.toList()); + session.users().getUserByUsername(realm, "user2")).collect(Collectors.toList()); assertSame(userSessions.size(), 1); @@ -311,9 +311,9 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { kcSession.sessions().removeUserSessions(realm); }); - assertEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername("user1", realm)) + assertEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername(realm, "user1")) .count()); - assertEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername("user2", realm)) + assertEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername(realm, "user2")) .count()); } @@ -358,7 +358,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { // create an user session that is older than the max lifespan timeout. KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> { Time.setOffset(-(realm.getSsoSessionMaxLifespan() + 1)); - UserSessionModel userSession = session1.sessions().createUserSession(realm, session1.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", false, null, null); + UserSessionModel userSession = session1.sessions().createUserSession(realm, session1.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", false, null, null); expiredUserSessions.add(userSession.getId()); AuthenticatedClientSessionModel clientSession = session1.sessions().createClientSession(realm, client, userSession); assertEquals(userSession, clientSession.getUserSession()); @@ -367,7 +367,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { // create an user session whose last refresh exceeds the max session idle timeout. KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> { Time.setOffset(-(realm.getSsoSessionIdleTimeout() + SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS + 1)); - UserSessionModel s = session1.sessions().createUserSession(realm, session1.users().getUserByUsername("user2", realm), "user2", "127.0.0.1", "form", false, null, null); + UserSessionModel s = session1.sessions().createUserSession(realm, session1.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.1", "form", false, null, null); // no need to explicitly set the last refresh time - it is the same as the creation time. expiredUserSessions.add(s.getId()); }); @@ -375,7 +375,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { // create an user session and associated client session that conforms to the max lifespan and max idle timeouts. Time.setOffset(0); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> { - UserSessionModel userSession = session1.sessions().createUserSession(realm, session1.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", false, null, null); + UserSessionModel userSession = session1.sessions().createUserSession(realm, session1.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", false, null, null); validUserSessions.add(userSession.getId()); validClientSessions.add(session1.sessions().createClientSession(realm, client, userSession).getId()); }); @@ -411,12 +411,12 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> { long sessionsBefore = session1.sessions().getActiveUserSessions(realm, client); - UserSessionModel userSession = session1.sessions().createUserSession("123", realm, session1.users().getUserByUsername("user1", realm), + UserSessionModel userSession = session1.sessions().createUserSession("123", realm, session1.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT); AuthenticatedClientSessionModel clientSession = session1.sessions().createClientSession(realm, client, userSession); assertEquals(userSession, clientSession.getUserSession()); - assertSession(userSession, session.users().getUserByUsername("user1", realm), "127.0.0.1", userSession.getStarted(), userSession.getStarted(), "test-app"); + assertSession(userSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.1", userSession.getStarted(), userSession.getStarted(), "test-app"); // Can find session by ID in current transaction UserSessionModel foundSession = session1.sessions().getUserSession(realm, "123"); @@ -464,7 +464,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { // the session's last refresh also exceeds the default 'session idle' timeout but doesn't exceed the 'session idle remember-me' timeout. KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> { Time.setOffset(-(realm.getSsoSessionMaxLifespan() * 2)); - UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); AuthenticatedClientSessionModel clientSession = kcSession.sessions().createClientSession(realm, client, userSession); assertEquals(userSession, clientSession.getUserSession()); Time.setOffset(-(realm.getSsoSessionIdleTimeout() * 2)); @@ -476,14 +476,14 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { // create an user session with remember-me enabled that is older than the 'max lifespan remember-me' timeout. KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> { Time.setOffset(-(realm.getSsoSessionMaxLifespanRememberMe() + 1)); - UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); expiredUserSessions.add(userSession.getId()); }); // finally create an user session with remember-me enabled whose last refresh exceeds the 'session idle remember-me' timeout. KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> { Time.setOffset(-(realm.getSsoSessionIdleTimeoutRememberMe() + SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS + 1)); - UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername("user2", realm), "user2", "127.0.0.1", "form", true, null, null); + UserSessionModel userSession = kcSession.sessions().createUserSession(realm, kcSession.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.1", "form", true, null, null); // no need to explicitly set the last refresh time - it is the same as the creation time. expiredUserSessions.add(userSession.getId()); }); @@ -561,7 +561,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { try { for (int i = 0; i < 25; i++) { Time.setOffset(i); - UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0." + i, "form", false, null, null); + UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0." + i, "form", false, null, null); AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, realm.getClientByClientId("test-app"), userSession); assertNotNull(clientSession); clientSession.setRedirectUri("http://redirect"); @@ -590,7 +590,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { public void testCreateAndGetInSameTransaction(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); ClientModel client = realm.getClientByClientId("test-app"); - UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); AuthenticatedClientSessionModel clientSession = createClientSession(session, client, userSession, "http://redirect", "state"); UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, userSession.getId()); @@ -606,7 +606,7 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { @ModelTest public void testAuthenticatedClientSessions(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); - UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); ClientModel client1 = realm.getClientByClientId("test-app"); ClientModel client2 = realm.getClientByClientId("third-party"); @@ -755,19 +755,19 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { public static void testOnUserRemoved(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user1 = session.users().getUserByUsername("user1", realm); - UserModel user2 = session.users().getUserByUsername("user2", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); + UserModel user2 = session.users().getUserByUsername(realm, "user2"); UserSessionModel[] sessions = new UserSessionModel[3]; - sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state"); createClientSession(session, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state"); - sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state"); - sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.3", "form", true, null, null); + sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.3", "form", true, null, null); //createClientSession(session, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state"); AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, realm.getClientByClientId("test-app"), sessions[2]); clientSession.setRedirectUri("http://redirct"); @@ -783,10 +783,10 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { session.getTransactionManager().commit(); - assertNotEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername("user2", realm)).count()); + assertNotEquals(0, session.sessions().getUserSessionsStream(realm, session.users().getUserByUsername(realm, "user2")).count()); - user1 = session.users().getUserByUsername("user1", realm); - user2 = session.users().getUserByUsername("user2", realm); + user1 = session.users().getUserByUsername(realm, "user1"); + user2 = session.users().getUserByUsername(realm, "user2"); // it seems as if Null does not happen with the new test suite. The sizes of these are ZERO so the removes worked at this point. //assertNull(session.sessions().getUserLoginFailure(realm, user1.getId())); @@ -804,15 +804,15 @@ public class UserSessionProviderTest extends AbstractTestRealmKeycloakTest { private static UserSessionModel[] createSessions(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName("test"); UserSessionModel[] sessions = new UserSessionModel[3]; - sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true, null, null); + sessions[0] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[0], "http://redirect", "state"); createClientSession(session, realm.getClientByClientId("third-party"), sessions[0], "http://redirect", "state"); - sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null); + sessions[1] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[1], "http://redirect", "state"); - sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.3", "form", true, null, null); + sessions[2] = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user2"), "user2", "127.0.0.3", "form", true, null, null); createClientSession(session, realm.getClientByClientId("test-app"), sessions[2], "http://redirect", "state"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientTokenExchangeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientTokenExchangeTest.java index d3310087af..a771c786f0 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientTokenExchangeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientTokenExchangeTest.java @@ -516,7 +516,7 @@ public class ClientTokenExchangeTest extends AbstractKeycloakTest { realm.removeClient(realm.getClientByClientId("direct-exchanger").getId()); realm.removeClient(realm.getClientByClientId("target").getId()); realm.removeRole(realm.getRole("example")); - session.users().removeUser(realm, session.users().getUserByUsername("impersonated-user", realm)); + session.users().removeUser(realm, session.users().getUserByUsername(realm, "impersonated-user")); } private Response checkTokenExchange() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RefreshTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RefreshTokenTest.java index 9a8b3c2799..11b7faaa49 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RefreshTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RefreshTokenTest.java @@ -708,7 +708,7 @@ public class RefreshTokenTest extends AbstractKeycloakTest { // Need to reset not-before of user, which was updated during user.logout() testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); - UserModel user = session.users().getUserByUsername("test-user@localhost", realm); + UserModel user = session.users().getUserByUsername(realm, "test-user@localhost"); session.users().setNotBeforeForUser(realm, user, 0); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/session/SessionTimeoutValidationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/session/SessionTimeoutValidationTest.java index a1f3bbd49a..f1e736e657 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/session/SessionTimeoutValidationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/session/SessionTimeoutValidationTest.java @@ -57,7 +57,7 @@ public class SessionTimeoutValidationTest extends AbstractTestRealmKeycloakTest testingClient.server().run( session -> { RealmModel realm = session.realms().getRealmByName("test"); session.sessions().removeUserSessions(realm); - UserModel user1 = session.users().getUserByUsername("user1", realm); + UserModel user1 = session.users().getUserByUsername(realm, "user1"); UserManager um = new UserManager(session); if (user1 != null) { @@ -78,7 +78,7 @@ public class SessionTimeoutValidationTest extends AbstractTestRealmKeycloakTest UserSessionModel userSessionModel = session.sessions().createUserSession( realm, - session.users().getUserByUsername("user1", realm), + session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null ); diff --git a/testsuite/model/pom.xml b/testsuite/model/pom.xml index cb4acefeca..6131c66614 100644 --- a/testsuite/model/pom.xml +++ b/testsuite/model/pom.xml @@ -136,6 +136,13 @@ + + jpa-federation-backward+infinispan + + Infinispan,JpaFederation,BackwardsCompatibilityUserStorage + + + jpa-federation @@ -143,6 +150,13 @@ + + jpa-federation-backward + + JpaFederation,BackwardsCompatibilityUserStorage + + + jpa-federation+ldap diff --git a/testsuite/model/src/test/java/org/keycloak/testsuite/model/UserModelTest.java b/testsuite/model/src/test/java/org/keycloak/testsuite/model/UserModelTest.java index 366283e407..f480c45703 100644 --- a/testsuite/model/src/test/java/org/keycloak/testsuite/model/UserModelTest.java +++ b/testsuite/model/src/test/java/org/keycloak/testsuite/model/UserModelTest.java @@ -90,7 +90,7 @@ public class UserModelTest extends KeycloakModelTest { user.joinGroup(session.groups().getGroupById(realm, groupIds.get((i + gIndex) % NUM_GROUPS))); }); - final UserModel obtainedUser = session.users().getUserById(user.getId(), realm); + final UserModel obtainedUser = session.users().getUserById(realm, user.getId()); assertThat(obtainedUser, Matchers.notNullValue()); assertThat(obtainedUser.getUsername(), is("user-" + i)); @@ -101,7 +101,7 @@ public class UserModelTest extends KeycloakModelTest { assertTrue(session.users().removeUser(realm, user)); assertFalse(session.users().removeUser(realm, user)); - assertNull(session.users().getUserByUsername(user.getUsername(), realm)); + assertNull(session.users().getUserByUsername(realm, user.getUsername())); } @Test @@ -138,7 +138,7 @@ public class UserModelTest extends KeycloakModelTest { do { userIds.stream().parallel().forEach(index -> inComittedTransaction(index, (session, userId) -> { final RealmModel realm = session.realms().getRealm(realmId); - final UserModel user = session.users().getUserById(userId, realm); + final UserModel user = session.users().getUserById(realm, userId); log.debugf("Remove user %s: %s", userId, session.users().removeUser(realm, user)); }, null, (session, userId) -> remainingUserIds.add(userId) )); @@ -169,7 +169,7 @@ public class UserModelTest extends KeycloakModelTest { final RealmModel realm = session.realms().getRealm(realmId); final UserStorageProvider instance = getUserFederationInstance(session, realm); log.debugf("Removing selected users from backend"); - final UserModel user = session.users().getUserByUsername("user-A", realm); + final UserModel user = session.users().getUserByUsername(realm, "user-A"); ((UserRegistrationProvider) instance).removeUser(realm, user); }); @@ -178,7 +178,7 @@ public class UserModelTest extends KeycloakModelTest { if (session.userCache() != null) { session.userCache().clear(); } - final UserModel user = session.users().getUserByUsername("user-A", realm); + final UserModel user = session.users().getUserByUsername(realm, "user-A"); assertThat("User should not be found in the main store", user, Matchers.nullValue()); }); } @@ -206,7 +206,7 @@ public class UserModelTest extends KeycloakModelTest { UserStorageProvider instance = getUserFederationInstance(session, realm); log.debugf("Removing selected users from backend"); IntStream.range(FIRST_DELETED_USER_INDEX, LAST_DELETED_USER_INDEX).forEach(j -> { - final UserModel user = session.users().getUserByUsername("user-" + j, realm); + final UserModel user = session.users().getUserByUsername(realm, "user-" + j); ((UserRegistrationProvider) instance).removeUser(realm, user); }); }); @@ -217,6 +217,18 @@ public class UserModelTest extends KeycloakModelTest { assertThat(session.users().getGroupMembersStream(realm, group).count(), is(100L - DELETED_USER_COUNT)); })); + inComittedTransaction(1, (session, i) -> { + // If we are using cache, we need to invalidate all users because after removing users from external + // provider cache may not be cleared and it may be the case, that cache is the only place that is having + // a reference to removed users. Our importValidation method won't be called at all for removed users + // because they are not present in any storage. However, when we get users by id cache may still be hit + // since it is not alerted in any way when users are removed from external provider. Hence we need to clear + // the cache manually. + if (session.userCache() != null) { + session.userCache().clear(); + } + }); + // Now delete the users, and count those that were not found to be deleted. This should be equal to the number // of users removed directly in the user federation. // Some of the transactions may fail due to conflicts as there are many parallel request, so repeat until all users are removed @@ -225,7 +237,7 @@ public class UserModelTest extends KeycloakModelTest { do { userIds.stream().parallel().forEach(index -> inComittedTransaction(index, (session, userId) -> { final RealmModel realm = session.realms().getRealm(realmId); - final UserModel user = session.users().getUserById(userId, realm); + final UserModel user = session.users().getUserById(realm, userId); if (user != null) { log.debugf("Deleting user: %s", userId); session.users().removeUser(realm, user); diff --git a/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/AbstractSessionCacheCommand.java b/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/AbstractSessionCacheCommand.java index bd5cb1ee10..b9be729398 100644 --- a/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/AbstractSessionCacheCommand.java +++ b/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/AbstractSessionCacheCommand.java @@ -335,7 +335,7 @@ public abstract class AbstractSessionCacheCommand extends AbstractCommand { BatchTaskRunner.runInBatches(0, count, batchCount, session.getKeycloakSessionFactory(), (KeycloakSession batchSession, int firstInIteration, int countInIteration) -> { RealmModel realm = batchSession.realms().getRealmByName(realmName); ClientModel client = realm.getClientByClientId(clientId); - UserModel user = batchSession.users().getUserByUsername(username, realm); + UserModel user = batchSession.users().getUserByUsername(realm, username); for (int i=0 ; i { - session.users().getUserById(user.getId(), realm); + session.users().getUserById(realm, user.getId()); if (user.getEmail() != null) { - session.users().getUserByEmail(user.getEmail(), realm); + session.users().getUserByEmail(realm, user.getEmail()); } - session.users().getUserByUsername(user.getUsername(), realm); + session.users().getUserByUsername(realm, user.getUsername()); session.users().getConsentsStream(realm, user.getId()); - session.users().getFederatedIdentitiesStream(user, realm) - .forEach(identity -> session.users().getUserByFederatedIdentity(identity, realm)); + session.users().getFederatedIdentitiesStream(realm, user) + .forEach(identity -> session.users().getUserByFederatedIdentity(realm, identity)); }); } diff --git a/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/UserCommands.java b/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/UserCommands.java index 1d7d06cfba..5c58eda910 100644 --- a/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/UserCommands.java +++ b/testsuite/utils/src/main/java/org/keycloak/testsuite/util/cli/UserCommands.java @@ -151,7 +151,7 @@ public class UserCommands { int last = first + count; for (int counter = first; counter < last; counter++) { String username = usernamePrefix + counter; - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); if (user == null) { log.errorf("User '%s' not found", username); } else { @@ -213,7 +213,7 @@ public class UserCommands { return; } - UserModel user = session.users().getUserByUsername(username, realm); + UserModel user = session.users().getUserByUsername(realm, username); if (user == null) { log.infof("User '%s' doesn't exist in realm '%s'", username, realmName); } else {