From 4b0e33e388c19152fa728125acfc8923651e6dfc Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Fri, 13 Nov 2015 09:38:09 -0200 Subject: [PATCH] KEYCLOAK-2056: Removal of file model provider --- dependencies/server-all/pom.xml | 4 - .../keycloak-model-file/main/module.xml | 18 - .../WEB-INF/jboss-deployment-structure.xml | 3 +- .../keycloak-services/main/module.xml | 1 - .../eap6/eap6-server-modules/build.xml | 10 +- .../WEB-INF/jboss-deployment-structure.xml | 3 +- .../keycloak-model-file/main/module.xml | 16 - .../keycloak-services/main/module.xml | 1 - model/file/pom.xml | 62 - .../models/file/FileRealmProvider.java | 119 -- .../models/file/FileRealmProviderFactory.java | 58 - .../models/file/FileUserProvider.java | 520 ----- .../models/file/FileUserProviderFactory.java | 56 - .../models/file/adapter/ClientAdapter.java | 663 ------ .../models/file/adapter/GroupAdapter.java | 213 -- .../file/adapter/MigrationModelAdapter.java | 26 - .../models/file/adapter/RealmAdapter.java | 1840 ----------------- .../models/file/adapter/RoleAdapter.java | 188 -- .../models/file/adapter/UserAdapter.java | 614 ------ .../org.keycloak.models.RealmProviderFactory | 1 - .../org.keycloak.models.UserProviderFactory | 1 - model/pom.xml | 1 - pom.xml | 11 +- 23 files changed, 7 insertions(+), 4422 deletions(-) delete mode 100755 distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-model-file/main/module.xml delete mode 100755 distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-model-file/main/module.xml delete mode 100755 model/file/pom.xml delete mode 100755 model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java delete mode 100644 model/file/src/main/java/org/keycloak/models/file/FileRealmProviderFactory.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java delete mode 100644 model/file/src/main/java/org/keycloak/models/file/FileUserProviderFactory.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/ClientAdapter.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/MigrationModelAdapter.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/RoleAdapter.java delete mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java delete mode 100644 model/file/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory delete mode 100644 model/file/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory diff --git a/dependencies/server-all/pom.xml b/dependencies/server-all/pom.xml index 81ce0957c5..ad786a3cc0 100755 --- a/dependencies/server-all/pom.xml +++ b/dependencies/server-all/pom.xml @@ -36,10 +36,6 @@ org.keycloak keycloak-model-jpa - - org.keycloak - keycloak-model-file - org.keycloak keycloak-model-sessions-infinispan diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-model-file/main/module.xml b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-model-file/main/module.xml deleted file mode 100755 index 2612e06451..0000000000 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-model-file/main/module.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml index c339f44671..d8b1aa2ca0 100755 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml @@ -33,7 +33,6 @@ - @@ -70,4 +69,4 @@ - \ No newline at end of file + diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-services/main/module.xml b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-services/main/module.xml index 77ce3ad8dc..6b83a7e81d 100755 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-services/main/module.xml +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/base/org/keycloak/keycloak-services/main/module.xml @@ -43,7 +43,6 @@ - diff --git a/distribution/server-overlay/eap6/eap6-server-modules/build.xml b/distribution/server-overlay/eap6/eap6-server-modules/build.xml index 60ccb65be0..924a32a6ac 100755 --- a/distribution/server-overlay/eap6/eap6-server-modules/build.xml +++ b/distribution/server-overlay/eap6/eap6-server-modules/build.xml @@ -224,11 +224,11 @@ - + - + @@ -250,12 +250,6 @@ - - - - - - diff --git a/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-as7-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml b/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-as7-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml index c339f44671..d8b1aa2ca0 100755 --- a/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-as7-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml +++ b/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-as7-server-subsystem/main/server-war/WEB-INF/jboss-deployment-structure.xml @@ -33,7 +33,6 @@ - @@ -70,4 +69,4 @@ - \ No newline at end of file + diff --git a/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-model-file/main/module.xml b/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-model-file/main/module.xml deleted file mode 100755 index 46f8ffd25d..0000000000 --- a/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-model-file/main/module.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-services/main/module.xml b/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-services/main/module.xml index 44703f8a5d..bf230faab4 100755 --- a/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-services/main/module.xml +++ b/distribution/server-overlay/eap6/eap6-server-modules/src/main/resources/modules/org/keycloak/keycloak-services/main/module.xml @@ -43,7 +43,6 @@ - diff --git a/model/file/pom.xml b/model/file/pom.xml deleted file mode 100755 index bb5333e042..0000000000 --- a/model/file/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - keycloak-parent - org.keycloak - 1.7.0.Final-SNAPSHOT - ../../pom.xml - - 4.0.0 - - keycloak-model-file - Keycloak Model File - - - - - org.keycloak - keycloak-export-import-api - - - org.keycloak - keycloak-export-import-single-file - - - org.keycloak - keycloak-core - provided - - - org.keycloak - keycloak-model-api - - - org.keycloak - keycloak-connections-file - - - org.codehaus.jackson - jackson-mapper-asl - provided - - - org.jboss.logging - jboss-logging - provided - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - diff --git a/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java b/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java deleted file mode 100755 index 33d4fa36d3..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file; - -import org.keycloak.connections.file.FileConnectionProvider; -import org.keycloak.connections.file.InMemoryModel; -import org.keycloak.migration.MigrationModel; -import org.keycloak.models.ClientModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RealmProvider; -import org.keycloak.models.RoleModel; -import org.keycloak.models.entities.RealmEntity; -import org.keycloak.models.file.adapter.MigrationModelAdapter; -import org.keycloak.models.file.adapter.RealmAdapter; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.List; - -/** - * Realm Provider for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class FileRealmProvider implements RealmProvider { - - private final KeycloakSession session; - private FileConnectionProvider fcProvider; - private final InMemoryModel inMemoryModel; - - public FileRealmProvider(KeycloakSession session, FileConnectionProvider fcProvider) { - this.session = session; - this.fcProvider = fcProvider; - session.enlistForClose(this); - this.inMemoryModel = fcProvider.getModel(); - } - - @Override - public void close() { - fcProvider.sessionClosed(session); - } - - @Override - public MigrationModel getMigrationModel() { - return new MigrationModelAdapter(inMemoryModel); - } - - @Override - public RealmModel createRealm(String name) { - return createRealm(KeycloakModelUtils.generateId(), name); - } - - @Override - public RealmModel createRealm(String id, String name) { - if (getRealmByName(name) != null) throw new ModelDuplicateException("Realm " + name + " already exists."); - RealmEntity realmEntity = new RealmEntity(); - realmEntity.setName(name); - realmEntity.setId(id); - RealmAdapter realm = new RealmAdapter(session, realmEntity, inMemoryModel); - inMemoryModel.putRealm(id, realm); - - return realm; - } - - @Override - public GroupModel getGroupById(String id, RealmModel realm) { - return null; - } - - @Override - public RealmModel getRealm(String id) { - RealmModel model = inMemoryModel.getRealm(id); - return model; - } - - @Override - public List getRealms() { - return new ArrayList(inMemoryModel.getRealms()); - } - - @Override - public RealmModel getRealmByName(String name) { - RealmModel model = inMemoryModel.getRealmByName(name); - return model; - } - - @Override - public boolean removeRealm(String id) { - return inMemoryModel.removeRealm(id); - } - - @Override - public RoleModel getRoleById(String id, RealmModel realm) { - return realm.getRoleById(id); - } - - @Override - public ClientModel getClientById(String id, RealmModel realm) { - return realm.getClientById(id); - } - -} diff --git a/model/file/src/main/java/org/keycloak/models/file/FileRealmProviderFactory.java b/model/file/src/main/java/org/keycloak/models/file/FileRealmProviderFactory.java deleted file mode 100644 index 211d8a5e64..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/FileRealmProviderFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file; - -import org.keycloak.Config; -import org.keycloak.connections.file.FileConnectionProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.RealmProvider; -import org.keycloak.models.RealmProviderFactory; - - -/** - * RealmProviderFactory for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class FileRealmProviderFactory implements RealmProviderFactory { - - @Override - public void init(Config.Scope config) { - - } - - @Override - public String getId() { - return "file"; - } - - @Override - public RealmProvider create(KeycloakSession session) { - FileConnectionProvider fcProvider = session.getProvider(FileConnectionProvider.class); - return new FileRealmProvider(session, fcProvider); - } - - @Override - public void close() { - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - } - -} diff --git a/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java b/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java deleted file mode 100755 index e4b29d3dbf..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file; - -import org.keycloak.connections.file.FileConnectionProvider; -import org.keycloak.connections.file.InMemoryModel; -import org.keycloak.models.ClientModel; -import org.keycloak.models.CredentialValidationOutput; -import org.keycloak.models.FederatedIdentityModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.ModelException; -import org.keycloak.models.session.PersistentClientSessionModel; -import org.keycloak.models.session.PersistentUserSessionModel; -import org.keycloak.models.ProtocolMapperModel; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RequiredActionProviderModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserCredentialModel; -import org.keycloak.models.UserFederationProviderModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.UserProvider; -import org.keycloak.models.entities.FederatedIdentityEntity; -import org.keycloak.models.entities.PersistentClientSessionEntity; -import org.keycloak.models.entities.PersistentUserSessionEntity; -import org.keycloak.models.entities.UserEntity; -import org.keycloak.models.file.adapter.UserAdapter; -import org.keycloak.models.utils.CredentialValidation; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * UserProvider for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class FileUserProvider implements UserProvider { - - private final KeycloakSession session; - private FileConnectionProvider fcProvider; - private final InMemoryModel inMemoryModel; - - public FileUserProvider(KeycloakSession session, FileConnectionProvider fcProvider) { - this.session = session; - this.fcProvider = fcProvider; - session.enlistForClose(this); - this.inMemoryModel = fcProvider.getModel(); - } - - @Override - public void close() { - fcProvider.sessionClosed(session); - } - - @Override - public UserModel getUserById(String userId, RealmModel realm) { - return inMemoryModel.getUser(realm.getId(), userId); - } - - @Override - public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { - return null; - } - - @Override - public List getGroupMembers(RealmModel realm, GroupModel group) { - return null; - } - - @Override - public void preRemove(RealmModel realm, GroupModel group) { - - } - - @Override - public UserModel getUserByUsername(String username, RealmModel realm) { - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - if (user.getUsername() == null) continue; - if (user.getUsername().equals(username.toLowerCase())) return user; - } - - return null; - } - - @Override - public UserModel getUserByEmail(String email, RealmModel realm) { - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - if (user.getEmail() == null) continue; - if (user.getEmail().equals(email.toLowerCase())) return user; - } - - return null; - } - - @Override - public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) { - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - Set identities = this.getFederatedIdentities(user, realm); - for (FederatedIdentityModel idModel : identities) { - if (idModel.getUserId().equals(socialLink.getUserId())) return user; - } - } - - return null; - } - - @Override - public UserModel getUserByServiceAccountClient(ClientModel client) { - for (UserModel user : inMemoryModel.getUsers(client.getRealm().getId())) { - if (client.getId().equals(user.getServiceAccountClientLink())) { - return user; - } - } - return null; - } - - @Override - public List getUsers(RealmModel realm, boolean includeServiceAccounts) { - return getUsers(realm, -1, -1, includeServiceAccounts); - } - - @Override - public int getUsersCount(RealmModel realm) { - return inMemoryModel.getUsers(realm.getId()).size(); - } - - @Override - public List getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) { - List users = new ArrayList<>(inMemoryModel.getUsers(realm.getId())); - - if (!includeServiceAccounts) { - users = filterServiceAccountUsers(users); - } - - List sortedList = sortedSubList(users, firstResult, maxResults); - return sortedList; - } - - private List filterServiceAccountUsers(List users) { - List result = new ArrayList<>(); - for (UserModel user : users) { - if (user.getServiceAccountClientLink() == null) { - result.add(user); - } - } - return result; - } - - protected List sortedSubList(List list, int firstResult, int maxResults) { - if (list.isEmpty()) return list; - - Collections.sort(list); - int first = (firstResult <= 0) ? 0 : firstResult; - int last = first + maxResults; // could be int overflow - if ((maxResults > list.size() - first) || (last > list.size())) { // int overflow or regular overflow - last = list.size(); - } - - if (maxResults <= 0) { - last = list.size(); - } - - return list.subList(first, last); - } - - @Override - public List searchForUser(String search, RealmModel realm) { - return searchForUser(search, realm, -1, -1); - } - - @Override - public List searchForUser(String search, RealmModel realm, int firstResult, int maxResults) { - search = search.trim(); - Pattern caseInsensitivePattern = Pattern.compile("(?i:.*" + search + ".*)", Pattern.CASE_INSENSITIVE); - - int spaceInd = search.lastIndexOf(" "); - boolean isFirstAndLastSearch = spaceInd != -1; - Pattern firstNamePattern = null; - Pattern lastNamePattern = null; - if (isFirstAndLastSearch) { - String firstNamePatternString = search.substring(0, spaceInd); - String lastNamePatternString = search.substring(spaceInd + 1); - firstNamePattern = Pattern.compile("(?i:.*" + firstNamePatternString + ".*$)", Pattern.CASE_INSENSITIVE); - lastNamePattern = Pattern.compile("(?i:^.*" + lastNamePatternString + ".*)", Pattern.CASE_INSENSITIVE); - } - - List found = new ArrayList(); - - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - String firstName = user.getFirstName(); - String lastName = user.getLastName(); - // Case when we have search string like "ohn Bow". Then firstName must end with "ohn" AND lastName must start with "bow" (everything case-insensitive) - if (isFirstAndLastSearch) { - if (isAMatch(firstNamePattern, firstName) && - isAMatch(lastNamePattern, lastName)) { - found.add(user); - continue; - } - } - - if (isAMatch(caseInsensitivePattern, firstName) || - isAMatch(caseInsensitivePattern, lastName) || - isAMatch(caseInsensitivePattern, user.getUsername()) || - isAMatch(caseInsensitivePattern, user.getEmail())) { - found.add(user); - } - } - - // Remove users with service account link - found = filterServiceAccountUsers(found); - - return sortedSubList(found, firstResult, maxResults); - } - - @Override - public List searchForUserByAttributes(Map attributes, RealmModel realm) { - return searchForUserByAttributes(attributes, realm, -1, -1); - } - - protected boolean isAMatch(Pattern pattern, String value) { - return (value != null) && (pattern != null) && pattern.matcher(value).matches(); - } - - @Override - public List searchForUserByAttributes(Map attributes, RealmModel realm, int firstResult, int maxResults) { - Pattern usernamePattern = null; - Pattern firstNamePattern = null; - Pattern lastNamePattern = null; - Pattern emailPattern = null; - for (Map.Entry entry : attributes.entrySet()) { - if (entry.getKey().equalsIgnoreCase(UserModel.USERNAME)) { - usernamePattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE); - } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) { - firstNamePattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE); - } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) { - lastNamePattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE); - } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) { - emailPattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE); - } - } - - List found = new ArrayList(); - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - if (isAMatch(usernamePattern, user.getUsername()) || - isAMatch(firstNamePattern, user.getFirstName()) || - isAMatch(lastNamePattern, user.getLastName()) || - isAMatch(emailPattern, user.getEmail())) { - found.add(user); - } - } - - return sortedSubList(found, firstResult, maxResults); - } - - @Override - public List searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) { - Collection users = inMemoryModel.getUsers(realm.getId()); - - List matchedUsers = new ArrayList<>(); - for (UserModel user : users) { - List vals = user.getAttribute(attrName); - if (vals.contains(attrValue)) { - matchedUsers.add(user); - } - } - - return matchedUsers; - } - - @Override - public Set getFederatedIdentities(UserModel userModel, RealmModel realm) { - UserEntity userEntity = ((UserAdapter)getUserById(userModel.getId(), realm)).getUserEntity(); - List linkEntities = userEntity.getFederatedIdentities(); - - if (linkEntities == null) { - return Collections.EMPTY_SET; - } - - Set result = new HashSet(); - for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) { - FederatedIdentityModel model = new FederatedIdentityModel(federatedIdentityEntity.getIdentityProvider(), - federatedIdentityEntity.getUserId(), federatedIdentityEntity.getUserName()); - result.add(model); - } - return result; - } - - private FederatedIdentityEntity findSocialLink(UserModel userModel, String socialProvider, RealmModel realm) { - UserModel user = getUserById(userModel.getId(), realm); - UserEntity userEntity = ((UserAdapter)getUserById(userModel.getId(), realm)).getUserEntity(); - List linkEntities = userEntity.getFederatedIdentities(); - if (linkEntities == null) { - return null; - } - - for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) { - if (federatedIdentityEntity.getIdentityProvider().equals(socialProvider)) { - return federatedIdentityEntity; - } - } - return null; - } - - - @Override - public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) { - FederatedIdentityEntity federatedIdentityEntity = findSocialLink(user, socialProvider, realm); - return federatedIdentityEntity != null ? new FederatedIdentityModel(federatedIdentityEntity.getIdentityProvider(), federatedIdentityEntity.getUserId(), federatedIdentityEntity.getUserName()) : null; - } - - @Override - public UserAdapter addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { - if (inMemoryModel.hasUserWithUsername(realm.getId(), username.toLowerCase())) - throw new ModelDuplicateException("User with username " + username + " already exists in realm."); - - UserAdapter userModel = addUserEntity(realm, id, username.toLowerCase()); - - if (addDefaultRoles) { - for (String r : realm.getDefaultRoles()) { - userModel.grantRole(realm.getRole(r)); - } - - for (ClientModel application : realm.getClients()) { - for (String r : application.getDefaultRoles()) { - userModel.grantRole(application.getRole(r)); - } - } - } - - if (addDefaultRequiredActions) { - for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) { - if (r.isEnabled() && r.isDefaultAction()) { - userModel.addRequiredAction(r.getAlias()); - } - } - } - - - return userModel; - } - - protected UserAdapter addUserEntity(RealmModel realm, String userId, String username) { - if (realm == null) throw new NullPointerException("realm == null"); - if (username == null) throw new NullPointerException("username == null"); - - if (userId == null) userId = KeycloakModelUtils.generateId(); - - UserEntity userEntity = new UserEntity(); - userEntity.setId(userId); - userEntity.setCreatedTimestamp(System.currentTimeMillis()); - userEntity.setUsername(username); - // Compatibility with JPA model, which has user disabled by default - // userEntity.setEnabled(true); - userEntity.setRealmId(realm.getId()); - - UserAdapter user = new UserAdapter(realm, userEntity, inMemoryModel); - inMemoryModel.putUser(realm.getId(), userId, user); - - return user; - } - - @Override - public boolean removeUser(RealmModel realm, UserModel user) { - return inMemoryModel.removeUser(realm.getId(), user.getId()); - } - - - @Override - public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) { - UserAdapter userAdapter = (UserAdapter)getUserById(user.getId(), realm); - UserEntity userEntity = userAdapter.getUserEntity(); - FederatedIdentityEntity federatedIdentityEntity = new FederatedIdentityEntity(); - federatedIdentityEntity.setIdentityProvider(socialLink.getIdentityProvider()); - federatedIdentityEntity.setUserId(socialLink.getUserId()); - federatedIdentityEntity.setUserName(socialLink.getUserName().toLowerCase()); - - //check if it already exitsts - do I need to do this? - for (FederatedIdentityEntity fedIdent : userEntity.getFederatedIdentities()) { - if (fedIdent.equals(federatedIdentityEntity)) return; - } - - userEntity.getFederatedIdentities().add(federatedIdentityEntity); - } - - @Override - public boolean removeFederatedIdentity(RealmModel realm, UserModel userModel, String socialProvider) { - UserModel user = getUserById(userModel.getId(), realm); - UserEntity userEntity = ((UserAdapter) user).getUserEntity(); - FederatedIdentityEntity federatedIdentityEntity = findSocialLink(userEntity, socialProvider); - if (federatedIdentityEntity == null) { - return false; - } - - userEntity.getFederatedIdentities().remove(federatedIdentityEntity); - return true; - } - - private FederatedIdentityEntity findSocialLink(UserEntity userEntity, String socialProvider) { - List linkEntities = userEntity.getFederatedIdentities(); - if (linkEntities == null) { - return null; - } - - for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) { - if (federatedIdentityEntity.getIdentityProvider().equals(socialProvider)) { - return federatedIdentityEntity; - } - } - return null; - } - - @Override - public UserModel addUser(RealmModel realm, String username) { - return this.addUser(realm, KeycloakModelUtils.generateId(), username.toLowerCase(), true, true); - } - - @Override - public void grantToAllUsers(RealmModel realm, RoleModel role) { - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - user.grantRole(role); - } - } - - @Override - public void preRemove(RealmModel realm) { - // Nothing to do here? Federation links are attached to users, which are removed by InMemoryModel - } - - @Override - public void preRemove(RealmModel realm, UserFederationProviderModel link) { - Set toBeRemoved = new HashSet(); - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - String fedLink = user.getFederationLink(); - if (fedLink == null) continue; - if (fedLink.equals(link.getId())) toBeRemoved.add(user); - } - - for (UserModel user : toBeRemoved) { - inMemoryModel.removeUser(realm.getId(), user.getId()); - } - } - - @Override - public void preRemove(RealmModel realm, RoleModel role) { - // todo not sure what to do for this - } - - @Override - public void preRemove(RealmModel realm, ClientModel client) { - // TODO - } - - @Override - public void preRemove(ClientModel client, ProtocolMapperModel protocolMapper) { - // TODO - } - - @Override - public boolean validCredentials(RealmModel realm, UserModel user, List input) { - return CredentialValidation.validCredentials(realm, user, input); - } - - @Override - public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) { - return CredentialValidation.validCredentials(realm, user, input); - } - - @Override - public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) { - federatedUser = getUserById(federatedUser.getId(), realm); - UserEntity userEntity = ((UserAdapter) federatedUser).getUserEntity(); - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, federatedIdentityModel.getIdentityProvider()); - - federatedIdentityEntity.setToken(federatedIdentityModel.getToken()); - } - - private FederatedIdentityEntity findFederatedIdentityLink(UserEntity userEntity, String identityProvider) { - List linkEntities = userEntity.getFederatedIdentities(); - if (linkEntities == null) { - return null; - } - - for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) { - if (federatedIdentityEntity.getIdentityProvider().equals(identityProvider)) { - return federatedIdentityEntity; - } - } - return null; - } - - @Override - public CredentialValidationOutput validCredentials(RealmModel realm, UserCredentialModel... input) { - //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - return null; // not supported yet - } -} diff --git a/model/file/src/main/java/org/keycloak/models/file/FileUserProviderFactory.java b/model/file/src/main/java/org/keycloak/models/file/FileUserProviderFactory.java deleted file mode 100644 index e7f3674229..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/FileUserProviderFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file; - -import org.keycloak.Config; -import org.keycloak.connections.file.FileConnectionProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.UserProvider; -import org.keycloak.models.UserProviderFactory; - -/** - * UserProviderFactory for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class FileUserProviderFactory implements UserProviderFactory { - - @Override - public void init(Config.Scope config) { - } - - @Override - public String getId() { - return "file"; - } - - @Override - public UserProvider create(KeycloakSession session) { - FileConnectionProvider fcProvider = session.getProvider(FileConnectionProvider.class); - return new FileUserProvider(session, fcProvider); - } - - @Override - public void close() { - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - } - -} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/ClientAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/ClientAdapter.java deleted file mode 100755 index 81e60ee295..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/ClientAdapter.java +++ /dev/null @@ -1,663 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file.adapter; - -import org.keycloak.connections.file.InMemoryModel; -import org.keycloak.models.ClientModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.ProtocolMapperModel; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.entities.ClientEntity; -import org.keycloak.models.entities.ProtocolMapperEntity; -import org.keycloak.models.entities.RoleEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * ApplicationModel used for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class ClientAdapter implements ClientModel { - - private final RealmModel realm; - private KeycloakSession session; - private final ClientEntity entity; - private final InMemoryModel inMemoryModel; - - private final Map allRoles = new HashMap(); - private final Map allScopeMappings = new HashMap(); - - public ClientAdapter(KeycloakSession session, RealmModel realm, ClientEntity entity, InMemoryModel inMemoryModel) { - this.realm = realm; - this.session = session; - this.entity = entity; - this.inMemoryModel = inMemoryModel; - } - - @Override - public void updateClient() { - } - - @Override - public String getId() { - return entity.getId(); - } - - @Override - public String getName() { - return entity.getName(); - } - - @Override - public void setName(String name) { - entity.setName(name); - } - - @Override - public String getDescription() { return entity.getDescription(); } - - @Override - public void setDescription(String description) { entity.setDescription(description); } - - @Override - public Set getWebOrigins() { - Set result = new HashSet(); - if (entity.getWebOrigins() != null) { - result.addAll(entity.getWebOrigins()); - } - return result; - } - - @Override - public void setWebOrigins(Set webOrigins) { - List result = new ArrayList(); - result.addAll(webOrigins); - entity.setWebOrigins(result); - } - - @Override - public void addWebOrigin(String webOrigin) { - Set webOrigins = getWebOrigins(); - webOrigins.add(webOrigin); - setWebOrigins(webOrigins); - } - - @Override - public void removeWebOrigin(String webOrigin) { - Set webOrigins = getWebOrigins(); - webOrigins.remove(webOrigin); - setWebOrigins(webOrigins); - } - - @Override - public Set getRedirectUris() { - Set result = new HashSet(); - if (entity.getRedirectUris() != null) { - result.addAll(entity.getRedirectUris()); - } - return result; - } - - @Override - public void setRedirectUris(Set redirectUris) { - List result = new ArrayList(); - result.addAll(redirectUris); - entity.setRedirectUris(result); - } - - @Override - public void addRedirectUri(String redirectUri) { - if (entity.getRedirectUris().contains(redirectUri)) return; - entity.getRedirectUris().add(redirectUri); - } - - @Override - public void removeRedirectUri(String redirectUri) { - entity.getRedirectUris().remove(redirectUri); - } - - @Override - public boolean isEnabled() { - return entity.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - entity.setEnabled(enabled); - } - - @Override - public String getClientAuthenticatorType() { - return entity.getClientAuthenticatorType(); - } - - @Override - public void setClientAuthenticatorType(String clientAuthenticatorType) { - entity.setClientAuthenticatorType(clientAuthenticatorType); - } - - @Override - public boolean validateSecret(String secret) { - return secret.equals(entity.getSecret()); - } - - @Override - public String getSecret() { - return entity.getSecret(); - } - - @Override - public void setSecret(String secret) { - entity.setSecret(secret); - } - - @Override - public boolean isPublicClient() { - return entity.isPublicClient(); - } - - @Override - public void setPublicClient(boolean flag) { - entity.setPublicClient(flag); - } - - - @Override - public boolean isFrontchannelLogout() { - return entity.isFrontchannelLogout(); - } - - @Override - public void setFrontchannelLogout(boolean flag) { - entity.setFrontchannelLogout(flag); - } - - @Override - public boolean isFullScopeAllowed() { - return entity.isFullScopeAllowed(); - } - - @Override - public void setFullScopeAllowed(boolean value) { - entity.setFullScopeAllowed(value); - } - - @Override - public RealmModel getRealm() { - return realm; - } - - @Override - public int getNotBefore() { - return entity.getNotBefore(); - } - - @Override - public void setNotBefore(int notBefore) { - entity.setNotBefore(notBefore); - } - - @Override - public Set getScopeMappings() { - return new HashSet(allScopeMappings.values()); - } - - @Override - public Set getRealmScopeMappings() { - Set allScopes = getScopeMappings(); - - Set realmRoles = new HashSet(); - for (RoleModel role : allScopes) { - RoleAdapter roleAdapter = (RoleAdapter)role; - if (roleAdapter.isRealmRole()) { - realmRoles.add(role); - } - } - return realmRoles; - } - - @Override - public void addScopeMapping(RoleModel role) { - allScopeMappings.put(role.getId(), role); - } - - @Override - public void deleteScopeMapping(RoleModel role) { - allScopeMappings.remove(role.getId()); - } - - @Override - public String getProtocol() { - return entity.getProtocol(); - } - - @Override - public void setProtocol(String protocol) { - entity.setProtocol(protocol); - - } - - @Override - public void setAttribute(String name, String value) { - entity.getAttributes().put(name, value); - - } - - @Override - public void removeAttribute(String name) { - entity.getAttributes().remove(name); - } - - @Override - public String getAttribute(String name) { - return entity.getAttributes().get(name); - } - - @Override - public Map getAttributes() { - Map copy = new HashMap(); - copy.putAll(entity.getAttributes()); - return copy; - } - - @Override - public Set getProtocolMappers() { - Set result = new HashSet(); - for (ProtocolMapperEntity entity : this.entity.getProtocolMappers()) { - ProtocolMapperModel model = getProtocolMapperById(entity.getId()); - if (model != null) result.add(model); - } - return result; - } - - @Override - public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) { - if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) { - throw new RuntimeException("protocol mapper name must be unique per protocol"); - } - ProtocolMapperEntity entity = new ProtocolMapperEntity(); - String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId(); - entity.setId(id); - entity.setProtocol(model.getProtocol()); - entity.setName(model.getName()); - entity.setProtocolMapper(model.getProtocolMapper()); - entity.setConfig(model.getConfig()); - entity.setConsentRequired(model.isConsentRequired()); - entity.setConsentText(model.getConsentText()); - this.entity.getProtocolMappers().add(entity); - return entityToModel(entity); - } - - @Override - public void removeProtocolMapper(ProtocolMapperModel mapping) { - ProtocolMapperEntity toBeRemoved = null; - for (ProtocolMapperEntity e : entity.getProtocolMappers()) { - if (e.getId().equals(mapping.getId())) { - toBeRemoved = e; - break; - } - } - - entity.getProtocolMappers().remove(toBeRemoved); - } - - @Override - public void updateProtocolMapper(ProtocolMapperModel mapping) { - ProtocolMapperEntity entity = getProtocolMapperEntityById(mapping.getId()); - entity.setProtocolMapper(mapping.getProtocolMapper()); - entity.setConsentRequired(mapping.isConsentRequired()); - entity.setConsentText(mapping.getConsentText()); - if (entity.getConfig() != null) { - entity.getConfig().clear(); - entity.getConfig().putAll(mapping.getConfig()); - } else { - entity.setConfig(mapping.getConfig()); - } - } - - protected ProtocolMapperEntity getProtocolMapperEntityById(String id) { - for (ProtocolMapperEntity e : entity.getProtocolMappers()) { - if (e.getId().equals(id)) { - return e; - } - } - return null; - } - - protected ProtocolMapperEntity getProtocolMapperEntityByName(String protocol, String name) { - for (ProtocolMapperEntity e : entity.getProtocolMappers()) { - if (e.getProtocol().equals(protocol) && e.getName().equals(name)) { - return e; - } - } - return null; - - } - - @Override - public ProtocolMapperModel getProtocolMapperById(String id) { - ProtocolMapperEntity entity = getProtocolMapperEntityById(id); - if (entity == null) return null; - return entityToModel(entity); - } - - @Override - public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) { - ProtocolMapperEntity entity = getProtocolMapperEntityByName(protocol, name); - if (entity == null) return null; - return entityToModel(entity); - } - - protected ProtocolMapperModel entityToModel(ProtocolMapperEntity entity) { - ProtocolMapperModel mapping = new ProtocolMapperModel(); - mapping.setId(entity.getId()); - mapping.setName(entity.getName()); - mapping.setProtocol(entity.getProtocol()); - mapping.setProtocolMapper(entity.getProtocolMapper()); - mapping.setConsentRequired(entity.isConsentRequired()); - mapping.setConsentText(entity.getConsentText()); - Map config = new HashMap(); - if (entity.getConfig() != null) config.putAll(entity.getConfig()); - mapping.setConfig(config); - return mapping; - } - - @Override - public String getClientId() { - return entity.getClientId(); - } - - @Override - public void setClientId(String clientId) { - if (appNameExists(clientId)) throw new ModelDuplicateException("Application named " + clientId + " already exists."); - entity.setClientId(clientId); - } - - private boolean appNameExists(String name) { - for (ClientModel app : realm.getClients()) { - if (app == this) continue; - if (app.getClientId().equals(name)) return true; - } - - return false; - } - - @Override - public boolean isSurrogateAuthRequired() { - return entity.isSurrogateAuthRequired(); - } - - @Override - public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { - entity.setSurrogateAuthRequired(surrogateAuthRequired); - } - - @Override - public String getManagementUrl() { - return entity.getManagementUrl(); - } - - @Override - public void setManagementUrl(String url) { - entity.setManagementUrl(url); - } - - @Override - public void setRootUrl(String url) { - entity.setRootUrl(url); - } - - @Override - public String getRootUrl() { - return entity.getRootUrl(); - } - - @Override - public void setBaseUrl(String url) { - entity.setBaseUrl(url); - } - - @Override - public String getBaseUrl() { - return entity.getBaseUrl(); - } - - @Override - public boolean isBearerOnly() { - return entity.isBearerOnly(); - } - - @Override - public void setBearerOnly(boolean only) { - entity.setBearerOnly(only); - } - - @Override - public boolean isConsentRequired() { - return entity.isConsentRequired(); - } - - @Override - public void setConsentRequired(boolean consentRequired) { - entity.setConsentRequired(consentRequired); - } - - @Override - public boolean isServiceAccountsEnabled() { - return entity.isServiceAccountsEnabled(); - } - - @Override - public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) { - entity.setServiceAccountsEnabled(serviceAccountsEnabled); - } - - @Override - public boolean isDirectGrantsOnly() { - return entity.isDirectGrantsOnly(); - } - - @Override - public void setDirectGrantsOnly(boolean flag) { - entity.setDirectGrantsOnly(flag); - } - - @Override - public RoleAdapter getRole(String name) { - for (RoleAdapter role : allRoles.values()) { - if (role.getName().equals(name)) return role; - } - return null; - } - - @Override - public RoleAdapter addRole(String name) { - return this.addRole(KeycloakModelUtils.generateId(), name); - } - - @Override - public RoleAdapter addRole(String id, String name) { - if (roleNameExists(name)) throw new ModelDuplicateException("Role named " + name + " already exists."); - RoleEntity roleEntity = new RoleEntity(); - roleEntity.setId(id); - roleEntity.setName(name); - roleEntity.setClientId(getId()); - - RoleAdapter role = new RoleAdapter(getRealm(), roleEntity, this); - allRoles.put(id, role); - - return role; - } - - private boolean roleNameExists(String name) { - for (RoleModel role : allRoles.values()) { - if (role.getName().equals(name)) return true; - } - - return false; - } - - @Override - public boolean removeRole(RoleModel role) { - boolean removed = (allRoles.remove(role.getId()) != null); - - // remove application roles from users - for (UserModel user : inMemoryModel.getUsers(realm.getId())) { - user.deleteRoleMapping(role); - } - - // delete scope mappings from applications - for (ClientModel app : realm.getClients()) { - app.deleteScopeMapping(role); - } - - // remove role from the realm - realm.removeRole(role); - - this.deleteScopeMapping(role); - - return removed; - } - - @Override - public Set getRoles() { - return new HashSet(allRoles.values()); - } - - @Override - public boolean hasScope(RoleModel role) { - if (isFullScopeAllowed()) return true; - Set roles = getScopeMappings(); - if (roles.contains(role)) return true; - - for (RoleModel mapping : roles) { - if (mapping.hasRole(role)) return true; - } - roles = getRoles(); - if (roles.contains(role)) return true; - - for (RoleModel mapping : roles) { - if (mapping.hasRole(role)) return true; - } - return false; - } - - @Override - public Set getClientScopeMappings(ClientModel client) { - Set allScopes = client.getScopeMappings(); - - Set appRoles = new HashSet(); - for (RoleModel role : allScopes) { - RoleAdapter roleAdapter = (RoleAdapter)role; - if (getId().equals(roleAdapter.getRoleEntity().getClientId())) { - appRoles.add(role); - } - } - return appRoles; - } - - @Override - public List getDefaultRoles() { - return entity.getDefaultRoles(); - } - - @Override - public void addDefaultRole(String name) { - RoleModel role = getRole(name); - if (role == null) { - addRole(name); - } - - List defaultRoles = getDefaultRoles(); - if (defaultRoles.contains(name)) return; - - String[] defaultRoleNames = defaultRoles.toArray(new String[defaultRoles.size() + 1]); - defaultRoleNames[defaultRoleNames.length - 1] = name; - updateDefaultRoles(defaultRoleNames); - } - - @Override - public void updateDefaultRoles(String[] defaultRoles) { - List roleNames = new ArrayList(); - for (String roleName : defaultRoles) { - RoleModel role = getRole(roleName); - if (role == null) { - addRole(roleName); - } - - roleNames.add(roleName); - } - - entity.setDefaultRoles(roleNames); - } - - @Override - public int getNodeReRegistrationTimeout() { - return entity.getNodeReRegistrationTimeout(); - } - - @Override - public void setNodeReRegistrationTimeout(int timeout) { - entity.setNodeReRegistrationTimeout(timeout); - } - - @Override - public Map getRegisteredNodes() { - return entity.getRegisteredNodes() == null ? Collections.emptyMap() : Collections.unmodifiableMap(entity.getRegisteredNodes()); - } - - @Override - public void registerNode(String nodeHost, int registrationTime) { - if (entity.getRegisteredNodes() == null) { - entity.setRegisteredNodes(new HashMap()); - } - - entity.getRegisteredNodes().put(nodeHost, registrationTime); - } - - @Override - public void unregisterNode(String nodeHost) { - if (entity.getRegisteredNodes() == null) return; - - entity.getRegisteredNodes().remove(nodeHost); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || !(o instanceof ClientModel)) return false; - - ClientModel that = (ClientModel) o; - return that.getId().equals(getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } -} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java deleted file mode 100755 index 14f92cb45e..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.keycloak.models.file.adapter; - -import org.keycloak.models.ClientModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.entities.GroupEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * - * @author Marek Posolda - */ -public class GroupAdapter implements GroupModel { - - private final GroupEntity group; - private RealmModel realm; - private KeycloakSession session; - - public GroupAdapter(KeycloakSession session, RealmModel realm, GroupEntity group) { - this.group = group; - this.realm = realm; - this.session = session; - } - - @Override - public String getId() { - return group.getId(); - } - - @Override - public String getName() { - return group.getName(); - } - - @Override - public void setName(String name) { - group.setName(name); - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || !(o instanceof GroupModel)) return false; - - GroupModel that = (GroupModel) o; - return that.getId().equals(getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - - @Override - public void setSingleAttribute(String name, String value) { - if (group.getAttributes() == null) { - group.setAttributes(new HashMap>()); - } - - List attrValues = new ArrayList<>(); - attrValues.add(value); - group.getAttributes().put(name, attrValues); - } - - @Override - public void setAttribute(String name, List values) { - if (group.getAttributes() == null) { - group.setAttributes(new HashMap>()); - } - - group.getAttributes().put(name, values); - } - - @Override - public void removeAttribute(String name) { - if (group.getAttributes() == null) return; - - group.getAttributes().remove(name); - } - - @Override - public String getFirstAttribute(String name) { - if (group.getAttributes()==null) return null; - - List attrValues = group.getAttributes().get(name); - return (attrValues==null || attrValues.isEmpty()) ? null : attrValues.get(0); - } - - @Override - public List getAttribute(String name) { - if (group.getAttributes()==null) return Collections.emptyList(); - List attrValues = group.getAttributes().get(name); - return (attrValues == null) ? Collections.emptyList() : Collections.unmodifiableList(attrValues); - } - - @Override - public Map> getAttributes() { - return group.getAttributes()==null ? Collections.>emptyMap() : Collections.unmodifiableMap((Map) group.getAttributes()); - } - - @Override - public boolean hasRole(RoleModel role) { - Set roles = getRoleMappings(); - return KeycloakModelUtils.hasRole(roles, role); - } - - @Override - public void grantRole(RoleModel role) { - if (group.getRoleIds() == null) { - group.setRoleIds(new LinkedList()); - } - if (group.getRoleIds().contains(role.getId())) { - return; - } - group.getRoleIds().add(role.getId()); - } - - @Override - public Set getRoleMappings() { - if (group.getRoleIds() == null || group.getRoleIds().isEmpty()) return Collections.EMPTY_SET; - Set roles = new HashSet<>(); - for (String id : group.getRoleIds()) { - roles.add(realm.getRoleById(id)); - } - return roles; - } - - @Override - public Set getRealmRoleMappings() { - Set allRoles = getRoleMappings(); - - // Filter to retrieve just realm roles - Set realmRoles = new HashSet(); - for (RoleModel role : allRoles) { - if (role.getContainer() instanceof RealmModel) { - realmRoles.add(role); - } - } - return realmRoles; - } - - @Override - public void deleteRoleMapping(RoleModel role) { - if (group == null || role == null) return; - if (group.getRoleIds() == null) return; - group.getRoleIds().remove(role.getId()); - } - - @Override - public Set getClientRoleMappings(ClientModel app) { - Set result = new HashSet(); - Set roles = getRoleMappings(); - - for (RoleModel role : roles) { - if (app.equals(role.getContainer())) { - result.add(role); - } - } - return result; - } - - @Override - public GroupModel getParent() { - if (group.getParentId() == null) return null; - return realm.getGroupById(group.getParentId()); - } - - @Override - public String getParentId() { - return group.getParentId(); - } - - @Override - public Set getSubGroups() { - Set subGroups = new HashSet<>(); - for (GroupModel groupModel : realm.getGroups()) { - if (groupModel.getParent().equals(this)) { - subGroups.add(groupModel); - } - } - return subGroups; - } - - @Override - public void setParent(GroupModel group) { - this.group.setParentId(group.getId()); - - } - - @Override - public void addChild(GroupModel subGroup) { - subGroup.setParent(this); - - } - - @Override - public void removeChild(GroupModel subGroup) { - subGroup.setParent(null); - - } -} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/MigrationModelAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/MigrationModelAdapter.java deleted file mode 100755 index 13695db46b..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/MigrationModelAdapter.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.keycloak.models.file.adapter; - -import org.keycloak.connections.file.InMemoryModel; -import org.keycloak.migration.MigrationModel; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class MigrationModelAdapter implements MigrationModel { - protected InMemoryModel em; - - public MigrationModelAdapter(InMemoryModel em) { - this.em = em; - } - - @Override - public String getStoredVersion() { - return em.getModelVersion(); - } - - @Override - public void setStoredVersion(String version) { - em.setModelVersion(version); - } -} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java deleted file mode 100755 index 643c3c8560..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java +++ /dev/null @@ -1,1840 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file.adapter; - -import org.keycloak.connections.file.InMemoryModel; -import org.keycloak.common.enums.SslRequired; -import org.keycloak.models.AuthenticationExecutionModel; -import org.keycloak.models.AuthenticationFlowModel; -import org.keycloak.models.AuthenticatorConfigModel; -import org.keycloak.models.ClientModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.IdentityProviderMapperModel; -import org.keycloak.models.IdentityProviderModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.OTPPolicy; -import org.keycloak.models.PasswordPolicy; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RequiredActionProviderModel; -import org.keycloak.models.RequiredCredentialModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserFederationMapperEventImpl; -import org.keycloak.models.UserFederationMapperModel; -import org.keycloak.models.UserFederationProviderCreationEventImpl; -import org.keycloak.models.UserFederationProviderModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.entities.AuthenticationExecutionEntity; -import org.keycloak.models.entities.AuthenticationFlowEntity; -import org.keycloak.models.entities.AuthenticatorConfigEntity; -import org.keycloak.models.entities.ClientEntity; -import org.keycloak.models.entities.IdentityProviderMapperEntity; -import org.keycloak.models.entities.RealmEntity; -import org.keycloak.models.entities.RequiredActionProviderEntity; -import org.keycloak.models.entities.RequiredCredentialEntity; -import org.keycloak.models.entities.RoleEntity; -import org.keycloak.models.entities.UserFederationMapperEntity; -import org.keycloak.models.entities.UserFederationProviderEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.security.Key; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * RealmModel for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class RealmAdapter implements RealmModel { - - private final InMemoryModel inMemoryModel; - private final RealmEntity realm; - - protected volatile transient PublicKey publicKey; - protected volatile transient PrivateKey privateKey; - protected volatile transient X509Certificate certificate; - protected volatile transient Key codeSecretKey; - - private volatile transient PasswordPolicy passwordPolicy; - private volatile transient OTPPolicy otpPolicy; - private volatile transient KeycloakSession session; - - private final Map allApps = new HashMap(); - private ClientModel masterAdminApp = null; - private final Map allRoles = new HashMap(); - private final Map allGroups = new HashMap(); - private final Map allIdProviders = new HashMap(); - - public RealmAdapter(KeycloakSession session, RealmEntity realm, InMemoryModel inMemoryModel) { - this.session = session; - this.realm = realm; - this.inMemoryModel = inMemoryModel; - } - - public RealmEntity getRealmEnity() { - return realm; - } - - @Override - public String getId() { - return realm.getId(); - } - - @Override - public String getName() { - return realm.getName(); - } - - @Override - public void setName(String name) { - if (getName() == null) { - realm.setName(name); - return; - } - - if (getName().equals(name)) return; // allow setting name to same value - - if (inMemoryModel.getRealmByName(name) != null) throw new ModelDuplicateException("Realm " + name + " already exists."); - realm.setName(name); - } - - @Override - public boolean isEnabled() { - return realm.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - realm.setEnabled(enabled); - } - - @Override - public SslRequired getSslRequired() { - return SslRequired.valueOf(realm.getSslRequired()); - } - - @Override - public void setSslRequired(SslRequired sslRequired) { - realm.setSslRequired(sslRequired.name()); - } - - @Override - public boolean isRegistrationAllowed() { - return realm.isRegistrationAllowed(); - } - - @Override - public void setRegistrationAllowed(boolean registrationAllowed) { - realm.setRegistrationAllowed(registrationAllowed); - } - - @Override - public boolean isRegistrationEmailAsUsername() { - return realm.isRegistrationEmailAsUsername(); - } - - @Override - public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) { - realm.setRegistrationEmailAsUsername(registrationEmailAsUsername); - } - - @Override - public boolean isRememberMe() { - return realm.isRememberMe(); - } - - @Override - public void setRememberMe(boolean rememberMe) { - realm.setRememberMe(rememberMe); - } - - @Override - public boolean isBruteForceProtected() { - return realm.isBruteForceProtected(); - } - - @Override - public void setBruteForceProtected(boolean value) { - realm.setBruteForceProtected(value); - } - - @Override - public int getMaxFailureWaitSeconds() { - return realm.getMaxFailureWaitSeconds(); - } - - @Override - public void setMaxFailureWaitSeconds(int val) { - realm.setMaxFailureWaitSeconds(val); - } - - @Override - public int getWaitIncrementSeconds() { - return realm.getWaitIncrementSeconds(); - } - - @Override - public void setWaitIncrementSeconds(int val) { - realm.setWaitIncrementSeconds(val); - } - - @Override - public long getQuickLoginCheckMilliSeconds() { - return realm.getQuickLoginCheckMilliSeconds(); - } - - @Override - public void setQuickLoginCheckMilliSeconds(long val) { - realm.setQuickLoginCheckMilliSeconds(val); - } - - @Override - public int getMinimumQuickLoginWaitSeconds() { - return realm.getMinimumQuickLoginWaitSeconds(); - } - - @Override - public void setMinimumQuickLoginWaitSeconds(int val) { - realm.setMinimumQuickLoginWaitSeconds(val); - } - - - @Override - public int getMaxDeltaTimeSeconds() { - return realm.getMaxDeltaTimeSeconds(); - } - - @Override - public void setMaxDeltaTimeSeconds(int val) { - realm.setMaxDeltaTimeSeconds(val); - } - - @Override - public int getFailureFactor() { - return realm.getFailureFactor(); - } - - @Override - public void setFailureFactor(int failureFactor) { - realm.setFailureFactor(failureFactor); - } - - - @Override - public boolean isVerifyEmail() { - return realm.isVerifyEmail(); - } - - @Override - public void setVerifyEmail(boolean verifyEmail) { - realm.setVerifyEmail(verifyEmail); - } - - @Override - public boolean isResetPasswordAllowed() { - return realm.isResetPasswordAllowed(); - } - - @Override - public void setResetPasswordAllowed(boolean resetPassword) { - realm.setResetPasswordAllowed(resetPassword); - } - - @Override - public boolean isEditUsernameAllowed() { - return realm.isEditUsernameAllowed(); - } - - @Override - public void setEditUsernameAllowed(boolean editUsernameAllowed) { - realm.setEditUsernameAllowed(editUsernameAllowed); - } - - @Override - public PasswordPolicy getPasswordPolicy() { - if (passwordPolicy == null) { - passwordPolicy = new PasswordPolicy(realm.getPasswordPolicy()); - } - return passwordPolicy; - } - - @Override - public void setPasswordPolicy(PasswordPolicy policy) { - this.passwordPolicy = policy; - realm.setPasswordPolicy(policy.toString()); - } - - @Override - public OTPPolicy getOTPPolicy() { - if (otpPolicy == null) { - otpPolicy = new OTPPolicy(); - otpPolicy.setDigits(realm.getOtpPolicyDigits()); - otpPolicy.setAlgorithm(realm.getOtpPolicyAlgorithm()); - otpPolicy.setInitialCounter(realm.getOtpPolicyInitialCounter()); - otpPolicy.setLookAheadWindow(realm.getOtpPolicyLookAheadWindow()); - otpPolicy.setType(realm.getOtpPolicyType()); - otpPolicy.setPeriod(realm.getOtpPolicyPeriod()); - } - return otpPolicy; - } - - @Override - public void setOTPPolicy(OTPPolicy policy) { - realm.setOtpPolicyAlgorithm(policy.getAlgorithm()); - realm.setOtpPolicyDigits(policy.getDigits()); - realm.setOtpPolicyInitialCounter(policy.getInitialCounter()); - realm.setOtpPolicyLookAheadWindow(policy.getLookAheadWindow()); - realm.setOtpPolicyType(policy.getType()); - realm.setOtpPolicyPeriod(policy.getPeriod()); - - } - - @Override - public int getNotBefore() { - return realm.getNotBefore(); - } - - @Override - public void setNotBefore(int notBefore) { - realm.setNotBefore(notBefore); - } - - - @Override - public boolean isRevokeRefreshToken() { - return realm.isRevokeRefreshToken(); - } - - @Override - public void setRevokeRefreshToken(boolean revokeRefreshToken) { - realm.setRevokeRefreshToken(revokeRefreshToken); - } - - @Override - public int getSsoSessionIdleTimeout() { - return realm.getSsoSessionIdleTimeout(); - } - - @Override - public void setSsoSessionIdleTimeout(int seconds) { - realm.setSsoSessionIdleTimeout(seconds); - } - - @Override - public int getSsoSessionMaxLifespan() { - return realm.getSsoSessionMaxLifespan(); - } - - @Override - public void setSsoSessionMaxLifespan(int seconds) { - realm.setSsoSessionMaxLifespan(seconds); - } - - @Override - public int getOfflineSessionIdleTimeout() { - return realm.getOfflineSessionIdleTimeout(); - } - - @Override - public void setOfflineSessionIdleTimeout(int seconds) { - realm.setOfflineSessionIdleTimeout(seconds); - } - - @Override - public int getAccessTokenLifespan() { - return realm.getAccessTokenLifespan(); - } - - @Override - public void setAccessTokenLifespan(int tokenLifespan) { - realm.setAccessTokenLifespan(tokenLifespan); - } - - @Override - public int getAccessCodeLifespan() { - return realm.getAccessCodeLifespan(); - } - - @Override - public void setAccessCodeLifespan(int accessCodeLifespan) { - realm.setAccessCodeLifespan(accessCodeLifespan); - } - - @Override - public int getAccessCodeLifespanUserAction() { - return realm.getAccessCodeLifespanUserAction(); - } - - @Override - public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { - realm.setAccessCodeLifespanUserAction(accessCodeLifespanUserAction); - } - - @Override - public String getPublicKeyPem() { - return realm.getPublicKeyPem(); - } - - @Override - public void setPublicKeyPem(String publicKeyPem) { - realm.setPublicKeyPem(publicKeyPem); - this.publicKey = null; - } - - @Override - public X509Certificate getCertificate() { - if (certificate != null) return certificate; - certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); - return certificate; - } - - @Override - public void setCertificate(X509Certificate certificate) { - this.certificate = certificate; - String certificatePem = KeycloakModelUtils.getPemFromCertificate(certificate); - setCertificatePem(certificatePem); - } - - @Override - public String getCertificatePem() { - return realm.getCertificatePem(); - } - - @Override - public void setCertificatePem(String certificate) { - realm.setCertificatePem(certificate); - - } - - - @Override - public String getPrivateKeyPem() { - return realm.getPrivateKeyPem(); - } - - @Override - public void setPrivateKeyPem(String privateKeyPem) { - realm.setPrivateKeyPem(privateKeyPem); - this.privateKey = null; - } - - @Override - public PublicKey getPublicKey() { - if (publicKey != null) return publicKey; - publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); - return publicKey; - } - - @Override - public void setPublicKey(PublicKey publicKey) { - this.publicKey = publicKey; - String publicKeyPem = KeycloakModelUtils.getPemFromKey(publicKey); - setPublicKeyPem(publicKeyPem); - } - - @Override - public PrivateKey getPrivateKey() { - if (privateKey != null) return privateKey; - privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); - return privateKey; - } - - @Override - public void setPrivateKey(PrivateKey privateKey) { - this.privateKey = privateKey; - String privateKeyPem = KeycloakModelUtils.getPemFromKey(privateKey); - setPrivateKeyPem(privateKeyPem); - } - - @Override - public String getCodeSecret() { - return realm.getCodeSecret(); - } - - @Override - public Key getCodeSecretKey() { - if (codeSecretKey == null) { - codeSecretKey = KeycloakModelUtils.getSecretKey(getCodeSecret()); - } - return codeSecretKey; - } - - @Override - public void setCodeSecret(String codeSecret) { - realm.setCodeSecret(codeSecret); - } - - @Override - public String getLoginTheme() { - return realm.getLoginTheme(); - } - - @Override - public void setLoginTheme(String name) { - realm.setLoginTheme(name); - } - - @Override - public String getAccountTheme() { - return realm.getAccountTheme(); - } - - @Override - public void setAccountTheme(String name) { - realm.setAccountTheme(name); - } - - @Override - public String getAdminTheme() { - return realm.getAdminTheme(); - } - - @Override - public void setAdminTheme(String name) { - realm.setAdminTheme(name); - } - - @Override - public String getEmailTheme() { - return realm.getEmailTheme(); - } - - @Override - public void setEmailTheme(String name) { - realm.setEmailTheme(name); - } - - @Override - public RoleAdapter getRole(String name) { - for (RoleAdapter role : allRoles.values()) { - if (role.getName().equals(name)) return role; - } - return null; - } - - @Override - public RoleModel addRole(String name) { - return this.addRole(KeycloakModelUtils.generateId(), name); - } - - @Override - public RoleModel addRole(String id, String name) { - if (id == null) throw new NullPointerException("id == null"); - if (name == null) throw new NullPointerException("name == null"); - if (hasRoleWithName(name)) throw new ModelDuplicateException("Realm already contains role with name " + name + "."); - - RoleEntity roleEntity = new RoleEntity(); - roleEntity.setId(id); - roleEntity.setName(name); - roleEntity.setRealmId(getId()); - - RoleAdapter roleModel = new RoleAdapter(this, roleEntity, this); - allRoles.put(id, roleModel); - return roleModel; - } - - @Override - public boolean removeRole(RoleModel role) { - return removeRoleById(role.getId()); - } - - @Override - public boolean removeRoleById(String id) { - if (id == null) throw new NullPointerException("id == null"); - - // try realm roles first - if (allRoles.remove(id) != null) return true; - - for (ClientModel app : getClients()) { - for (RoleModel appRole : app.getRoles()) { - if (id.equals(appRole.getId())) { - app.removeRole(appRole); - return true; - } - } - } - - return false; - } - - @Override - public Set getRoles() { - return new HashSet(allRoles.values()); - } - - @Override - public RoleModel getRoleById(String id) { - RoleModel found = allRoles.get(id); - if (found != null) return found; - - for (ClientModel app : getClients()) { - for (RoleModel appRole : app.getRoles()) { - if (appRole.getId().equals(id)) return appRole; - } - } - - return null; - } - - @Override - public GroupModel getGroupById(String id) { - GroupModel found = allGroups.get(id); - if (found != null) return found; - return null; - } - - @Override - public void moveGroup(GroupModel group, GroupModel toParent) { - if (group.getParentId() != null) { - group.getParent().removeChild(group); - } - group.setParent(toParent); - if (toParent != null) toParent.addChild(group); - else addTopLevelGroup(group); - } - @Override - public List getGroups() { - List list = new LinkedList<>(); - for (GroupAdapter group : allGroups.values()) { - list.add(group); - } - return list; - } - - @Override - public List getTopLevelGroups() { - List list = new LinkedList<>(); - for (GroupAdapter group : allGroups.values()) { - if (group.getParent() == null) list.add(group); - } - return list; - } - - @Override - public boolean removeGroup(GroupModel group) { - return allGroups.remove(group.getId()) != null; - } - - @Override - public List getDefaultRoles() { - return realm.getDefaultRoles(); - } - - @Override - public void addDefaultRole(String name) { - RoleModel role = getRole(name); - if (role == null) { - addRole(name); - } - - List roleNames = getDefaultRoles(); - if (roleNames.contains(name)) throw new IllegalArgumentException("Realm " + realm.getName() + " already contains default role named " + name); - - roleNames.add(name); - realm.setDefaultRoles(roleNames); - } - - boolean hasRoleWithName(String name) { - for (RoleModel role : allRoles.values()) { - if (role.getName().equals(name)) return true; - } - - return false; - } - - @Override - public void updateDefaultRoles(String[] defaultRoles) { - List roleNames = new ArrayList(); - for (String roleName : defaultRoles) { - RoleModel role = getRole(roleName); - if (role == null) { - addRole(roleName); - } - - roleNames.add(roleName); - } - - realm.setDefaultRoles(roleNames); - } - - @Override - public ClientModel getClientById(String id) { - return allApps.get(id); - } - - @Override - public ClientModel getClientByClientId(String clientId) { - for (ClientModel app : getClients()) { - if (app.getClientId().equals(clientId)) return app; - } - - return null; - } - - @Override - public Map getClientNameMap() { - Map resourceMap = new HashMap(); - for (ClientModel resource : getClients()) { - resourceMap.put(resource.getClientId(), resource); - } - return resourceMap; - } - - @Override - public List getClients() { - return new ArrayList(allApps.values()); - } - - @Override - public ClientModel addClient(String name) { - return this.addClient(KeycloakModelUtils.generateId(), name); - } - - @Override - public ClientModel addClient(String id, String clientId) { - if (clientId == null) throw new NullPointerException("name == null"); - if (id == null) throw new NullPointerException("id == null"); - - if (getClientNameMap().containsKey(clientId)) { - throw new ModelDuplicateException("Application named '" + clientId + "' already exists."); - } - - ClientEntity appEntity = new ClientEntity(); - appEntity.setId(id); - appEntity.setClientId(clientId); - appEntity.setRealmId(getId()); - appEntity.setEnabled(true); - - final ClientModel app = new ClientAdapter(session, this, appEntity, inMemoryModel); - session.getKeycloakSessionFactory().publish(new ClientCreationEvent() { - @Override - public ClientModel getCreatedClient() { - return app; - } - }); - - allApps.put(id, app); - - return app; - } - - @Override - public boolean removeClient(String id) { - ClientModel appToBeRemoved = this.getClientById(id); - if (appToBeRemoved == null) return false; - - // remove any composite role assignments for this app - for (RoleModel role : this.getRoles()) { - RoleAdapter roleAdapter = (RoleAdapter)role; - roleAdapter.removeApplicationComposites(id); - } - - for (RoleModel role : appToBeRemoved.getRoles()) { - appToBeRemoved.removeRole(role); - } - - return (allApps.remove(id) != null); - } - - boolean hasUserWithEmail(String email) { - for (UserModel user : inMemoryModel.getUsers(getId())) { - if (user.getEmail() == null) continue; - if (user.getEmail().equals(email)) return true; - } - - return false; - } - - @Override - public void addRequiredCredential(String type) { - if (type == null) throw new NullPointerException("Credential type can not be null"); - - RequiredCredentialModel credentialModel = initRequiredCredentialModel(type); - - List requiredCredList = realm.getRequiredCredentials(); - for (RequiredCredentialEntity cred : requiredCredList) { - if (type.equals(cred.getType())) return; - } - - addRequiredCredential(credentialModel, requiredCredList); - } - - protected void addRequiredCredential(RequiredCredentialModel credentialModel, List persistentCollection) { - RequiredCredentialEntity credEntity = new RequiredCredentialEntity(); - credEntity.setType(credentialModel.getType()); - credEntity.setFormLabel(credentialModel.getFormLabel()); - credEntity.setInput(credentialModel.isInput()); - credEntity.setSecret(credentialModel.isSecret()); - - persistentCollection.add(credEntity); - } - - @Override - public void updateRequiredCredentials(Set creds) { - updateRequiredCredentials(creds, realm.getRequiredCredentials()); - } - - protected void updateRequiredCredentials(Set creds, List credsEntities) { - Set already = new HashSet(); - Set toRemove = new HashSet(); - for (RequiredCredentialEntity entity : credsEntities) { - if (!creds.contains(entity.getType())) { - toRemove.add(entity); - } else { - already.add(entity.getType()); - } - } - for (RequiredCredentialEntity entity : toRemove) { - credsEntities.remove(entity); - } - for (String cred : creds) { - if (!already.contains(cred)) { - RequiredCredentialModel credentialModel = initRequiredCredentialModel(cred); - addRequiredCredential(credentialModel, credsEntities); - } - } - } - - @Override - public List getRequiredCredentials() { - return convertRequiredCredentialEntities(realm.getRequiredCredentials()); - } - - protected List convertRequiredCredentialEntities(Collection credEntities) { - - List result = new ArrayList(); - for (RequiredCredentialEntity entity : credEntities) { - RequiredCredentialModel credentialModel = new RequiredCredentialModel(); - credentialModel.setFormLabel(entity.getFormLabel()); - credentialModel.setInput(entity.isInput()); - credentialModel.setSecret(entity.isSecret()); - credentialModel.setType(entity.getType()); - - result.add(credentialModel); - } - return result; - } - - protected RequiredCredentialModel initRequiredCredentialModel(String type) { - RequiredCredentialModel credentialModel = RequiredCredentialModel.BUILT_IN.get(type); - if (credentialModel == null) { - throw new RuntimeException("Unknown credential type " + type); - } - return credentialModel; - } - - @Override - public Map getBrowserSecurityHeaders() { - return realm.getBrowserSecurityHeaders(); - } - - @Override - public void setBrowserSecurityHeaders(Map headers) { - realm.setBrowserSecurityHeaders(headers); - } - - @Override - public Map getSmtpConfig() { - return realm.getSmtpConfig(); - } - - @Override - public void setSmtpConfig(Map smtpConfig) { - realm.setSmtpConfig(smtpConfig); - } - - @Override - public List getIdentityProviders() { - return new ArrayList(allIdProviders.values()); - } - - @Override - public IdentityProviderModel getIdentityProviderByAlias(String alias) { - for (IdentityProviderModel identityProviderModel : getIdentityProviders()) { - if (identityProviderModel.getAlias().equals(alias)) { - return identityProviderModel; - } - } - - return null; - } - - @Override - public void addIdentityProvider(IdentityProviderModel identityProvider) { - if (identityProvider.getAlias() == null) throw new NullPointerException("identityProvider.getAlias() == null"); - if (identityProvider.getInternalId() == null) identityProvider.setInternalId(KeycloakModelUtils.generateId()); - allIdProviders.put(identityProvider.getInternalId(), identityProvider); - } - - @Override - public void removeIdentityProviderByAlias(String alias) { - for (IdentityProviderModel provider : getIdentityProviders()) { - if (provider.getAlias().equals(alias)) { - allIdProviders.remove(provider.getInternalId()); - break; - } - } - } - - @Override - public void updateIdentityProvider(IdentityProviderModel identityProvider) { - removeIdentityProviderByAlias(identityProvider.getAlias()); - addIdentityProvider(identityProvider); - } - - @Override - public UserFederationProviderModel addUserFederationProvider(String providerName, Map config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) { - KeycloakModelUtils.ensureUniqueDisplayName(displayName, null, getUserFederationProviders()); - - UserFederationProviderEntity entity = new UserFederationProviderEntity(); - entity.setId(KeycloakModelUtils.generateId()); - entity.setPriority(priority); - entity.setProviderName(providerName); - entity.setConfig(config); - if (displayName == null) { - displayName = entity.getId(); - } - entity.setDisplayName(displayName); - entity.setFullSyncPeriod(fullSyncPeriod); - entity.setChangedSyncPeriod(changedSyncPeriod); - entity.setLastSync(lastSync); - realm.getUserFederationProviders().add(entity); - - UserFederationProviderModel providerModel = new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync); - - session.getKeycloakSessionFactory().publish(new UserFederationProviderCreationEventImpl(this, providerModel)); - - return providerModel; - } - - @Override - public void removeUserFederationProvider(UserFederationProviderModel provider) { - Iterator it = realm.getUserFederationProviders().iterator(); - while (it.hasNext()) { - UserFederationProviderEntity entity = it.next(); - if (entity.getId().equals(provider.getId())) { - session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), - entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); - - Set mappers = getUserFederationMapperEntitiesByFederationProvider(provider.getId()); - for (UserFederationMapperEntity mapper : mappers) { - realm.getUserFederationMappers().remove(mapper); - } - - it.remove(); - } - } - } - - @Override - public void updateUserFederationProvider(UserFederationProviderModel model) { - KeycloakModelUtils.ensureUniqueDisplayName(model.getDisplayName(), model, getUserFederationProviders()); - - Iterator it = realm.getUserFederationProviders().iterator(); - while (it.hasNext()) { - UserFederationProviderEntity entity = it.next(); - if (entity.getId().equals(model.getId())) { - entity.setProviderName(model.getProviderName()); - entity.setConfig(model.getConfig()); - entity.setPriority(model.getPriority()); - String displayName = model.getDisplayName(); - if (displayName != null) { - entity.setDisplayName(model.getDisplayName()); - } - entity.setFullSyncPeriod(model.getFullSyncPeriod()); - entity.setChangedSyncPeriod(model.getChangedSyncPeriod()); - entity.setLastSync(model.getLastSync()); - } - } - } - - @Override - public List getUserFederationProviders() { - List entities = realm.getUserFederationProviders(); - List copy = new LinkedList(); - for (UserFederationProviderEntity entity : entities) { - copy.add(entity); - - } - Collections.sort(copy, new Comparator() { - - @Override - public int compare(UserFederationProviderEntity o1, UserFederationProviderEntity o2) { - return o1.getPriority() - o2.getPriority(); - } - - }); - List result = new LinkedList(); - for (UserFederationProviderEntity entity : copy) { - result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(), - entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync())); - } - - return result; - } - - @Override - public void setUserFederationProviders(List providers) { - for (UserFederationProviderModel currentProvider : providers) { - KeycloakModelUtils.ensureUniqueDisplayName(currentProvider.getDisplayName(), currentProvider, providers); - } - - List entities = new LinkedList(); - for (UserFederationProviderModel model : providers) { - UserFederationProviderEntity entity = new UserFederationProviderEntity(); - if (model.getId() != null) { - entity.setId(model.getId()); - } else { - String id = KeycloakModelUtils.generateId(); - entity.setId(id); - model.setId(id); - } - entity.setProviderName(model.getProviderName()); - entity.setConfig(model.getConfig()); - entity.setPriority(model.getPriority()); - String displayName = model.getDisplayName(); - if (displayName == null) { - entity.setDisplayName(entity.getId()); - } - entity.setDisplayName(displayName); - entity.setFullSyncPeriod(model.getFullSyncPeriod()); - entity.setChangedSyncPeriod(model.getChangedSyncPeriod()); - entity.setLastSync(model.getLastSync()); - entities.add(entity); - - session.getKeycloakSessionFactory().publish(new UserFederationProviderCreationEventImpl(this, model)); - } - - realm.setUserFederationProviders(entities); - } - - @Override - public boolean isEventsEnabled() { - return realm.isEventsEnabled(); - } - - @Override - public void setEventsEnabled(boolean enabled) { - realm.setEventsEnabled(enabled); - } - - @Override - public long getEventsExpiration() { - return realm.getEventsExpiration(); - } - - @Override - public void setEventsExpiration(long expiration) { - realm.setEventsExpiration(expiration); - } - - @Override - public Set getEventsListeners() { - return new HashSet(realm.getEventsListeners()); - } - - @Override - public void setEventsListeners(Set listeners) { - if (listeners != null) { - realm.setEventsListeners(new ArrayList(listeners)); - } else { - realm.setEventsListeners(Collections.EMPTY_LIST); - } - } - - @Override - public Set getEnabledEventTypes() { - return new HashSet(realm.getEnabledEventTypes()); - } - - @Override - public void setEnabledEventTypes(Set enabledEventTypes) { - if (enabledEventTypes != null) { - realm.setEnabledEventTypes(new ArrayList(enabledEventTypes)); - } else { - realm.setEnabledEventTypes(Collections.EMPTY_LIST); - } - } - - @Override - public boolean isAdminEventsEnabled() { - return realm.isAdminEventsEnabled(); - } - - @Override - public void setAdminEventsEnabled(boolean enabled) { - realm.setAdminEventsEnabled(enabled); - } - - @Override - public boolean isAdminEventsDetailsEnabled() { - return realm.isAdminEventsDetailsEnabled(); - } - - @Override - public void setAdminEventsDetailsEnabled(boolean enabled) { - realm.setAdminEventsDetailsEnabled(enabled); - } - - @Override - public ClientModel getMasterAdminClient() { - return this.masterAdminApp; - } - - @Override - public void setMasterAdminClient(ClientModel client) { - if (client == null) { - realm.setMasterAdminClient(null); - this.masterAdminApp = null; - } else { - String appId = client.getId(); - if (appId == null) { - throw new IllegalStateException("Master Admin app not initialized."); - } - realm.setMasterAdminClient(appId); - this.masterAdminApp = client; - } - } - - @Override - public boolean isIdentityFederationEnabled() { - //TODO: not sure if we will support identity federation storage for file - return getIdentityProviders() != null && !getIdentityProviders().isEmpty(); - } - - @Override - public int getAccessCodeLifespanLogin() { - return realm.getAccessCodeLifespanLogin(); - } - - @Override - public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) { - realm.setAccessCodeLifespanLogin(accessCodeLifespanLogin); - } - - @Override - public boolean isInternationalizationEnabled() { - return realm.isInternationalizationEnabled(); - } - - @Override - public void setInternationalizationEnabled(boolean enabled) { - realm.setInternationalizationEnabled(enabled); - } - - @Override - public Set getSupportedLocales() { - return new HashSet<>(realm.getSupportedLocales()); - } - - @Override - public void setSupportedLocales(Set locales) { - realm.setSupportedLocales(new ArrayList<>(locales)); - } - - @Override - public String getDefaultLocale() { - return realm.getDefaultLocale(); - } - - @Override - public void setDefaultLocale(String locale) { - realm.setDefaultLocale(locale); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || !(o instanceof RealmModel)) return false; - - RealmModel that = (RealmModel) o; - return that.getId().equals(getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - - @Override - public Set getIdentityProviderMappers() { - Set mappings = new HashSet<>(); - for (IdentityProviderMapperEntity entity : this.realm.getIdentityProviderMappers()) { - IdentityProviderMapperModel mapping = entityToModel(entity); - mappings.add(mapping); - } - return mappings; - } - @Override - public Set getIdentityProviderMappersByAlias(String brokerAlias) { - Set mappings = new HashSet<>(); - for (IdentityProviderMapperEntity entity : this.realm.getIdentityProviderMappers()) { - if (!entity.getIdentityProviderAlias().equals(brokerAlias)) { - continue; - } - IdentityProviderMapperModel mapping = entityToModel(entity); - mappings.add(mapping); - } - return mappings; - } - - @Override - public IdentityProviderMapperModel addIdentityProviderMapper(IdentityProviderMapperModel model) { - if (getIdentityProviderMapperByName(model.getIdentityProviderAlias(), model.getIdentityProviderMapper()) != null) { - throw new RuntimeException("identity provider mapper name must be unique per identity provider"); - } - String id = KeycloakModelUtils.generateId(); - IdentityProviderMapperEntity entity = new IdentityProviderMapperEntity(); - entity.setId(id); - entity.setName(model.getName()); - entity.setIdentityProviderAlias(model.getIdentityProviderAlias()); - entity.setIdentityProviderMapper(model.getIdentityProviderMapper()); - entity.setConfig(model.getConfig()); - - this.realm.getIdentityProviderMappers().add(entity); - return entityToModel(entity); - } - - protected IdentityProviderMapperEntity getIdentityProviderMapperEntity(String id) { - for (IdentityProviderMapperEntity entity : this.realm.getIdentityProviderMappers()) { - if (entity.getId().equals(id)) { - return entity; - } - } - return null; - - } - - protected IdentityProviderMapperEntity getIdentityProviderMapperEntityByName(String alias, String name) { - for (IdentityProviderMapperEntity entity : this.realm.getIdentityProviderMappers()) { - if (entity.getIdentityProviderAlias().equals(alias) && entity.getName().equals(name)) { - return entity; - } - } - return null; - - } - - @Override - public void removeIdentityProviderMapper(IdentityProviderMapperModel mapping) { - IdentityProviderMapperEntity toDelete = getIdentityProviderMapperEntity(mapping.getId()); - if (toDelete != null) { - this.realm.getIdentityProviderMappers().remove(toDelete); - } - - } - - @Override - public void updateIdentityProviderMapper(IdentityProviderMapperModel mapping) { - IdentityProviderMapperEntity entity = getIdentityProviderMapperEntity(mapping.getId()); - entity.setIdentityProviderAlias(mapping.getIdentityProviderAlias()); - entity.setIdentityProviderMapper(mapping.getIdentityProviderMapper()); - if (entity.getConfig() == null) { - entity.setConfig(mapping.getConfig()); - } else { - entity.getConfig().clear(); - entity.getConfig().putAll(mapping.getConfig()); - } - - } - - @Override - public IdentityProviderMapperModel getIdentityProviderMapperById(String id) { - IdentityProviderMapperEntity entity = getIdentityProviderMapperEntity(id); - if (entity == null) return null; - return entityToModel(entity); - } - - @Override - public IdentityProviderMapperModel getIdentityProviderMapperByName(String alias, String name) { - IdentityProviderMapperEntity entity = getIdentityProviderMapperEntityByName(alias, name); - if (entity == null) return null; - return entityToModel(entity); - } - - protected IdentityProviderMapperModel entityToModel(IdentityProviderMapperEntity entity) { - IdentityProviderMapperModel mapping = new IdentityProviderMapperModel(); - mapping.setId(entity.getId()); - mapping.setName(entity.getName()); - mapping.setIdentityProviderAlias(entity.getIdentityProviderAlias()); - mapping.setIdentityProviderMapper(entity.getIdentityProviderMapper()); - Map config = new HashMap(); - if (entity.getConfig() != null) config.putAll(entity.getConfig()); - mapping.setConfig(config); - return mapping; - } - - @Override - public AuthenticationFlowModel getBrowserFlow() { - String flowId = realm.getBrowserFlow(); - if (flowId == null) return null; - return getAuthenticationFlowById(flowId); - } - - @Override - public void setBrowserFlow(AuthenticationFlowModel flow) { - realm.setBrowserFlow(flow.getId()); - - } - - @Override - public AuthenticationFlowModel getRegistrationFlow() { - String flowId = realm.getRegistrationFlow(); - if (flowId == null) return null; - return getAuthenticationFlowById(flowId); - } - - @Override - public void setRegistrationFlow(AuthenticationFlowModel flow) { - realm.setRegistrationFlow(flow.getId()); - - } - - @Override - public AuthenticationFlowModel getDirectGrantFlow() { - String flowId = realm.getDirectGrantFlow(); - if (flowId == null) return null; - return getAuthenticationFlowById(flowId); - } - - @Override - public void setDirectGrantFlow(AuthenticationFlowModel flow) { - realm.setDirectGrantFlow(flow.getId()); - - } - - @Override - public AuthenticationFlowModel getResetCredentialsFlow() { - String flowId = realm.getResetCredentialsFlow(); - if (flowId == null) return null; - return getAuthenticationFlowById(flowId); - } - - @Override - public void setResetCredentialsFlow(AuthenticationFlowModel flow) { - realm.setResetCredentialsFlow(flow.getId()); - } - - public AuthenticationFlowModel getClientAuthenticationFlow() { - String flowId = realm.getClientAuthenticationFlow(); - if (flowId == null) return null; - return getAuthenticationFlowById(flowId); - } - - - public void setClientAuthenticationFlow(AuthenticationFlowModel flow) { - realm.setClientAuthenticationFlow(flow.getId()); - } - - @Override - public List getAuthenticationFlows() { - List flows = realm.getAuthenticationFlows(); - if (flows.size() == 0) return Collections.EMPTY_LIST; - List models = new LinkedList<>(); - for (AuthenticationFlowEntity entity : flows) { - AuthenticationFlowModel model = entityToModel(entity); - models.add(model); - } - return models; - } - - - - @Override - public AuthenticationFlowModel getFlowByAlias(String alias) { - for (AuthenticationFlowModel flow : getAuthenticationFlows()) { - if (flow.getAlias().equals(alias)) { - return flow; - } - } - return null; - } - - - protected AuthenticationFlowModel entityToModel(AuthenticationFlowEntity entity) { - AuthenticationFlowModel model = new AuthenticationFlowModel(); - model.setId(entity.getId()); - model.setAlias(entity.getAlias()); - model.setDescription(entity.getDescription()); - model.setProviderId(entity.getProviderId()); - model.setBuiltIn(entity.isBuiltIn()); - model.setTopLevel(entity.isTopLevel()); - return model; - } - - @Override - public AuthenticationFlowModel getAuthenticationFlowById(String id) { - for (AuthenticationFlowModel model : getAuthenticationFlows()) { - if (model.getId().equals(id)) return model; - } - return null; - } - - protected AuthenticationFlowEntity getFlowEntity(String id) { - List flows = realm.getAuthenticationFlows(); - for (AuthenticationFlowEntity entity : flows) { - if (id.equals(entity.getId())) return entity; - } - return null; - - } - - @Override - public void removeAuthenticationFlow(AuthenticationFlowModel model) { - AuthenticationFlowEntity toDelete = getFlowEntity(model.getId()); - if (toDelete == null) return; - realm.getAuthenticationFlows().remove(toDelete); - } - - @Override - public void updateAuthenticationFlow(AuthenticationFlowModel model) { - AuthenticationFlowEntity toUpdate = getFlowEntity(model.getId()); - if (toUpdate == null) return; - toUpdate.setAlias(model.getAlias()); - toUpdate.setDescription(model.getDescription()); - toUpdate.setProviderId(model.getProviderId()); - toUpdate.setBuiltIn(model.isBuiltIn()); - toUpdate.setTopLevel(model.isTopLevel()); - - } - - @Override - public AuthenticationFlowModel addAuthenticationFlow(AuthenticationFlowModel model) { - AuthenticationFlowEntity entity = new AuthenticationFlowEntity(); - String id = (model.getId() == null) ? KeycloakModelUtils.generateId(): model.getId(); - entity.setId(id); - entity.setAlias(model.getAlias()); - entity.setDescription(model.getDescription()); - entity.setProviderId(model.getProviderId()); - entity.setBuiltIn(model.isBuiltIn()); - entity.setTopLevel(model.isTopLevel()); - realm.getAuthenticationFlows().add(entity); - model.setId(entity.getId()); - return model; - } - - @Override - public List getAuthenticationExecutions(String flowId) { - AuthenticationFlowEntity flow = getFlowEntity(flowId); - if (flow == null) return Collections.EMPTY_LIST; - - List queryResult = flow.getExecutions(); - List executions = new LinkedList<>(); - for (AuthenticationExecutionEntity entity : queryResult) { - AuthenticationExecutionModel model = entityToModel(entity); - executions.add(model); - } - Collections.sort(executions, AuthenticationExecutionModel.ExecutionComparator.SINGLETON); - return executions; - } - - public AuthenticationExecutionModel entityToModel(AuthenticationExecutionEntity entity) { - AuthenticationExecutionModel model = new AuthenticationExecutionModel(); - model.setId(entity.getId()); - model.setRequirement(entity.getRequirement()); - model.setPriority(entity.getPriority()); - model.setAuthenticator(entity.getAuthenticator()); - model.setParentFlow(entity.getParentFlow()); - model.setFlowId(entity.getFlowId()); - model.setAuthenticatorFlow(entity.isAuthenticatorFlow()); - model.setAuthenticatorConfig(entity.getAuthenticatorConfig()); - return model; - } - - @Override - public AuthenticationExecutionModel getAuthenticationExecutionById(String id) { - AuthenticationExecutionEntity execution = getAuthenticationExecutionEntity(id); - return entityToModel(execution); - } - - public AuthenticationExecutionEntity getAuthenticationExecutionEntity(String id) { - List flows = realm.getAuthenticationFlows(); - for (AuthenticationFlowEntity entity : flows) { - for (AuthenticationExecutionEntity exe : entity.getExecutions()) { - if (exe.getId().equals(id)) { - return exe; - } - } - } - return null; - } - - @Override - public AuthenticationExecutionModel addAuthenticatorExecution(AuthenticationExecutionModel model) { - AuthenticationExecutionEntity entity = new AuthenticationExecutionEntity(); - String id = (model.getId() == null) ? KeycloakModelUtils.generateId(): model.getId(); - entity.setId(id); - entity.setAuthenticator(model.getAuthenticator()); - entity.setPriority(model.getPriority()); - entity.setRequirement(model.getRequirement()); - entity.setAuthenticatorFlow(model.isAuthenticatorFlow()); - entity.setFlowId(model.getFlowId()); - entity.setAuthenticatorConfig(model.getAuthenticatorConfig()); - AuthenticationFlowEntity flow = getFlowEntity(model.getId()); - flow.getExecutions().add(entity); - model.setId(entity.getId()); - return model; - - } - - @Override - public void updateAuthenticatorExecution(AuthenticationExecutionModel model) { - AuthenticationExecutionEntity entity = null; - AuthenticationFlowEntity flow = getFlowEntity(model.getParentFlow()); - for (AuthenticationExecutionEntity exe : flow.getExecutions()) { - if (exe.getId().equals(model.getId())) { - entity = exe; - } - } - if (entity == null) return; - entity.setAuthenticatorFlow(model.isAuthenticatorFlow()); - entity.setAuthenticator(model.getAuthenticator()); - entity.setPriority(model.getPriority()); - entity.setRequirement(model.getRequirement()); - entity.setFlowId(model.getFlowId()); - entity.setAuthenticatorConfig(model.getAuthenticatorConfig()); - } - - @Override - public void removeAuthenticatorExecution(AuthenticationExecutionModel model) { - AuthenticationExecutionEntity entity = null; - AuthenticationFlowEntity flow = getFlowEntity(model.getParentFlow()); - for (AuthenticationExecutionEntity exe : flow.getExecutions()) { - if (exe.getId().equals(model.getId())) { - entity = exe; - } - } - if (entity == null) return; - flow.getExecutions().remove(entity); - - } - - @Override - public List getAuthenticatorConfigs() { - List authenticators = new LinkedList<>(); - for (AuthenticatorConfigEntity entity : realm.getAuthenticatorConfigs()) { - authenticators.add(entityToModel(entity)); - } - return authenticators; - } - - @Override - public AuthenticatorConfigModel getAuthenticatorConfigByAlias(String alias) { - for (AuthenticatorConfigModel config : getAuthenticatorConfigs()) { - if (config.getAlias().equals(alias)) { - return config; - } - } - return null; - } - - - @Override - public AuthenticatorConfigModel addAuthenticatorConfig(AuthenticatorConfigModel model) { - AuthenticatorConfigEntity auth = new AuthenticatorConfigEntity(); - String id = (model.getId() == null) ? KeycloakModelUtils.generateId(): model.getId(); - auth.setId(id); - auth.setAlias(model.getAlias()); - auth.setConfig(model.getConfig()); - realm.getAuthenticatorConfigs().add(auth); - model.setId(auth.getId()); - return model; - } - - @Override - public void removeAuthenticatorConfig(AuthenticatorConfigModel model) { - AuthenticatorConfigEntity entity = getAuthenticatorEntity(model.getId()); - if (entity == null) return; - realm.getAuthenticatorConfigs().remove(entity); - - } - - @Override - public AuthenticatorConfigModel getAuthenticatorConfigById(String id) { - AuthenticatorConfigEntity entity = getAuthenticatorEntity(id); - if (entity == null) return null; - return entityToModel(entity); - } - - public AuthenticatorConfigEntity getAuthenticatorEntity(String id) { - AuthenticatorConfigEntity entity = null; - for (AuthenticatorConfigEntity auth : realm.getAuthenticatorConfigs()) { - if (auth.getId().equals(id)) { - entity = auth; - break; - } - } - return entity; - } - - public AuthenticatorConfigModel entityToModel(AuthenticatorConfigEntity entity) { - AuthenticatorConfigModel model = new AuthenticatorConfigModel(); - model.setId(entity.getId()); - model.setAlias(entity.getAlias()); - Map config = new HashMap<>(); - if (entity.getConfig() != null) config.putAll(entity.getConfig()); - model.setConfig(config); - return model; - } - - @Override - public void updateAuthenticatorConfig(AuthenticatorConfigModel model) { - AuthenticatorConfigEntity entity = getAuthenticatorEntity(model.getId()); - if (entity == null) return; - entity.setAlias(model.getAlias()); - if (entity.getConfig() == null) { - entity.setConfig(model.getConfig()); - } else { - entity.getConfig().clear(); - entity.getConfig().putAll(model.getConfig()); - } - } - - @Override - public RequiredActionProviderModel addRequiredActionProvider(RequiredActionProviderModel model) { - RequiredActionProviderEntity auth = new RequiredActionProviderEntity(); - auth.setId(KeycloakModelUtils.generateId()); - auth.setAlias(model.getAlias()); - auth.setName(model.getName()); - auth.setProviderId(model.getProviderId()); - auth.setConfig(model.getConfig()); - auth.setEnabled(model.isEnabled()); - auth.setDefaultAction(model.isDefaultAction()); - realm.getRequiredActionProviders().add(auth); - model.setId(auth.getId()); - return model; - } - - @Override - public void removeRequiredActionProvider(RequiredActionProviderModel model) { - RequiredActionProviderEntity entity = getRequiredActionProviderEntity(model.getId()); - if (entity == null) return; - realm.getRequiredActionProviders().remove(entity); - } - - @Override - public RequiredActionProviderModel getRequiredActionProviderById(String id) { - RequiredActionProviderEntity entity = getRequiredActionProviderEntity(id); - if (entity == null) return null; - return entityToModel(entity); - } - - public RequiredActionProviderModel entityToModel(RequiredActionProviderEntity entity) { - RequiredActionProviderModel model = new RequiredActionProviderModel(); - model.setId(entity.getId()); - model.setProviderId(entity.getProviderId()); - model.setAlias(entity.getAlias()); - model.setName(entity.getName()); - model.setEnabled(entity.isEnabled()); - model.setDefaultAction(entity.isDefaultAction()); - Map config = new HashMap<>(); - if (entity.getConfig() != null) config.putAll(entity.getConfig()); - model.setConfig(config); - return model; - } - - @Override - public void updateRequiredActionProvider(RequiredActionProviderModel model) { - RequiredActionProviderEntity entity = getRequiredActionProviderEntity(model.getId()); - if (entity == null) return; - entity.setAlias(model.getAlias()); - entity.setProviderId(model.getProviderId()); - entity.setEnabled(model.isEnabled()); - entity.setName(model.getName()); - entity.setDefaultAction(model.isDefaultAction()); - if (entity.getConfig() == null) { - entity.setConfig(model.getConfig()); - } else { - entity.getConfig().clear(); - entity.getConfig().putAll(model.getConfig()); - } - } - - @Override - public List getRequiredActionProviders() { - List actions = new LinkedList<>(); - for (RequiredActionProviderEntity entity : realm.getRequiredActionProviders()) { - actions.add(entityToModel(entity)); - } - return actions; - } - - public RequiredActionProviderEntity getRequiredActionProviderEntity(String id) { - RequiredActionProviderEntity entity = null; - for (RequiredActionProviderEntity auth : realm.getRequiredActionProviders()) { - if (auth.getId().equals(id)) { - entity = auth; - break; - } - } - return entity; - } - - @Override - public RequiredActionProviderModel getRequiredActionProviderByAlias(String alias) { - for (RequiredActionProviderModel action : getRequiredActionProviders()) { - if (action.getAlias().equals(alias)) return action; - } - return null; - } - - - - - @Override - public Set getUserFederationMappers() { - Set mappers = new HashSet(); - for (UserFederationMapperEntity entity : this.realm.getUserFederationMappers()) { - UserFederationMapperModel mapper = entityToModel(entity); - mappers.add(mapper); - } - return mappers; - } - - @Override - public Set getUserFederationMappersByFederationProvider(String federationProviderId) { - Set mappers = new HashSet(); - Set mapperEntities = getUserFederationMapperEntitiesByFederationProvider(federationProviderId); - for (UserFederationMapperEntity entity : mapperEntities) { - mappers.add(entityToModel(entity)); - } - return mappers; - } - - @Override - public UserFederationMapperModel addUserFederationMapper(UserFederationMapperModel model) { - if (getUserFederationMapperByName(model.getFederationProviderId(), model.getName()) != null) { - throw new ModelDuplicateException("User federation mapper must be unique per federation provider. There is already: " + model.getName()); - } - String id = KeycloakModelUtils.generateId(); - UserFederationMapperEntity entity = new UserFederationMapperEntity(); - entity.setId(id); - entity.setName(model.getName()); - entity.setFederationProviderId(model.getFederationProviderId()); - entity.setFederationMapperType(model.getFederationMapperType()); - entity.setConfig(model.getConfig()); - - this.realm.getUserFederationMappers().add(entity); - UserFederationMapperModel mapperModel = entityToModel(entity); - - session.getKeycloakSessionFactory().publish(new UserFederationMapperEventImpl(mapperModel, this, session)); - - return mapperModel; - } - - protected UserFederationMapperEntity getUserFederationMapperEntity(String id) { - for (UserFederationMapperEntity entity : this.realm.getUserFederationMappers()) { - if (entity.getId().equals(id)) { - return entity; - } - } - return null; - - } - - protected UserFederationMapperEntity getUserFederationMapperEntityByName(String federationProviderId, String name) { - for (UserFederationMapperEntity entity : this.realm.getUserFederationMappers()) { - if (entity.getFederationProviderId().equals(federationProviderId) && entity.getName().equals(name)) { - return entity; - } - } - return null; - - } - - protected Set getUserFederationMapperEntitiesByFederationProvider(String federationProviderId) { - Set mappers = new HashSet(); - for (UserFederationMapperEntity entity : this.realm.getUserFederationMappers()) { - if (federationProviderId.equals(entity.getFederationProviderId())) { - mappers.add(entity); - } - } - return mappers; - } - - @Override - public void removeUserFederationMapper(UserFederationMapperModel mapper) { - UserFederationMapperEntity toDelete = getUserFederationMapperEntity(mapper.getId()); - if (toDelete != null) { - this.realm.getUserFederationMappers().remove(toDelete); - } - } - - @Override - public void updateUserFederationMapper(UserFederationMapperModel mapper) { - UserFederationMapperEntity entity = getUserFederationMapperEntity(mapper.getId()); - entity.setFederationProviderId(mapper.getFederationProviderId()); - entity.setFederationMapperType(mapper.getFederationMapperType()); - if (entity.getConfig() == null) { - entity.setConfig(mapper.getConfig()); - } else { - entity.getConfig().clear(); - entity.getConfig().putAll(mapper.getConfig()); - } - - session.getKeycloakSessionFactory().publish(new UserFederationMapperEventImpl(mapper, this, session)); - } - - @Override - public UserFederationMapperModel getUserFederationMapperById(String id) { - UserFederationMapperEntity entity = getUserFederationMapperEntity(id); - if (entity == null) return null; - return entityToModel(entity); - } - - @Override - public UserFederationMapperModel getUserFederationMapperByName(String federationProviderId, String name) { - UserFederationMapperEntity entity = getUserFederationMapperEntityByName(federationProviderId, name); - if (entity == null) return null; - return entityToModel(entity); - } - - protected UserFederationMapperModel entityToModel(UserFederationMapperEntity entity) { - UserFederationMapperModel mapper = new UserFederationMapperModel(); - mapper.setId(entity.getId()); - mapper.setName(entity.getName()); - mapper.setFederationProviderId(entity.getFederationProviderId()); - mapper.setFederationMapperType(entity.getFederationMapperType()); - Map config = new HashMap(); - if (entity.getConfig() != null) config.putAll(entity.getConfig()); - mapper.setConfig(config); - return mapper; - } - - @Override - public GroupModel createGroup(String name) { - return null; - } - - @Override - public void addTopLevelGroup(GroupModel subGroup) { - - } -} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/RoleAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/RoleAdapter.java deleted file mode 100755 index 7706459df7..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/RoleAdapter.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file.adapter; - -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleContainerModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.entities.RoleEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * RoleModel for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class RoleAdapter implements RoleModel { - - private final RoleEntity role; - private RoleContainerModel roleContainer; - private final RealmModel realm; - - private final Set compositeRoles = new HashSet(); - - public RoleAdapter(RealmModel realm, RoleEntity roleEntity) { - this(realm, roleEntity, null); - } - - public RoleAdapter(RealmModel realm, RoleEntity roleEntity, RoleContainerModel roleContainer) { - this.role = roleEntity; - this.roleContainer = roleContainer; - this.realm = realm; - } - - public RoleEntity getRoleEntity() { - return this.role; - } - - public boolean isRealmRole() { - return role.getRealmId() != null; - } - - @Override - public String getId() { - return role.getId(); - } - - @Override - public String getName() { - return role.getName(); - } - - @Override - public void setName(String name) { - RealmAdapter realmAdapter = (RealmAdapter)realm; - if (role.getName().equals(name)) return; - if (realmAdapter.hasRoleWithName(name)) throw new ModelDuplicateException("Role name " + name + " already exists."); - role.setName(name); - } - - @Override - public String getDescription() { - return role.getDescription(); - } - - @Override - public void setDescription(String description) { - role.setDescription(description); - } - - @Override - public boolean isScopeParamRequired() { - return role.isScopeParamRequired(); - } - - @Override - public void setScopeParamRequired(boolean scopeParamRequired) { - role.setScopeParamRequired(scopeParamRequired); - } - - @Override - public boolean isComposite() { - return role.getCompositeRoleIds() != null && role.getCompositeRoleIds().size() > 0; - } - - @Override - public void addCompositeRole(RoleModel childRole) { - List compositeRoleIds = role.getCompositeRoleIds(); - if (compositeRoleIds == null) compositeRoleIds = new ArrayList(); - compositeRoleIds.add(childRole.getId()); - role.setCompositeRoleIds(compositeRoleIds); - compositeRoles.add(childRole); - } - - /** - * Recursively remove composite roles for the specified app - * @param appId - */ - public void removeApplicationComposites(String appId) { - if (!isComposite()) return; - Set toBeRemoved = new HashSet(); - for (RoleModel compositeRole : getComposites()) { - RoleAdapter roleAdapter = (RoleAdapter)compositeRole; - if (appId.equals(roleAdapter.getRoleEntity().getClientId())) { - toBeRemoved.add(compositeRole); - } else { - roleAdapter.removeApplicationComposites(appId); - } - } - - for (RoleModel compositeRole : toBeRemoved) { - removeCompositeRole(compositeRole); - } - } - - @Override - public void removeCompositeRole(RoleModel childRole) { - compositeRoles.remove(childRole); - List compositeRoleIds = role.getCompositeRoleIds(); - if (compositeRoleIds == null) return; // shouldn't happen - compositeRoleIds.remove(childRole.getId()); - role.setCompositeRoleIds(compositeRoleIds); - } - - @Override - public Set getComposites() { - return Collections.unmodifiableSet(compositeRoles); - } - - @Override - public RoleContainerModel getContainer() { - if (roleContainer == null) { - // Compute it - if (role.getRealmId() != null) { - roleContainer = realm;//new RealmAdapter(session, realm); - } else if (role.getClientId() != null) { - roleContainer = realm.getClientById(role.getClientId());//new ApplicationAdapter(session, realm, appEntity); - } else { - throw new IllegalStateException("Both realmId and applicationId are null for role: " + this); - } - } - return roleContainer; - } - - @Override - public boolean hasRole(RoleModel role) { - if (this.equals(role)) return true; - if (!isComposite()) return false; - - Set visited = new HashSet(); - return KeycloakModelUtils.searchFor(role, this, visited); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || !(o instanceof RoleModel)) return false; - - RoleModel that = (RoleModel) o; - return that.getId().equals(getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - -} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java deleted file mode 100755 index d0dc92b756..0000000000 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java +++ /dev/null @@ -1,614 +0,0 @@ -/* - * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @author tags. All rights reserved. - * - * 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.file.adapter; - -import org.keycloak.connections.file.InMemoryModel; -import org.keycloak.models.ClientModel; - -import static org.keycloak.models.utils.Pbkdf2PasswordEncoder.getSalt; - -import org.keycloak.models.GroupModel; -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.OTPPolicy; -import org.keycloak.models.UserConsentModel; -import org.keycloak.models.PasswordPolicy; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserCredentialModel; -import org.keycloak.models.UserCredentialValueModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.entities.CredentialEntity; -import org.keycloak.models.entities.FederatedIdentityEntity; -import org.keycloak.models.entities.RoleEntity; -import org.keycloak.models.entities.UserEntity; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.models.utils.Pbkdf2PasswordEncoder; -import org.keycloak.common.util.Time; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * UserModel for JSON persistence. - * - * @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc. - */ -public class UserAdapter implements UserModel, Comparable { - - private final InMemoryModel inMemoryModel; - private final UserEntity user; - private final RealmModel realm; - - private final Set allRoles = new HashSet(); - private final Set allGroups = new HashSet(); - - public UserAdapter(RealmModel realm, UserEntity userEntity, InMemoryModel inMemoryModel) { - this.user = userEntity; - this.realm = realm; - if (userEntity.getFederatedIdentities() == null) { - userEntity.setFederatedIdentities(new ArrayList()); - } - this.inMemoryModel = inMemoryModel; - } - - public UserEntity getUserEntity() { - return this.user; - } - - @Override - public String getId() { - return user.getId(); - } - - @Override - public String getUsername() { - return user.getUsername(); - } - - @Override - public void setUsername(String username) { - username = KeycloakModelUtils.toLowerCaseSafe(username); - - if (getUsername() == null) { - user.setUsername(username); - return; - } - - if (getUsername().equals(username)) return; // allow setting to same name - - if (inMemoryModel.hasUserWithUsername(realm.getId(), username)) - throw new ModelDuplicateException("User with username " + username + " already exists in realm."); - user.setUsername(username); - } - - @Override - public Long getCreatedTimestamp() { - return user.getCreatedTimestamp(); - } - - @Override - public void setCreatedTimestamp(Long timestamp) { - user.setCreatedTimestamp(timestamp); - } - - @Override - public boolean isEnabled() { - return user.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - user.setEnabled(enabled); - } - - @Override - public String getFirstName() { - return user.getFirstName(); - } - - @Override - public void setFirstName(String firstName) { - user.setFirstName(firstName); - } - - @Override - public String getLastName() { - return user.getLastName(); - } - - @Override - public void setLastName(String lastName) { - user.setLastName(lastName); - } - - @Override - public String getEmail() { - return user.getEmail(); - } - - @Override - public void setEmail(String email) { - email = KeycloakModelUtils.toLowerCaseSafe(email); - - if (email == null) { - user.setEmail(email); - return; - } - - if (email.equals(getEmail())) return; - - RealmAdapter realmAdapter = (RealmAdapter)realm; - if (realmAdapter.hasUserWithEmail(email)) throw new ModelDuplicateException("User with email address " + email + " already exists."); - user.setEmail(email); - } - - @Override - public boolean isEmailVerified() { - return user.isEmailVerified(); - } - - @Override - public void setEmailVerified(boolean verified) { - user.setEmailVerified(verified); - } - - @Override - public void setSingleAttribute(String name, String value) { - if (user.getAttributes() == null) { - user.setAttributes(new HashMap>()); - } - - List attrValues = new ArrayList<>(); - attrValues.add(value); - user.getAttributes().put(name, attrValues); - } - - @Override - public void setAttribute(String name, List values) { - if (user.getAttributes() == null) { - user.setAttributes(new HashMap>()); - } - - user.getAttributes().put(name, values); - } - - @Override - public void removeAttribute(String name) { - if (user.getAttributes() == null) return; - - user.getAttributes().remove(name); - } - - @Override - public String getFirstAttribute(String name) { - if (user.getAttributes()==null) return null; - - List attrValues = user.getAttributes().get(name); - return (attrValues==null || attrValues.isEmpty()) ? null : attrValues.get(0); - } - - @Override - public List getAttribute(String name) { - if (user.getAttributes()==null) return Collections.emptyList(); - List attrValues = user.getAttributes().get(name); - return (attrValues == null) ? Collections.emptyList() : Collections.unmodifiableList(attrValues); - } - - @Override - public Map> getAttributes() { - return user.getAttributes()==null ? Collections.>emptyMap() : Collections.unmodifiableMap((Map) user.getAttributes()); - } - - @Override - public Set getRequiredActions() { - List requiredActions = user.getRequiredActions(); - if (requiredActions == null) requiredActions = new ArrayList(); - return new HashSet(requiredActions); - } - - @Override - public void addRequiredAction(RequiredAction action) { - String actionName = action.name(); - addRequiredAction(actionName); - } - - @Override - public void addRequiredAction(String actionName) { - List requiredActions = user.getRequiredActions(); - if (requiredActions == null) requiredActions = new ArrayList<>(); - if (!requiredActions.contains(actionName)) { - requiredActions.add(actionName); - } - user.setRequiredActions(requiredActions); - } - - @Override - public void removeRequiredAction(RequiredAction action) { - String actionName = action.name(); - removeRequiredAction(actionName); - } - - @Override - public void removeRequiredAction(String actionName) { - List requiredActions = user.getRequiredActions(); - if (requiredActions == null) return; - requiredActions.remove(actionName); - user.setRequiredActions(requiredActions); - } - - @Override - public boolean isOtpEnabled() { - return user.isTotp(); - } - - @Override - public void setOtpEnabled(boolean totp) { - user.setTotp(totp); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - updatePasswordCredential(cred); - } else if (UserCredentialModel.isOtp(cred.getType())){ - updateOtpCredential(cred); - - }else { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - credentialEntity.setValue(cred.getValue()); - user.getCredentials().add(credentialEntity); - } else { - credentialEntity.setValue(cred.getValue()); - } - } - } - - private void updateOtpCredential(UserCredentialModel cred) { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - credentialEntity.setValue(cred.getValue()); - OTPPolicy otpPolicy = realm.getOTPPolicy(); - credentialEntity.setAlgorithm(otpPolicy.getAlgorithm()); - credentialEntity.setDigits(otpPolicy.getDigits()); - credentialEntity.setCounter(otpPolicy.getInitialCounter()); - credentialEntity.setPeriod(otpPolicy.getPeriod()); - user.getCredentials().add(credentialEntity); - } else { - credentialEntity.setValue(cred.getValue()); - OTPPolicy policy = realm.getOTPPolicy(); - credentialEntity.setDigits(policy.getDigits()); - credentialEntity.setCounter(policy.getInitialCounter()); - credentialEntity.setAlgorithm(policy.getAlgorithm()); - credentialEntity.setPeriod(policy.getPeriod()); - } - } - - - private void updatePasswordCredential(UserCredentialModel cred) { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - setValue(credentialEntity, cred); - user.getCredentials().add(credentialEntity); - } else { - - int expiredPasswordsPolicyValue = -1; - PasswordPolicy policy = realm.getPasswordPolicy(); - if(policy != null) { - expiredPasswordsPolicyValue = policy.getExpiredPasswords(); - } - - if (expiredPasswordsPolicyValue != -1) { - user.getCredentials().remove(credentialEntity); - credentialEntity.setType(UserCredentialModel.PASSWORD_HISTORY); - user.getCredentials().add(credentialEntity); - - List credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY); - if (credentialEntities.size() > expiredPasswordsPolicyValue - 1) { - user.getCredentials().removeAll(credentialEntities.subList(expiredPasswordsPolicyValue - 1, credentialEntities.size())); - } - - credentialEntity = setCredentials(user, cred); - setValue(credentialEntity, cred); - user.getCredentials().add(credentialEntity); - } else { - List credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY); - if (credentialEntities != null && credentialEntities.size() > 0) { - user.getCredentials().removeAll(credentialEntities); - } - setValue(credentialEntity, cred); - } - } - } - - private CredentialEntity setCredentials(UserEntity user, UserCredentialModel cred) { - CredentialEntity credentialEntity = new CredentialEntity(); - credentialEntity.setType(cred.getType()); - credentialEntity.setDevice(cred.getDevice()); - return credentialEntity; - } - - private void setValue(CredentialEntity credentialEntity, UserCredentialModel cred) { - byte[] salt = getSalt(); - int hashIterations = 1; - PasswordPolicy policy = realm.getPasswordPolicy(); - if (policy != null) { - hashIterations = policy.getHashIterations(); - if (hashIterations == -1) - hashIterations = 1; - } - credentialEntity.setCreatedDate(Time.toMillis(Time.currentTime())); - credentialEntity.setValue(new Pbkdf2PasswordEncoder(salt).encode(cred.getValue(), hashIterations)); - credentialEntity.setSalt(salt); - credentialEntity.setHashIterations(hashIterations); - } - - private CredentialEntity getCredentialEntity(UserEntity userEntity, String credType) { - for (CredentialEntity entity : userEntity.getCredentials()) { - if (entity.getType().equals(credType)) { - return entity; - } - } - - return null; - } - - private List getCredentialEntities(UserEntity userEntity, String credType) { - List credentialEntities = new ArrayList(); - for (CredentialEntity entity : userEntity.getCredentials()) { - if (entity.getType().equals(credType)) { - credentialEntities.add(entity); - } - } - - // Avoiding direct use of credSecond.getCreatedDate() - credFirst.getCreatedDate() to prevent Integer Overflow - // Orders from most recent to least recent - Collections.sort(credentialEntities, new Comparator() { - public int compare(CredentialEntity credFirst, CredentialEntity credSecond) { - if (credFirst.getCreatedDate() > credSecond.getCreatedDate()) { - return -1; - } else if (credFirst.getCreatedDate() < credSecond.getCreatedDate()) { - return 1; - } else { - return 0; - } - } - }); - return credentialEntities; - } - - @Override - public List getCredentialsDirectly() { - List credentials = new ArrayList(user.getCredentials()); - List result = new ArrayList(); - - for (CredentialEntity credEntity : credentials) { - UserCredentialValueModel credModel = new UserCredentialValueModel(); - credModel.setType(credEntity.getType()); - credModel.setDevice(credEntity.getDevice()); - credModel.setCreatedDate(credEntity.getCreatedDate()); - credModel.setValue(credEntity.getValue()); - credModel.setSalt(credEntity.getSalt()); - credModel.setHashIterations(credEntity.getHashIterations()); - if (UserCredentialModel.isOtp(credEntity.getType())) { - credModel.setCounter(credEntity.getCounter()); - if (credEntity.getAlgorithm() == null) { - // for migration where these values would be null - credModel.setAlgorithm(realm.getOTPPolicy().getAlgorithm()); - } else { - credModel.setAlgorithm(credEntity.getAlgorithm()); - } - if (credEntity.getDigits() == 0) { - // for migration where these values would be 0 - credModel.setDigits(realm.getOTPPolicy().getDigits()); - } else { - credModel.setDigits(credEntity.getDigits()); - } - - if (credEntity.getPeriod() == 0) { - // for migration where these values would be 0 - credModel.setPeriod(realm.getOTPPolicy().getPeriod()); - } else { - credModel.setPeriod(credEntity.getPeriod()); - } - } - - result.add(credModel); - } - - return result; - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel credModel) { - CredentialEntity credentialEntity = getCredentialEntity(user, credModel.getType()); - - if (credentialEntity == null) { - credentialEntity = new CredentialEntity(); - // credentialEntity.setId(KeycloakModelUtils.generateId()); - credentialEntity.setType(credModel.getType()); - // credentialEntity.setUser(user); - credModel.setCreatedDate(credModel.getCreatedDate()); - user.getCredentials().add(credentialEntity); - } - - credentialEntity.setValue(credModel.getValue()); - credentialEntity.setSalt(credModel.getSalt()); - credentialEntity.setDevice(credModel.getDevice()); - credentialEntity.setHashIterations(credModel.getHashIterations()); - credentialEntity.setCounter(credModel.getCounter()); - credentialEntity.setAlgorithm(credModel.getAlgorithm()); - credentialEntity.setDigits(credModel.getDigits()); - credentialEntity.setPeriod(credModel.getPeriod()); - } - - @Override - public Set getGroups() { - return Collections.unmodifiableSet(allGroups); - } - - @Override - public void joinGroup(GroupModel group) { - allGroups.add(group); - - } - - @Override - public void leaveGroup(GroupModel group) { - if (user == null || group == null) return; - allGroups.remove(group); - - } - - @Override - public boolean isMemberOf(GroupModel group) { - return KeycloakModelUtils.isMember(getGroups(), group); - } - - @Override - public boolean hasRole(RoleModel role) { - Set roles = getRoleMappings(); - return KeycloakModelUtils.hasRole(roles, role); - } - - @Override - public void grantRole(RoleModel role) { - allRoles.add(role); - } - - @Override - public Set getRoleMappings() { - return Collections.unmodifiableSet(allRoles); - } - - @Override - public Set getRealmRoleMappings() { - Set allRoleMappings = getRoleMappings(); - - // Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user? - Set realmRoles = new HashSet(); - for (RoleModel role : allRoleMappings) { - RoleEntity roleEntity = ((RoleAdapter) role).getRoleEntity(); - - if (realm.getId().equals(roleEntity.getRealmId())) { - realmRoles.add(role); - } - } - return realmRoles; - } - - @Override - public void deleteRoleMapping(RoleModel role) { - if (user == null || role == null) return; - allRoles.remove(role); - } - - @Override - public Set getClientRoleMappings(ClientModel app) { - Set result = new HashSet(); - - for (RoleModel role : allRoles) { - RoleEntity roleEntity = ((RoleAdapter)role).getRoleEntity(); - if (app.getId().equals(roleEntity.getClientId())) { - result.add(new RoleAdapter(realm, roleEntity, app)); - } - } - return result; - } - - @Override - public String getFederationLink() { - return user.getFederationLink(); - } - - @Override - public void setFederationLink(String link) { - user.setFederationLink(link); - } - - @Override - public String getServiceAccountClientLink() { - return user.getServiceAccountClientLink(); - } - - @Override - public void setServiceAccountClientLink(String clientInternalId) { - user.setServiceAccountClientLink(clientInternalId); - } - - @Override - public void addConsent(UserConsentModel consent) { - // TODO - } - - @Override - public UserConsentModel getConsentByClient(String clientId) { - // TODO - return null; - } - - @Override - public List getConsents() { - // TODO - return null; - } - - @Override - public void updateConsent(UserConsentModel consent) { - // TODO - } - - @Override - public boolean revokeConsentForClient(String clientId) { - // TODO - return false; - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || !(o instanceof UserModel)) return false; - - UserModel that = (UserModel) o; - return that.getId().equals(getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - - @Override - public int compareTo(Object user) { - if (this == user) return 0; - return (getUsername().compareTo(((UserModel)user).getUsername())); - } -} diff --git a/model/file/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory b/model/file/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory deleted file mode 100644 index 173ba2d258..0000000000 --- a/model/file/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory +++ /dev/null @@ -1 +0,0 @@ -org.keycloak.models.file.FileRealmProviderFactory \ No newline at end of file diff --git a/model/file/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory b/model/file/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory deleted file mode 100644 index 691ada44ce..0000000000 --- a/model/file/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory +++ /dev/null @@ -1 +0,0 @@ -org.keycloak.models.file.FileUserProviderFactory \ No newline at end of file diff --git a/model/pom.xml b/model/pom.xml index 2f78805ae2..0322abb35b 100755 --- a/model/pom.xml +++ b/model/pom.xml @@ -29,7 +29,6 @@ invalidation-cache jpa mongo - file sessions-infinispan diff --git a/pom.xml b/pom.xml index 85409fe308..15e9f1cf15 100755 --- a/pom.xml +++ b/pom.xml @@ -838,7 +838,7 @@ org.keycloak keycloak-wf9-server-subsystem ${project.version} - + org.keycloak keycloak-subsystem @@ -959,11 +959,6 @@ keycloak-model-api ${project.version} - - org.keycloak - keycloak-model-file - ${project.version} - org.keycloak keycloak-invalidation-cache-infinispan @@ -1441,7 +1436,7 @@ org.wildfly.build wildfly-feature-pack-build-maven-plugin ${wildfly.build-tools.version} - + org.wildfly.build wildfly-server-provisioning-maven-plugin @@ -1462,7 +1457,7 @@ 3.1.1 - +