From 49ac3587b6dcfe705fcd1c78579cbc52643ace7e Mon Sep 17 00:00:00 2001 From: Stian Thorgersen Date: Mon, 6 Feb 2017 20:22:43 +0100 Subject: [PATCH] KEYCLOAK-4384 Remove Mongo support --- dependencies/server-all/pom.xml | 9 - .../content/bin/migrate-domain-clustered.cli | 7 +- .../content/bin/migrate-domain-standalone.cli | 7 +- .../content/bin/migrate-standalone-ha.cli | 7 +- .../content/bin/migrate-standalone.cli | 7 +- .../keycloak-model-mongo/main/module.xml | 41 - .../keycloak-services/main/module.xml | 1 - .../mongodb/mongo-java-driver/main/module.xml | 30 - misc/DatabaseTesting.md | 10 - misc/Testsuite.md | 12 - misc/UpdatingDatabaseSchema.md | 18 +- misc/UpdatingServerConfig.md | 17 +- model/mongo/pom.xml | 75 - .../mongo/adapter/PolicyAdapter.java | 180 -- .../mongo/adapter/ResourceAdapter.java | 106 - .../mongo/adapter/ResourceServerAdapter.java | 73 - .../mongo/adapter/ScopeAdapter.java | 60 - .../mongo/entities/PolicyEntity.java | 166 -- .../mongo/entities/ResourceEntity.java | 142 -- .../mongo/entities/ResourceServerEntity.java | 67 - .../mongo/entities/ScopeEntity.java | 66 - .../store/MongoAuthorizationStoreFactory.java | 52 - .../mongo/store/MongoPolicyStore.java | 201 -- .../mongo/store/MongoResourceServerStore.java | 90 - .../mongo/store/MongoResourceStore.java | 176 -- .../mongo/store/MongoScopeStore.java | 126 -- .../mongo/store/MongoStoreFactory.java | 71 - ...DefaultMongoConnectionFactoryProvider.java | 354 --- .../mongo/DefaultMongoConnectionProvider.java | 58 - .../mongo/MongoConnectionProvider.java | 39 - .../mongo/MongoConnectionProviderFactory.java | 33 - .../connections/mongo/MongoConnectionSpi.java | 49 - .../mongo/MongoKeycloakTransaction.java | 85 - .../mongo/api/MongoCollection.java | 38 - .../connections/mongo/api/MongoEntity.java | 26 - .../connections/mongo/api/MongoField.java | 37 - .../mongo/api/MongoIdentifiableEntity.java | 38 - .../connections/mongo/api/MongoStore.java | 96 - .../context/MongoStoreInvocationContext.java | 51 - .../mongo/api/context/MongoTask.java | 28 - .../connections/mongo/api/types/Mapper.java | 39 - .../mongo/api/types/MapperContext.java | 54 - .../mongo/api/types/MapperRegistry.java | 136 -- .../connections/mongo/impl/EntityInfo.java | 57 - .../mongo/impl/MongoStoreImpl.java | 491 ----- .../SimpleMongoStoreInvocationContext.java | 85 - ...ransactionMongoStoreInvocationContext.java | 171 -- .../mongo/impl/types/BasicDBListMapper.java | 61 - .../impl/types/BasicDBListToSetMapper.java | 61 - .../mongo/impl/types/BasicDBObjectMapper.java | 137 -- .../impl/types/BasicDBObjectToMapMapper.java | 94 - .../mongo/impl/types/EnumToStringMapper.java | 44 - .../mongo/impl/types/ListMapper.java | 62 - .../mongo/impl/types/MapMapper.java | 79 - .../mongo/impl/types/MongoEntityMapper.java | 80 - .../mongo/impl/types/SimpleMapper.java | 51 - .../mongo/impl/types/StringToEnumMapper.java | 45 - .../mongo/lock/MongoDBLockProvider.java | 149 -- .../lock/MongoDBLockProviderFactory.java | 98 - .../mongo/updater/MongoUpdaterProvider.java | 33 - .../updater/MongoUpdaterProviderFactory.java | 26 - .../mongo/updater/MongoUpdaterSpi.java | 49 - .../impl/DefaultMongoUpdaterProvider.java | 178 -- .../DefaultMongoUpdaterProviderFactory.java | 53 - .../AbstractMigrateUserFedToComponent.java | 167 -- .../mongo/updater/impl/updates/Update.java | 88 - .../impl/updates/Update1_0_0_Final.java | 62 - .../impl/updates/Update1_1_0_Beta1.java | 61 - .../impl/updates/Update1_2_0_Beta1.java | 297 --- .../updater/impl/updates/Update1_2_0_CR1.java | 81 - .../updater/impl/updates/Update1_3_0.java | 76 - .../updater/impl/updates/Update1_4_0.java | 79 - .../updater/impl/updates/Update1_7_0.java | 56 - .../updater/impl/updates/Update1_8_0.java | 61 - .../updater/impl/updates/Update1_9_2.java | 62 - .../updater/impl/updates/Update2_3_0.java | 80 - .../updater/impl/updates/Update2_4_0.java | 53 - .../updater/impl/updates/Update2_5_0.java | 57 - .../events/mongo/MongoAdminEventQuery.java | 149 -- .../events/mongo/MongoEventQuery.java | 126 -- .../events/mongo/MongoEventStoreProvider.java | 204 -- .../mongo/MongoEventStoreProviderFactory.java | 70 - .../adapters/AbstractMongoAdapter.java | 61 - .../keycloak/adapters/ClientAdapter.java | 770 ------- .../adapters/ClientTemplateAdapter.java | 417 ---- .../mongo/keycloak/adapters/GroupAdapter.java | 267 --- .../adapters/MigrationModelAdapter.java | 55 - .../keycloak/adapters/MongoRealmProvider.java | 473 ---- .../adapters/MongoRealmProviderFactory.java | 62 - .../keycloak/adapters/MongoUserProvider.java | 864 -------- .../adapters/MongoUserProviderFactory.java | 61 - .../MongoUserSessionPersisterProvider.java | 335 --- ...goUserSessionPersisterProviderFactory.java | 54 - .../mongo/keycloak/adapters/RealmAdapter.java | 1931 ----------------- .../mongo/keycloak/adapters/RoleAdapter.java | 201 -- .../mongo/keycloak/adapters/UserAdapter.java | 357 --- .../entities/AbstractIdentifiableEntity.java | 62 - .../AuthenticationExecutionEntity.java | 100 - .../entities/AuthenticationFlowEntity.java | 82 - .../entities/AuthenticatorConfigEntity.java | 45 - .../mongo/keycloak/entities/ClientEntity.java | 357 --- .../ClientIdentityProviderMappingEntity.java | 34 - .../entities/ClientTemplateEntity.java | 175 -- .../keycloak/entities/ComponentEntity.java | 84 - .../keycloak/entities/CredentialEntity.java | 139 -- .../entities/FederatedIdentityEntity.java | 88 - .../mongo/keycloak/entities/GroupEntity.java | 75 - .../entities/IdentityProviderEntity.java | 162 -- .../IdentityProviderMapperEntity.java | 63 - .../keycloak/entities/MongoClientEntity.java | 40 - .../entities/MongoClientTemplateEntity.java | 34 - .../keycloak/entities/MongoGroupEntity.java | 32 - .../entities/MongoMigrationModelEntity.java | 57 - .../MongoOfflineUserSessionEntity.java | 27 - .../MongoOnlineUserSessionEntity.java | 27 - .../keycloak/entities/MongoRealmEntity.java | 54 - .../keycloak/entities/MongoRoleEntity.java | 98 - .../entities/MongoUserConsentEntity.java | 33 - .../keycloak/entities/MongoUserEntity.java | 41 - .../entities/MongoUserSessionEntity.java | 31 - .../PersistentClientSessionEntity.java | 61 - .../entities/PersistentUserSessionEntity.java | 72 - .../entities/ProtocolMapperEntity.java | 81 - .../mongo/keycloak/entities/RealmEntity.java | 687 ------ .../RequiredActionProviderEntity.java | 81 - .../entities/RequiredCredentialEntity.java | 61 - .../mongo/keycloak/entities/RoleEntity.java | 84 - .../keycloak/entities/UserConsentEntity.java | 82 - .../mongo/keycloak/entities/UserEntity.java | 193 -- .../entities/UserFederationMapperEntity.java | 63 - .../UserFederationProviderEntity.java | 91 - .../models/mongo/utils/MongoModelUtils.java | 91 - .../MongoUserFederatedStorageProvider.java | 617 ------ ...goUserFederatedStorageProviderFactory.java | 57 - .../storage/mongo/entity/FederatedUser.java | 124 -- ...horization.store.AuthorizationStoreFactory | 37 - ...tions.mongo.MongoConnectionProviderFactory | 18 - ....mongo.updater.MongoUpdaterProviderFactory | 18 - ....keycloak.events.EventStoreProviderFactory | 18 - .../org.keycloak.models.RealmProviderFactory | 18 - .../org.keycloak.models.UserProviderFactory | 18 - ...ycloak.models.dblock.DBLockProviderFactory | 35 - ...ession.UserSessionPersisterProviderFactory | 18 - .../services/org.keycloak.provider.Spi | 19 - ...erated.UserFederatedStorageProviderFactory | 1 - model/pom.xml | 1 - pom.xml | 17 - .../resources/META-INF/keycloak-server.json | 10 - .../base/src/test/resources/log4j.properties | 1 - .../src/test/resources/log4j.properties | 1 - testsuite/integration/pom.xml | 125 -- .../ldap/LDAPBinaryAttributesTest.java | 6 +- .../resources/META-INF/keycloak-server.json | 10 - .../src/test/resources/log4j.properties | 1 - testsuite/jetty/jetty81/pom.xml | 79 - testsuite/jetty/jetty91/pom.xml | 79 - testsuite/jetty/jetty92/pom.xml | 79 - testsuite/jetty/jetty93/pom.xml | 79 - testsuite/proxy/pom.xml | 79 - testsuite/tomcat6/pom.xml | 79 - testsuite/tomcat7/pom.xml | 79 - testsuite/tomcat8/pom.xml | 79 - .../default-server-subsys-config.properties | 16 - .../cli/default-keycloak-subsys-config.cli | 6 +- 164 files changed, 16 insertions(+), 18214 deletions(-) delete mode 100755 distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-model-mongo/main/module.xml delete mode 100644 distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/mongodb/mongo-java-driver/main/module.xml delete mode 100755 model/mongo/pom.xml delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/PolicyAdapter.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceAdapter.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceServerAdapter.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ScopeAdapter.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/PolicyEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceServerEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ScopeEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoAuthorizationStoreFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoPolicyStore.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceServerStore.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceStore.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoScopeStore.java delete mode 100644 model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoStoreFactory.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionFactoryProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionSpi.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/MongoKeycloakTransaction.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoCollection.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoField.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoIdentifiableEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoStore.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoStoreInvocationContext.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoTask.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/Mapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperContext.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperRegistry.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/MongoStoreImpl.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/SimpleMongoStoreInvocationContext.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/TransactionMongoStoreInvocationContext.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListToSetMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectToMapMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/EnumToStringMapper.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/ListMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MapMapper.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MongoEntityMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/SimpleMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/StringToEnumMapper.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterSpi.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProvider.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/AbstractMigrateUserFedToComponent.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_0_0_Final.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_1_0_Beta1.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_Beta1.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_CR1.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_3_0.java delete mode 100755 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_4_0.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_7_0.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_8_0.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_9_2.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_3_0.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_4_0.java delete mode 100644 model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_5_0.java delete mode 100755 model/mongo/src/main/java/org/keycloak/events/mongo/MongoAdminEventQuery.java delete mode 100755 model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventQuery.java delete mode 100755 model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProvider.java delete mode 100755 model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/AbstractMongoAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientTemplateAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProviderFactory.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProviderFactory.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RoleAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AbstractIdentifiableEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationExecutionEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationFlowEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticatorConfigEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientIdentityProviderMappingEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientTemplateEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ComponentEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/CredentialEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/FederatedIdentityEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/GroupEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderMapperEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientTemplateEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoMigrationModelEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOfflineUserSessionEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOnlineUserSessionEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRealmEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRoleEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserConsentEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserSessionEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentClientSessionEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentUserSessionEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ProtocolMapperEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RealmEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredActionProviderEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredCredentialEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RoleEntity.java delete mode 100644 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserConsentEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationMapperEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationProviderEntity.java delete mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java delete mode 100644 model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProvider.java delete mode 100644 model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProviderFactory.java delete mode 100644 model/mongo/src/main/java/org/keycloak/storage/mongo/entity/FederatedUser.java delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.authorization.store.AuthorizationStoreFactory delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.MongoConnectionProviderFactory delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.updater.MongoUpdaterProviderFactory delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.events.EventStoreProviderFactory delete mode 100755 model/mongo/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory delete mode 100755 model/mongo/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.models.dblock.DBLockProviderFactory delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.models.session.UserSessionPersisterProviderFactory delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.provider.Spi delete mode 100644 model/mongo/src/main/resources/META-INF/services/org.keycloak.storage.federated.UserFederatedStorageProviderFactory diff --git a/dependencies/server-all/pom.xml b/dependencies/server-all/pom.xml index fa143126f5c..fd6bb0012ef 100755 --- a/dependencies/server-all/pom.xml +++ b/dependencies/server-all/pom.xml @@ -85,15 +85,6 @@ org.keycloak keycloak-saml-core - - - org.keycloak - keycloak-model-mongo - - - org.mongodb - mongo-java-driver - org.liquibase diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-clustered.cli b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-clustered.cli index d11e2b9f253..ac7251e9075 100644 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-clustered.cli +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-clustered.cli @@ -51,12 +51,7 @@ if (result == []) of /profile=$clusteredProfile/subsystem=keycloak-server/:read- echo end-if -# Find if we are using jpa or mongo -if (result == mongo) of /profile=$clusteredProfile/subsystem=keycloak-server/spi=realm/:read-attribute(name=default-provider) - set persistenceProvider=mongo -else - set persistenceProvider=jpa -end-if +set persistenceProvider=jpa # Migrate from 2.1.0 to 2.2.0 if (outcome == failed) of /profile=$clusteredProfile/subsystem=infinispan/cache-container=keycloak/distributed-cache=authorization/:read-resource diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-standalone.cli b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-standalone.cli index b24819e3b0b..486532d4a25 100644 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-standalone.cli +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-domain-standalone.cli @@ -63,12 +63,7 @@ if (result == []) of /profile=$standaloneProfile/subsystem=keycloak-server/:read echo end-if -# Find if we are using jpa or mongo -if (result == mongo) of /profile=$standaloneProfile/subsystem=keycloak-server/spi=realm/:read-attribute(name=default-provider) - set persistenceProvider=mongo -else - set persistenceProvider=jpa -end-if +set persistenceProvider=jpa # Migrate from 2.1.0 to 2.2.0 if (result == update) of /profile=$standaloneProfile/subsystem=keycloak-server/spi=connectionsJpa/provider=default/:map-get(name=properties,key=databaseSchema) diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone-ha.cli b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone-ha.cli index 7b5dcc73527..9bccbd0a56a 100644 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone-ha.cli +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone-ha.cli @@ -42,12 +42,7 @@ if (result == []) of /subsystem=keycloak-server/:read-children-names(child-type= echo end-if -# Find if we are using jpa or mongo -if (result == mongo) of /subsystem=keycloak-server/spi=realm/:read-attribute(name=default-provider) - set persistenceProvider=mongo -else - set persistenceProvider=jpa -end-if +set persistenceProvider=jpa # Migrate from 2.1.0 to 2.2.0 if (outcome == failed) of /extension=org.jboss.as.deployment-scanner/:read-resource diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone.cli b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone.cli index 3398f171b38..e6d859d60c8 100644 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone.cli +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/content/bin/migrate-standalone.cli @@ -55,12 +55,7 @@ if (result == []) of /subsystem=keycloak-server/:read-children-names(child-type= echo end-if -# Find if we are using jpa or mongo -if (result == mongo) of /subsystem=keycloak-server/spi=realm/:read-attribute(name=default-provider) - set persistenceProvider=mongo -else - set persistenceProvider=jpa -end-if +set persistenceProvider=jpa # Migrate from 2.1.0 to 2.2.0 if (outcome == failed) of /extension=org.jboss.as.deployment-scanner/:read-resource diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-model-mongo/main/module.xml b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-model-mongo/main/module.xml deleted file mode 100755 index 3bd99ae4665..00000000000 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-model-mongo/main/module.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-services/main/module.xml b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-services/main/module.xml index cd71511382d..35288c6b2b0 100755 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-services/main/module.xml +++ b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/keycloak/keycloak-services/main/module.xml @@ -34,7 +34,6 @@ - diff --git a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/mongodb/mongo-java-driver/main/module.xml b/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/mongodb/mongo-java-driver/main/module.xml deleted file mode 100644 index 94f4d24dffd..00000000000 --- a/distribution/feature-packs/server-feature-pack/src/main/resources/modules/system/layers/keycloak/org/mongodb/mongo-java-driver/main/module.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/misc/DatabaseTesting.md b/misc/DatabaseTesting.md index 02eb365246c..96d130e8839 100644 --- a/misc/DatabaseTesting.md +++ b/misc/DatabaseTesting.md @@ -1,16 +1,6 @@ Test with various databases =========================== -MongoDB -------- - -The Keycloak testsuite uses an embedded MongoDB when running tests so you don't have to have one running locally. - -Run tests: - - mvn install -Pmongo - - MySQL ----- diff --git a/misc/Testsuite.md b/misc/Testsuite.md index 9b99036d6ce..84038064709 100644 --- a/misc/Testsuite.md +++ b/misc/Testsuite.md @@ -45,18 +45,6 @@ For example to use the example themes run the server with: **NOTE:** If `keycloak.theme.dir` is specified the default themes (base, rcue and keycloak) are loaded from the classpath -### Run server with Mongo model - -To start a Keycloak server with identity model data persisted in Mongo database instead of default JPA/H2 you can run: - - mvn exec:java -Pkeycloak-server -Dkeycloak.realm.provider=mongo -Dkeycloak.user.provider=mongo -Dkeycloak.audit.provider=mongo - -By default it's using database `keycloak` on localhost/27017 and it uses already existing data from this DB (no cleanup of existing data during bootstrap). Assumption is that you already have DB running on localhost/27017 . Use system properties to configure things differently: - - mvn exec:java -Pkeycloak-server -Dkeycloak.realm.provider=mongo -Dkeycloak.user.provider=mongo -Dkeycloak.eventStore.provider=mongo -Dkeycloak.connectionsMongo.host=localhost -Dkeycloak.connectionsMongo.port=27017 -Dkeycloak.connectionsMongo.db=keycloak -Dkeycloak.connectionsMongo.clearOnStartup=false - -Note that if you are using Mongo model, it would mean that Mongo will be used for audit as well. You may need to use audit related properties for configuration of Mongo if you want to override default ones (For example keycloak.audit.mongo.host, keycloak.audit.mongo.port etc) - TOTP codes ---------- diff --git a/misc/UpdatingDatabaseSchema.md b/misc/UpdatingDatabaseSchema.md index d0277a02619..363d1099f5b 100644 --- a/misc/UpdatingDatabaseSchema.md +++ b/misc/UpdatingDatabaseSchema.md @@ -2,7 +2,7 @@ Updating Database Schema ======================== Keycloak supports automatically migrating the database to a new version. This is done by applying one or more change-sets -to the existing database. This means if you need to do any changes to database schemas for JPA or Mongo you need to create +to the existing database. This means if you need to do any changes to database schemas you need to create a change-set that can transform the schema as well as any existing data. This includes changes to: @@ -13,7 +13,7 @@ This includes changes to: * Event entities -Creating a JPA change-set +Creating a change-set ------------------------- We use Liquibase to support updating the database. The change-sets are located in @@ -57,20 +57,6 @@ Once the server has started fully, stop it and run: mvn -f testsuite/integration exec:java -Pkeycloak-server -Dkeycloak.connectionsJpa.url='jdbc:h2:keycloak' -Dkeycloak.connectionsJpa.databaseSchema='development-validate' -Creating a Mongo change-set ---------------------------- - -As Mongo is schema-less it's significantly easier to create a change-set. You only need to create/delete collections as -needed, as well as update any indexes. You will also need to update existing data if required. - -Mongo change-sets are written in Java and are located in the `connections/mongo` module, to add a new change-set create -a new class that implements `org.keycloak.connections.mongo.updater.updates.Update` the name of the class should be -`Update` with `.` replaced with `_`. - -You also need to add a reference to this file in `org.keycloak.connections.mongo.updater.DefaultMongoUpdaterProvider`. -It should be added last to the `DefaultMongoUpdaterProvider#updates` array. - - Testing database migration -------------------------- diff --git a/misc/UpdatingServerConfig.md b/misc/UpdatingServerConfig.md index a3282af9960..37f5af55e0a 100644 --- a/misc/UpdatingServerConfig.md +++ b/misc/UpdatingServerConfig.md @@ -20,23 +20,22 @@ The changes you will likely make are when you need to add a new SPI, change an e All elements in an SPI declaration are optional, but a full SPI declaration looks like this: ````xml - - mongo - + + myprovider + - + - + - - + ```` -Here we have two providers defined for the SPI `dblock`. The -`default-provider` is listed as `mongo`. However it is up to the SPI to decide how it will +Here we have two providers defined for the SPI `example`. The +`default-provider` is listed as `myprovider`. However it is up to the SPI to decide how it will treat this setting. Some SPIs allow more than one provider and some do not. So `default-provider` can help the SPI to choose. diff --git a/model/mongo/pom.xml b/model/mongo/pom.xml deleted file mode 100755 index bf5b9a83095..00000000000 --- a/model/mongo/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - keycloak-parent - org.keycloak - 3.0.0.CR1-SNAPSHOT - ../../pom.xml - - 4.0.0 - - keycloak-model-mongo - Keycloak Model Mongo - - - - 1.8 - 1.8 - - - - - org.bouncycastle - bcprov-jdk15on - provided - - - org.keycloak - keycloak-core - provided - - - org.keycloak - keycloak-server-spi - - - org.keycloak - keycloak-server-spi-private - provided - - - org.keycloak - keycloak-services - provided - - - org.jboss.logging - jboss-logging - provided - - - org.mongodb - mongo-java-driver - provided - - - \ No newline at end of file diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/PolicyAdapter.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/PolicyAdapter.java deleted file mode 100644 index 928bba9bbae..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/PolicyAdapter.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.authorization.mongo.adapter; - -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.Policy; -import org.keycloak.authorization.model.Resource; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.model.Scope; -import org.keycloak.authorization.mongo.entities.PolicyEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.adapters.AbstractMongoAdapter; -import org.keycloak.representations.idm.authorization.DecisionStrategy; -import org.keycloak.representations.idm.authorization.Logic; - -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * @author Pedro Igor - */ -public class PolicyAdapter extends AbstractMongoAdapter implements Policy { - - private final PolicyEntity entity; - private final AuthorizationProvider authorizationProvider; - - public PolicyAdapter(PolicyEntity entity, MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - super(invocationContext); - this.entity = entity; - this.authorizationProvider = authorizationProvider; - } - - @Override - protected PolicyEntity getMongoEntity() { - return entity; - } - - @Override - public String getId() { - return getMongoEntity().getId(); - } - - @Override - public String getType() { - return getMongoEntity().getType(); - } - - @Override - public DecisionStrategy getDecisionStrategy() { - return getMongoEntity().getDecisionStrategy(); - } - - @Override - public void setDecisionStrategy(DecisionStrategy decisionStrategy) { - getMongoEntity().setDecisionStrategy(decisionStrategy); - updateMongoEntity(); - } - - @Override - public Logic getLogic() { - return getMongoEntity().getLogic(); - } - - @Override - public void setLogic(Logic logic) { - getMongoEntity().setLogic(logic); - updateMongoEntity(); - } - - @Override - public Map getConfig() { - return getMongoEntity().getConfig(); - } - - @Override - public void setConfig(Map config) { - getMongoEntity().setConfig(config); - updateMongoEntity(); - } - - @Override - public String getName() { - return getMongoEntity().getName(); - } - - @Override - public void setName(String name) { - getMongoEntity().setName(name); - updateMongoEntity(); - } - - @Override - public String getDescription() { - return getMongoEntity().getDescription(); - } - - @Override - public void setDescription(String description) { - getMongoEntity().setDescription(description); - updateMongoEntity(); - } - - @Override - public ResourceServer getResourceServer() { - return this.authorizationProvider.getStoreFactory().getResourceServerStore().findById(getMongoEntity().getResourceServerId()); - } - - @Override - public Set getAssociatedPolicies() { - return getMongoEntity().getAssociatedPolicies().stream() - .map((Function) id -> authorizationProvider.getStoreFactory().getPolicyStore().findById(id, getMongoEntity().getResourceServerId())) - .collect(Collectors.toSet()); - } - - @Override - public Set getResources() { - return getMongoEntity().getResources().stream() - .map((Function) id -> authorizationProvider.getStoreFactory().getResourceStore().findById(id, getMongoEntity().getResourceServerId())) - .collect(Collectors.toSet()); - } - - @Override - public Set getScopes() { - return getMongoEntity().getScopes().stream() - .map((Function) id -> authorizationProvider.getStoreFactory().getScopeStore().findById(id, getMongoEntity().getResourceServerId())) - .collect(Collectors.toSet()); - } - - @Override - public void addScope(Scope scope) { - getMongoEntity().addScope(scope.getId()); - updateMongoEntity(); - } - - @Override - public void removeScope(Scope scope) { - getMongoEntity().removeScope(scope.getId()); - updateMongoEntity(); - } - - @Override - public void addAssociatedPolicy(Policy associatedPolicy) { - getMongoEntity().addAssociatedPolicy(associatedPolicy.getId()); - updateMongoEntity(); - } - - @Override - public void removeAssociatedPolicy(Policy associatedPolicy) { - getMongoEntity().removeAssociatedPolicy(associatedPolicy.getId()); - updateMongoEntity(); - } - - @Override - public void addResource(Resource resource) { - getMongoEntity().addResource(resource.getId()); - updateMongoEntity(); - } - - @Override - public void removeResource(Resource resource) { - getMongoEntity().removeResource(resource.getId()); - updateMongoEntity(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceAdapter.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceAdapter.java deleted file mode 100644 index 8138a2479d5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceAdapter.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.keycloak.authorization.mongo.adapter; - -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.Resource; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.model.Scope; -import org.keycloak.authorization.mongo.entities.ResourceEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.adapters.AbstractMongoAdapter; - -import java.util.List; -import java.util.Set; - -import static java.util.stream.Collectors.toList; - -/** - * @author Pedro Igor - */ -public class ResourceAdapter extends AbstractMongoAdapter implements Resource { - - private final ResourceEntity entity; - private final AuthorizationProvider authorizationProvider; - - public ResourceAdapter(ResourceEntity entity, MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - super(invocationContext); - this.entity = entity; - this.authorizationProvider = authorizationProvider; - } - - @Override - public String getId() { - return getMongoEntity().getId(); - } - - @Override - public String getName() { - return getMongoEntity().getName(); - } - - @Override - public void setName(String name) { - getMongoEntity().setName(name); - updateMongoEntity(); - } - - @Override - public String getUri() { - return getMongoEntity().getUri(); - } - - @Override - public void setUri(String uri) { - getMongoEntity().setUri(uri); - updateMongoEntity(); - } - - @Override - public String getType() { - return getMongoEntity().getType(); - } - - @Override - public void setType(String type) { - getMongoEntity().setType(type); - updateMongoEntity(); - } - - @Override - public List getScopes() { - return getMongoEntity().getScopes().stream() - .map(id -> authorizationProvider.getStoreFactory().getScopeStore().findById(id, getResourceServer().getId())) - .collect(toList()); - } - - @Override - public String getIconUri() { - return getMongoEntity().getIconUri(); - } - - @Override - public void setIconUri(String iconUri) { - getMongoEntity().setIconUri(iconUri); - updateMongoEntity(); - } - - @Override - public ResourceServer getResourceServer() { - return this.authorizationProvider.getStoreFactory().getResourceServerStore().findById(getMongoEntity().getResourceServerId()); - } - - @Override - public String getOwner() { - return getMongoEntity().getOwner(); - } - - @Override - public void updateScopes(Set scopes) { - getMongoEntity().updateScopes(scopes); - updateMongoEntity(); - } - - @Override - protected ResourceEntity getMongoEntity() { - return this.entity; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceServerAdapter.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceServerAdapter.java deleted file mode 100644 index 1bfbf3f8db8..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ResourceServerAdapter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.authorization.mongo.adapter; - -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.mongo.entities.ResourceServerEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.adapters.AbstractMongoAdapter; -import org.keycloak.representations.idm.authorization.PolicyEnforcementMode; - -/** - * @author Pedro Igor - */ -public class ResourceServerAdapter extends AbstractMongoAdapter implements ResourceServer{ - - private final ResourceServerEntity entity; - - public ResourceServerAdapter(ResourceServerEntity entity, MongoStoreInvocationContext invocationContext) { - super(invocationContext); - this.entity = entity; - } - - @Override - public String getId() { - return getMongoEntity().getId(); - } - - @Override - public String getClientId() { - return getMongoEntity().getClientId(); - } - - @Override - public boolean isAllowRemoteResourceManagement() { - return getMongoEntity().isAllowRemoteResourceManagement(); - } - - @Override - public void setAllowRemoteResourceManagement(boolean allowRemoteResourceManagement) { - getMongoEntity().setAllowRemoteResourceManagement(allowRemoteResourceManagement); - updateMongoEntity(); - } - - @Override - public PolicyEnforcementMode getPolicyEnforcementMode() { - return getMongoEntity().getPolicyEnforcementMode(); - } - - @Override - public void setPolicyEnforcementMode(PolicyEnforcementMode enforcementMode) { - getMongoEntity().setPolicyEnforcementMode(enforcementMode); - updateMongoEntity(); - } - - @Override - protected ResourceServerEntity getMongoEntity() { - return this.entity; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ScopeAdapter.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ScopeAdapter.java deleted file mode 100644 index 72196ca152d..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/adapter/ScopeAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.keycloak.authorization.mongo.adapter; - -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.model.Scope; -import org.keycloak.authorization.mongo.entities.ScopeEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.adapters.AbstractMongoAdapter; - -/** - * @author Pedro Igor - */ -public class ScopeAdapter extends AbstractMongoAdapter implements Scope { - - private final ScopeEntity entity; - private final AuthorizationProvider authorizationProvider; - - public ScopeAdapter(ScopeEntity entity, MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - super(invocationContext); - this.entity = entity; - this.authorizationProvider = authorizationProvider; - } - - @Override - public String getId() { - return getMongoEntity().getId(); - } - - @Override - public String getName() { - return getMongoEntity().getName(); - } - - @Override - public void setName(String name) { - getMongoEntity().setName(name); - updateMongoEntity(); - } - - @Override - public String getIconUri() { - return getMongoEntity().getIconUri(); - } - - @Override - public void setIconUri(String iconUri) { - getMongoEntity().setIconUri(iconUri); - updateMongoEntity(); - } - - @Override - public ResourceServer getResourceServer() { - return this.authorizationProvider.getStoreFactory().getResourceServerStore().findById(getMongoEntity().getResourceServerId()); - } - - @Override - protected ScopeEntity getMongoEntity() { - return this.entity; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/PolicyEntity.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/PolicyEntity.java deleted file mode 100644 index 047961b5114..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/PolicyEntity.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.entities.AbstractIdentifiableEntity; -import org.keycloak.representations.idm.authorization.DecisionStrategy; -import org.keycloak.representations.idm.authorization.Logic; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * @author Pedro Igor - */ -@MongoCollection(collectionName = "policies") -public class PolicyEntity extends AbstractIdentifiableEntity implements MongoIdentifiableEntity { - - private String name; - - private String description; - - private String type; - - private DecisionStrategy decisionStrategy = DecisionStrategy.UNANIMOUS; - - private Logic logic = Logic.POSITIVE; - - private Map config = new HashMap(); - - private String resourceServerId; - - private Set associatedPolicies = new HashSet<>(); - - private Set resources = new HashSet<>(); - - private Set scopes = new HashSet<>(); - - public String getType() { - return this.type; - } - - public void setType(String type) { - this.type = type; - } - - public DecisionStrategy getDecisionStrategy() { - return this.decisionStrategy; - } - - public void setDecisionStrategy(DecisionStrategy decisionStrategy) { - this.decisionStrategy = decisionStrategy; - } - - public Logic getLogic() { - return this.logic; - } - - public void setLogic(Logic logic) { - this.logic = logic; - } - - public Map getConfig() { - return this.config; - } - - public void setConfig(Map config) { - this.config = config; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getResourceServerId() { - return this.resourceServerId; - } - - public void setResourceServerId(String resourceServerId) { - this.resourceServerId = resourceServerId; - } - - public Set getAssociatedPolicies() { - return this.associatedPolicies; - } - - public void setAssociatedPolicies(Set associatedPolicies) { - this.associatedPolicies = associatedPolicies; - } - - public Set getResources() { - return this.resources; - } - - public void setResources(Set resources) { - this.resources = resources; - } - - public Set getScopes() { - return this.scopes; - } - - public void setScopes(Set scopes) { - this.scopes = scopes; - } - - public void addScope(String scopeId) { - getScopes().add(scopeId); - } - - public void removeScope(String scopeId) { - getScopes().remove(scopeId); - } - - public void addAssociatedPolicy(String policyId) { - getAssociatedPolicies().add(policyId); - } - - public void removeAssociatedPolicy(String policyId) { - getAssociatedPolicies().remove(policyId); - } - - public void addResource(String resourceId) { - getResources().add(resourceId); - } - - public void removeResource(String resourceId) { - getResources().remove(resourceId); - } - - public void afterRemove(MongoStoreInvocationContext invocationContext) { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceEntity.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceEntity.java deleted file mode 100644 index 9f63eca3c94..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceEntity.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.entities; - -import org.keycloak.authorization.model.Scope; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.entities.AbstractIdentifiableEntity; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author Pedro Igor - */ -@MongoCollection(collectionName = "resources") -public class ResourceEntity extends AbstractIdentifiableEntity implements MongoIdentifiableEntity { - - private String name; - - private String uri; - - private String type; - - private String iconUri; - - private String owner; - - private String resourceServerId; - - private List scopes = new ArrayList<>(); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public List getScopes() { - return this.scopes; - } - - public void setScopes(List scopes) { - this.scopes = scopes; - } - - public String getIconUri() { - return iconUri; - } - - public void setIconUri(String iconUri) { - this.iconUri = iconUri; - } - - public String getResourceServerId() { - return resourceServerId; - } - - public void setResourceServerId(String resourceServerId) { - this.resourceServerId = resourceServerId; - } - - public String getOwner() { - return this.owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public void updateScopes(Set toUpdate) { - for (Scope scope : toUpdate) { - boolean hasScope = false; - - for (String existingScope : this.scopes) { - if (existingScope.equals(scope.getId())) { - hasScope = true; - } - } - - if (!hasScope) { - this.scopes.add(scope.getId()); - } - } - - for (String scopeId : new HashSet(this.scopes)) { - boolean hasScope = false; - - for (Scope scope : toUpdate) { - if (scopeId.equals(scope.getId())) { - hasScope = true; - } - } - - if (!hasScope) { - this.scopes.remove(scopeId); - } - } - } - - @Override - public void afterRemove(MongoStoreInvocationContext invocationContext) { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceServerEntity.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceServerEntity.java deleted file mode 100644 index 89aadf29bb0..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ResourceServerEntity.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.entities.AbstractIdentifiableEntity; -import org.keycloak.representations.idm.authorization.PolicyEnforcementMode; - -/** - * @author Pedro Igor - */ -@MongoCollection(collectionName = "resource-servers") -public class ResourceServerEntity extends AbstractIdentifiableEntity implements MongoIdentifiableEntity { - - private String clientId; - - private boolean allowRemoteResourceManagement; - - private PolicyEnforcementMode policyEnforcementMode = PolicyEnforcementMode.ENFORCING; - - public String getClientId() { - return this.clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public boolean isAllowRemoteResourceManagement() { - return this.allowRemoteResourceManagement; - } - - public void setAllowRemoteResourceManagement(boolean allowRemoteResourceManagement) { - this.allowRemoteResourceManagement = allowRemoteResourceManagement; - } - - public PolicyEnforcementMode getPolicyEnforcementMode() { - return this.policyEnforcementMode; - } - - public void setPolicyEnforcementMode(PolicyEnforcementMode policyEnforcementMode) { - this.policyEnforcementMode = policyEnforcementMode; - } - - @Override - public void afterRemove(MongoStoreInvocationContext invocationContext) { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ScopeEntity.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ScopeEntity.java deleted file mode 100644 index 537248cb0f7..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/entities/ScopeEntity.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.entities.AbstractIdentifiableEntity; - -/** - * @author Pedro Igor - */ -@MongoCollection(collectionName = "scopes") -public class ScopeEntity extends AbstractIdentifiableEntity implements MongoIdentifiableEntity { - - private String name; - - private String iconUri; - - private String resourceServerId; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getIconUri() { - return iconUri; - } - - public void setIconUri(String iconUri) { - this.iconUri = iconUri; - } - - public String getResourceServerId() { - return resourceServerId; - } - - public void setResourceServerId(String resourceServerId) { - this.resourceServerId = resourceServerId; - } - - @Override - public void afterRemove(MongoStoreInvocationContext invocationContext) { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoAuthorizationStoreFactory.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoAuthorizationStoreFactory.java deleted file mode 100644 index df4cfc9bd33..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoAuthorizationStoreFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.store; - -import org.keycloak.Config; -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.store.AuthorizationStoreFactory; -import org.keycloak.authorization.store.StoreFactory; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.models.KeycloakSession; - -/** - * @author Pedro Igor - */ -public class MongoAuthorizationStoreFactory implements AuthorizationStoreFactory { - @Override - public StoreFactory create(KeycloakSession session) { - MongoConnectionProvider connection = session.getProvider(MongoConnectionProvider.class); - return new MongoStoreFactory(connection.getInvocationContext(), session); - } - - @Override - public void init(Config.Scope config) { - - } - - @Override - public void close() { - - } - - @Override - public String getId() { - return "mongo"; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoPolicyStore.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoPolicyStore.java deleted file mode 100644 index c7227f699a5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoPolicyStore.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.store; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.Policy; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.mongo.adapter.PolicyAdapter; -import org.keycloak.authorization.mongo.entities.PolicyEntity; -import org.keycloak.authorization.store.PolicyStore; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import static java.util.stream.Collectors.toList; - -/** - * @author Pedro Igor - */ -public class MongoPolicyStore implements PolicyStore { - - private final MongoStoreInvocationContext invocationContext; - private final AuthorizationProvider authorizationProvider; - - public MongoPolicyStore(MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - this.invocationContext = invocationContext; - this.authorizationProvider = authorizationProvider; - } - - @Override - public Policy create(String name, String type, ResourceServer resourceServer) { - PolicyEntity entity = new PolicyEntity(); - - entity.setId(KeycloakModelUtils.generateId()); - entity.setName(name); - entity.setType(type); - entity.setResourceServerId(resourceServer.getId()); - - getMongoStore().insertEntity(entity, getInvocationContext()); - - return new PolicyAdapter(entity, getInvocationContext(), this.authorizationProvider) ; - } - - @Override - public void delete(String id) { - getMongoStore().removeEntity(PolicyEntity.class, id, getInvocationContext()); - } - - @Override - public Policy findById(String id, String resourceServerId) { - PolicyEntity entity = getMongoStore().loadEntity(PolicyEntity.class, id, getInvocationContext()); - - if (entity == null) { - return null; - } - - return new PolicyAdapter(entity, getInvocationContext(), this.authorizationProvider); - } - - - @Override - public Policy findByName(String name, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("name").is(name) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)).findFirst().orElse(null); - } - - @Override - public List findByResourceServer(String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - @Override - public List findByResourceServer(Map attributes, String resourceServerId, int firstResult, int maxResult) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("resourceServerId").is(resourceServerId); - - attributes.forEach((name, value) -> { - if ("permission".equals(name)) { - if (Boolean.valueOf(value[0])) { - queryBuilder.and("type").in(new String[] {"resource", "scope"}); - } else { - queryBuilder.and("type").notIn(new String[] {"resource", "scope"}); - } - } else if ("id".equals(name)) { - queryBuilder.and("_id").in(value); - } else { - queryBuilder.and(name).regex(Pattern.compile(".*" + value[0] + ".*", Pattern.CASE_INSENSITIVE)); - } - }); - - DBObject sort = new BasicDBObject("name", 1); - - return getMongoStore().loadEntities(PolicyEntity.class, queryBuilder.get(), sort, firstResult, maxResult, invocationContext).stream() - .map(policy -> findById(policy.getId(), resourceServerId)).collect(toList()); - } - - @Override - public List findByResource(String resourceId, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("resources").is(resourceId) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - @Override - public List findByResourceType(String resourceType, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .filter(policyEntity -> { - String defaultResourceType = policyEntity.getConfig().get("defaultResourceType"); - return defaultResourceType != null && defaultResourceType.equals(resourceType); - }) - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - @Override - public List findByScopeIds(List scopeIds, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("scopes").in(scopeIds) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - @Override - public List findByType(String type, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("type").is(type) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - @Override - public List findDependentPolicies(String policyId, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("associatedPolicies").is(policyId) - .get(); - - return getMongoStore().loadEntities(PolicyEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - private MongoStoreInvocationContext getInvocationContext() { - return this.invocationContext; - } - - private MongoStore getMongoStore() { - return getInvocationContext().getMongoStore(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceServerStore.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceServerStore.java deleted file mode 100644 index 25e5f67301a..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceServerStore.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.store; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.mongo.adapter.ResourceServerAdapter; -import org.keycloak.authorization.mongo.entities.ResourceServerEntity; -import org.keycloak.authorization.store.ResourceServerStore; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.utils.KeycloakModelUtils; - -/** - * @author Pedro Igor - */ -public class MongoResourceServerStore implements ResourceServerStore { - - private final MongoStoreInvocationContext invocationContext; - private final AuthorizationProvider authorizationProvider; - - public MongoResourceServerStore(MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - this.invocationContext = invocationContext; - this.authorizationProvider = authorizationProvider; - } - - @Override - public ResourceServer create(String clientId) { - ResourceServerEntity entity = new ResourceServerEntity(); - - entity.setId(KeycloakModelUtils.generateId()); - entity.setClientId(clientId); - - getMongoStore().insertEntity(entity, getInvocationContext()); - - return new ResourceServerAdapter(entity, getInvocationContext()); - } - - @Override - public void delete(String id) { - getMongoStore().removeEntity(ResourceServerEntity.class, id, getInvocationContext()); - } - - @Override - public ResourceServer findById(String id) { - ResourceServerEntity entity = getMongoStore().loadEntity(ResourceServerEntity.class, id, getInvocationContext()); - - if (entity == null) { - return null; - } - - return new ResourceServerAdapter(entity, getInvocationContext()); - } - - @Override - public ResourceServer findByClient(String clientId) { - DBObject query = new QueryBuilder() - .and("clientId").is(clientId) - .get(); - - return getMongoStore().loadEntities(ResourceServerEntity.class, query, getInvocationContext()).stream() - .map(resourceServer -> findById(resourceServer.getId())).findFirst().orElse(null); - } - - private MongoStoreInvocationContext getInvocationContext() { - return this.invocationContext; - } - - private MongoStore getMongoStore() { - return getInvocationContext().getMongoStore(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceStore.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceStore.java deleted file mode 100644 index dcbf3ec2f46..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoResourceStore.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.store; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.Resource; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.mongo.adapter.ResourceAdapter; -import org.keycloak.authorization.mongo.entities.ResourceEntity; -import org.keycloak.authorization.store.ResourceStore; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import static java.util.stream.Collectors.toList; - -/** - * @author Pedro Igor - */ -public class MongoResourceStore implements ResourceStore { - - private final MongoStoreInvocationContext invocationContext; - private final AuthorizationProvider authorizationProvider; - - public MongoResourceStore(MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - this.invocationContext = invocationContext; - this.authorizationProvider = authorizationProvider; - } - - @Override - public Resource create(String name, ResourceServer resourceServer, String owner) { - ResourceEntity entity = new ResourceEntity(); - - entity.setId(KeycloakModelUtils.generateId()); - entity.setName(name); - entity.setResourceServerId(resourceServer.getId()); - entity.setOwner(owner); - - getMongoStore().insertEntity(entity, getInvocationContext()); - - return new ResourceAdapter(entity, getInvocationContext(), this.authorizationProvider); - } - - @Override - public void delete(String id) { - getMongoStore().removeEntity(ResourceEntity.class, id, getInvocationContext()); - } - - @Override - public Resource findById(String id, String resourceServerId) { - ResourceEntity entity = getMongoStore().loadEntity(ResourceEntity.class, id, getInvocationContext()); - - if (entity == null) { - return null; - } - - return new ResourceAdapter(entity, getInvocationContext(), this.authorizationProvider); - } - - @Override - public List findByOwner(String ownerId, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("owner").is(ownerId) - .get(); - - return getMongoStore().loadEntities(ResourceEntity.class, query, getInvocationContext()).stream() - .map(scope -> findById(scope.getId(), resourceServerId)).collect(toList()); - } - - @Override - public List findByUri(String uri, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("uri").is(uri) - .get(); - - return getMongoStore().loadEntities(ResourceEntity.class, query, getInvocationContext()).stream() - .map(scope -> findById(scope.getId(), resourceServerId)).collect(toList()); - } - - @Override - public List findByResourceServer(String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .get(); - - return getMongoStore().loadEntities(ResourceEntity.class, query, getInvocationContext()).stream() - .map(scope -> findById(scope.getId(), resourceServerId)).collect(toList()); - } - - @Override - public List findByResourceServer(Map attributes, String resourceServerId, int firstResult, int maxResult) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("resourceServerId").is(resourceServerId); - - attributes.forEach((name, value) -> { - if ("scope".equals(name)) { - queryBuilder.and("scopes").in(value); - } else { - queryBuilder.and(name).regex(Pattern.compile(".*" + value[0] + ".*", Pattern.CASE_INSENSITIVE)); - } - }); - - DBObject sort = new BasicDBObject("name", 1); - - return getMongoStore().loadEntities(ResourceEntity.class, queryBuilder.get(), sort, firstResult, maxResult, invocationContext).stream() - .map(scope -> findById(scope.getId(), resourceServerId)).collect(toList()); - } - - @Override - public List findByScope(List id, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("scopes").in(id) - .get(); - - return getMongoStore().loadEntities(ResourceEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - @Override - public Resource findByName(String name, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("name").is(name) - .get(); - - return getMongoStore().loadEntities(ResourceEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)).findFirst().orElse(null); - } - - @Override - public List findByType(String type, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("type").is(type) - .get(); - - return getMongoStore().loadEntities(ResourceEntity.class, query, getInvocationContext()).stream() - .map(policyEntity -> findById(policyEntity.getId(), resourceServerId)) - .collect(toList()); - } - - private MongoStoreInvocationContext getInvocationContext() { - return this.invocationContext; - } - - private MongoStore getMongoStore() { - return getInvocationContext().getMongoStore(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoScopeStore.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoScopeStore.java deleted file mode 100644 index 04decb291f8..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoScopeStore.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.store; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.model.ResourceServer; -import org.keycloak.authorization.model.Scope; -import org.keycloak.authorization.mongo.adapter.ScopeAdapter; -import org.keycloak.authorization.mongo.entities.ScopeEntity; -import org.keycloak.authorization.store.ScopeStore; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import static java.util.stream.Collectors.toList; - -/** - * @author Pedro Igor - */ -public class MongoScopeStore implements ScopeStore { - - private final MongoStoreInvocationContext invocationContext; - private final AuthorizationProvider authorizationProvider; - - public MongoScopeStore(MongoStoreInvocationContext invocationContext, AuthorizationProvider authorizationProvider) { - this.invocationContext = invocationContext; - this.authorizationProvider = authorizationProvider; - } - - @Override - public Scope create(final String name, final ResourceServer resourceServer) { - ScopeEntity entity = new ScopeEntity(); - - entity.setId(KeycloakModelUtils.generateId()); - entity.setName(name); - entity.setResourceServerId(resourceServer.getId()); - - getMongoStore().insertEntity(entity, getInvocationContext()); - - return new ScopeAdapter(entity, getInvocationContext(), this.authorizationProvider); - } - - @Override - public void delete(String id) { - getMongoStore().removeEntity(ScopeEntity.class, id, getInvocationContext()); - } - - @Override - public Scope findById(String id, String resourceServerId) { - ScopeEntity entity = getMongoStore().loadEntity(ScopeEntity.class, id, getInvocationContext()); - - if (entity == null) { - return null; - } - - return new ScopeAdapter(entity, getInvocationContext(), this.authorizationProvider); - } - - @Override - public Scope findByName(String name, String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .and("name").is(name) - .get(); - - return getMongoStore().loadEntities(ScopeEntity.class, query, getInvocationContext()).stream() - .map(scope -> findById(scope.getId(), scope.getResourceServerId())).findFirst().orElse(null); - } - - @Override - public List findByResourceServer(String resourceServerId) { - DBObject query = new QueryBuilder() - .and("resourceServerId").is(resourceServerId) - .get(); - - return getMongoStore().loadEntities(ScopeEntity.class, query, getInvocationContext()).stream() - .map(scope -> findById(scope.getId(), scope.getResourceServerId())) - .collect(toList()); - } - - @Override - public List findByResourceServer(Map attributes, String resourceServerId, int firstResult, int maxResult) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("resourceServerId").is(resourceServerId); - - attributes.forEach((name, value) -> { - queryBuilder.and(name).regex(Pattern.compile(".*" + value[0] + ".*", Pattern.CASE_INSENSITIVE)); - }); - - DBObject sort = new BasicDBObject("name", 1); - - return getMongoStore().loadEntities(ScopeEntity.class, queryBuilder.get(), sort, firstResult, maxResult, invocationContext).stream() - .map(scope -> findById(scope.getId(), scope.getResourceServerId())).collect(toList()); - } - - private MongoStoreInvocationContext getInvocationContext() { - return this.invocationContext; - } - - private MongoStore getMongoStore() { - return getInvocationContext().getMongoStore(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoStoreFactory.java b/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoStoreFactory.java deleted file mode 100644 index 398b3d44182..00000000000 --- a/model/mongo/src/main/java/org/keycloak/authorization/mongo/store/MongoStoreFactory.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.authorization.mongo.store; - -import org.keycloak.authorization.AuthorizationProvider; -import org.keycloak.authorization.store.PolicyStore; -import org.keycloak.authorization.store.ResourceServerStore; -import org.keycloak.authorization.store.ResourceStore; -import org.keycloak.authorization.store.ScopeStore; -import org.keycloak.authorization.store.StoreFactory; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.KeycloakSession; - -/** - * @author Pedro Igor - */ -public class MongoStoreFactory implements StoreFactory { - - private final MongoStoreInvocationContext invocationContext; - private final KeycloakSession session; - - public MongoStoreFactory(MongoStoreInvocationContext invocationContext, KeycloakSession session) { - this.invocationContext = invocationContext; - this.session = session; - } - - @Override - public PolicyStore getPolicyStore() { - return new MongoPolicyStore(this.invocationContext, getAuthorizationProvider()); - } - - @Override - public ResourceServerStore getResourceServerStore() { - return new MongoResourceServerStore(this.invocationContext, getAuthorizationProvider()); - } - - @Override - public ResourceStore getResourceStore() { - return new MongoResourceStore(this.invocationContext, getAuthorizationProvider()); - } - - @Override - public ScopeStore getScopeStore() { - return new MongoScopeStore(this.invocationContext, getAuthorizationProvider()); - } - - private AuthorizationProvider getAuthorizationProvider() { - return session.getProvider(AuthorizationProvider.class); - } - - @Override - public void close() { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionFactoryProvider.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionFactoryProvider.java deleted file mode 100755 index 45d24d27051..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionFactoryProvider.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo; - -import com.mongodb.DB; -import com.mongodb.MongoClient; -import com.mongodb.MongoClientOptions; -import com.mongodb.MongoClientURI; -import com.mongodb.MongoCredential; -import com.mongodb.ServerAddress; -import org.jboss.logging.Logger; -import org.keycloak.Config; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.impl.MongoStoreImpl; -import org.keycloak.connections.mongo.impl.context.TransactionMongoStoreInvocationContext; -import org.keycloak.connections.mongo.updater.MongoUpdaterProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.KeycloakSessionTask; -import org.keycloak.models.dblock.DBLockManager; -import org.keycloak.models.dblock.DBLockProvider; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.provider.ServerInfoAwareProviderFactory; - -import javax.net.ssl.SSLSocketFactory; -import java.lang.reflect.Method; -import java.net.UnknownHostException; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * @author Stian Thorgersen - */ -public class DefaultMongoConnectionFactoryProvider implements MongoConnectionProviderFactory, ServerInfoAwareProviderFactory { - - enum MigrationStrategy { - UPDATE, VALIDATE - } - - // TODO Make it dynamic - private String[] entities = new String[]{ - "org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoUserEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoGroupEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoClientEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoClientTemplateEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoUserConsentEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoMigrationModelEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoOnlineUserSessionEntity", - "org.keycloak.models.mongo.keycloak.entities.MongoOfflineUserSessionEntity", - "org.keycloak.models.mongo.keycloak.entities.IdentityProviderEntity", - "org.keycloak.models.mongo.keycloak.entities.ClientIdentityProviderMappingEntity", - "org.keycloak.models.mongo.keycloak.entities.RequiredCredentialEntity", - "org.keycloak.models.mongo.keycloak.entities.CredentialEntity", - "org.keycloak.models.mongo.keycloak.entities.FederatedIdentityEntity", - "org.keycloak.models.mongo.keycloak.entities.UserFederationProviderEntity", - "org.keycloak.models.mongo.keycloak.entities.UserFederationMapperEntity", - "org.keycloak.models.mongo.keycloak.entities.ProtocolMapperEntity", - "org.keycloak.models.mongo.keycloak.entities.IdentityProviderMapperEntity", - "org.keycloak.models.mongo.keycloak.entities.AuthenticationExecutionEntity", - "org.keycloak.models.mongo.keycloak.entities.AuthenticationFlowEntity", - "org.keycloak.models.mongo.keycloak.entities.AuthenticatorConfigEntity", - "org.keycloak.models.mongo.keycloak.entities.RequiredActionProviderEntity", - "org.keycloak.models.mongo.keycloak.entities.PersistentUserSessionEntity", - "org.keycloak.models.mongo.keycloak.entities.PersistentClientSessionEntity", - "org.keycloak.models.mongo.keycloak.entities.ComponentEntity", - "org.keycloak.storage.mongo.entity.FederatedUser", - "org.keycloak.authorization.mongo.entities.PolicyEntity", - "org.keycloak.authorization.mongo.entities.ResourceEntity", - "org.keycloak.authorization.mongo.entities.ResourceServerEntity", - "org.keycloak.authorization.mongo.entities.ScopeEntity" - }; - - private static final Logger logger = Logger.getLogger(DefaultMongoConnectionFactoryProvider.class); - - private static final int STATE_BEFORE_INIT = 0; // Even before MongoClient is created - private static final int STATE_BEFORE_UPDATE = 1; // Mongo client was created, but DB is not yet updated to last version - private static final int STATE_AFTER_UPDATE = 2; // Mongo client was created and DB updated. DB is fully initialized now - - private volatile int state = STATE_BEFORE_INIT; - - private MongoClient client; - - private MongoStore mongoStore; - private DB db; - protected Config.Scope config; - - private Map operationalInfo; - - @Override - public void init(Config.Scope config) { - this.config = config; - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - - @Override - public DB getDBBeforeUpdate() { - lazyInitBeforeUpdate(); - return db; - } - - private void lazyInitBeforeUpdate() { - if (state == STATE_BEFORE_INIT) { - synchronized (this) { - if (state == STATE_BEFORE_INIT) { - try { - this.client = createMongoClient(); - String dbName = config.get("db", "keycloak"); - this.db = client.getDB(dbName); - - state = STATE_BEFORE_UPDATE; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } - } - - - @Override - public MongoConnectionProvider create(KeycloakSession session) { - lazyInit(session); - - TransactionMongoStoreInvocationContext invocationContext = new TransactionMongoStoreInvocationContext(mongoStore); - session.getTransactionManager().enlist(new MongoKeycloakTransaction(invocationContext)); - return new DefaultMongoConnectionProvider(db, mongoStore, invocationContext); - } - - private void lazyInit(KeycloakSession session) { - lazyInitBeforeUpdate(); - - if (state == STATE_BEFORE_UPDATE) { - synchronized (this) { - if (state == STATE_BEFORE_UPDATE) { - try { - update(session); - this.mongoStore = new MongoStoreImpl(db, getManagedEntities()); - - state = STATE_AFTER_UPDATE; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } - } - - private void update(KeycloakSession session) { - MigrationStrategy strategy = getMigrationStrategy(); - - MongoUpdaterProvider mongoUpdater = session.getProvider(MongoUpdaterProvider.class); - if (mongoUpdater == null) { - throw new RuntimeException("Can't update database: Mongo updater provider not found"); - } - - DBLockProvider dbLock = new DBLockManager(session).getDBLock(); - if (dbLock.hasLock()) { - updateOrValidateDB(strategy, session, mongoUpdater); - } else { - logger.trace("Don't have DBLock retrieved before upgrade. Needs to acquire lock first in separate transaction"); - - KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), new KeycloakSessionTask() { - - @Override - public void run(KeycloakSession lockSession) { - DBLockManager dbLockManager = new DBLockManager(lockSession); - DBLockProvider dbLock2 = dbLockManager.getDBLock(); - dbLock2.waitForLock(); - try { - updateOrValidateDB(strategy, session, mongoUpdater); - } finally { - dbLock2.releaseLock(); - } - } - - }); - } - } - - - private Class[] getManagedEntities() throws ClassNotFoundException { - Class[] entityClasses = new Class[entities.length]; - for (int i = 0; i < entities.length; i++) { - entityClasses[i] = getClass().getClassLoader().loadClass(entities[i]); - } - return entityClasses; - } - - protected void updateOrValidateDB(MigrationStrategy strategy, KeycloakSession session, MongoUpdaterProvider mongoUpdater) { - switch (strategy) { - case UPDATE: - mongoUpdater.update(session, db); - break; - case VALIDATE: - mongoUpdater.validate(session, db); - break; - } - } - - @Override - public void close() { - if (client != null) { - client.close(); - } - } - - @Override - public String getId() { - return "default"; - } - - - /** - * Override this method if you want more possibility to configure Mongo client. It can be also used to inject mongo client - * from different source. - * - * This method can assume that "config" is already set and can use it. - * - * @return mongoClient instance, which will be shared for whole Keycloak - * - * @throws UnknownHostException - */ - protected MongoClient createMongoClient() throws UnknownHostException { - operationalInfo = new LinkedHashMap<>(); - String dbName = config.get("db", "keycloak"); - - String uriString = config.get("uri"); - if (uriString != null) { - MongoClientURI uri = new MongoClientURI(uriString); - MongoClient client = new MongoClient(uri); - - StringBuilder hostsBuilder = new StringBuilder(); - for (int i=0 ; i getOperationalInfo() { - return operationalInfo; - } - - private MigrationStrategy getMigrationStrategy() { - String migrationStrategy = config.get("migrationStrategy"); - if (migrationStrategy == null) { - // Support 'databaseSchema' for backwards compatibility - migrationStrategy = config.get("databaseSchema"); - } - - if (migrationStrategy != null) { - return MigrationStrategy.valueOf(migrationStrategy.toUpperCase()); - } else { - return MigrationStrategy.UPDATE; - } - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionProvider.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionProvider.java deleted file mode 100644 index 9bd479d7c75..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/DefaultMongoConnectionProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo; - -import com.mongodb.DB; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Stian Thorgersen - */ -public class DefaultMongoConnectionProvider implements MongoConnectionProvider { - - private DB db; - private MongoStore mongoStore; - private MongoStoreInvocationContext invocationContext; - - public DefaultMongoConnectionProvider(DB db, MongoStore mongoStore, MongoStoreInvocationContext invocationContext) { - this.db = db; - this.mongoStore = mongoStore; - this.invocationContext = invocationContext; - } - - @Override - public DB getDB() { - return db; - } - - @Override - public MongoStore getMongoStore() { - return mongoStore; - } - - @Override - public MongoStoreInvocationContext getInvocationContext() { - return invocationContext; - } - - @Override - public void close() { - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProvider.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProvider.java deleted file mode 100644 index f13eaf7a4e7..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo; - -import com.mongodb.DB; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.provider.Provider; - -/** - * @author Stian Thorgersen - */ -public interface MongoConnectionProvider extends Provider { - - /** - * @return Fully updated and initialized DB - */ - DB getDB(); - - MongoStore getMongoStore(); - - MongoStoreInvocationContext getInvocationContext(); - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProviderFactory.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProviderFactory.java deleted file mode 100644 index 42a18533d9b..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionProviderFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo; - -import com.mongodb.DB; -import org.keycloak.provider.ProviderFactory; - -/** - * @author Stian Thorgersen - */ -public interface MongoConnectionProviderFactory extends ProviderFactory { - - /** - * @return DB object, which may not be yet updated to current Keycloak version. Useful just if something needs to be done even before DB update (for example acquire DB lock) - */ - DB getDBBeforeUpdate(); - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionSpi.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionSpi.java deleted file mode 100644 index 8eb672eb540..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoConnectionSpi.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo; - -import org.keycloak.provider.Provider; -import org.keycloak.provider.ProviderFactory; -import org.keycloak.provider.Spi; - -/** - * @author Stian Thorgersen - */ -public class MongoConnectionSpi implements Spi { - - @Override - public boolean isInternal() { - return true; - } - - @Override - public String getName() { - return "connectionsMongo"; - } - - @Override - public Class getProviderClass() { - return MongoConnectionProvider.class; - } - - @Override - public Class getProviderFactoryClass() { - return MongoConnectionProviderFactory.class; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoKeycloakTransaction.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoKeycloakTransaction.java deleted file mode 100644 index 85d76ab3921..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/MongoKeycloakTransaction.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo; - -import com.mongodb.MongoException; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.connections.mongo.impl.MongoStoreImpl; -import org.keycloak.models.KeycloakTransaction; - -/** - * @author Marek Posolda - */ -public class MongoKeycloakTransaction implements KeycloakTransaction { - - private final MongoStoreInvocationContext invocationContext; - - private boolean started = false; - private boolean rollbackOnly = false; - - public MongoKeycloakTransaction(MongoStoreInvocationContext invocationContext) { - this.invocationContext = invocationContext; - } - - @Override - public void begin() { - if (started) { - throw new IllegalStateException("Transaction already started"); - } - started = true; - invocationContext.begin(); - } - - @Override - public void commit() { - if (!started) { - throw new IllegalStateException("Transaction not yet started"); - } - if (rollbackOnly) { - throw new IllegalStateException("Can't commit as transaction marked for rollback"); - } - - try { - invocationContext.commit(); - } catch (MongoException e) { - throw MongoStoreImpl.convertException(e); - } - started = false; - } - - @Override - public void rollback() { - invocationContext.rollback(); - started = false; - } - - @Override - public void setRollbackOnly() { - this.rollbackOnly = true; - } - - @Override - public boolean getRollbackOnly() { - return rollbackOnly; - } - - @Override - public boolean isActive() { - return started; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoCollection.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoCollection.java deleted file mode 100644 index a3a760b610a..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoCollection.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api; - -import java.lang.annotation.Documented; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * @author Marek Posolda - */ -@Target({TYPE}) -@Documented -@Retention(RUNTIME) -@Inherited -public @interface MongoCollection { - - String collectionName(); -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoEntity.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoEntity.java deleted file mode 100644 index b626cb7f378..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoEntity.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api; - -/** - * Base interface for object, which is persisted in Mongo - * - * @author Marek Posolda - */ -public interface MongoEntity { -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoField.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoField.java deleted file mode 100644 index a0359ebe289..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoField.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * @author Marek Posolda - */ -@Target({METHOD, FIELD}) -@Documented -@Retention(RUNTIME) -public @interface MongoField { - - // TODO: fieldName add lazy loading? -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoIdentifiableEntity.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoIdentifiableEntity.java deleted file mode 100644 index d162c5a6b6a..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoIdentifiableEntity.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api; - -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * Entity with Id - * - * @author Marek Posolda - */ -public interface MongoIdentifiableEntity extends MongoEntity { - - public String getId(); - - public void setId(String id); - - /** - * Lifecycle callback, which is called after removal of this object from Mongo. - * It may be useful for triggering removal of wired objects. - */ - void afterRemove(MongoStoreInvocationContext invocationContext); -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoStore.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoStore.java deleted file mode 100755 index 1611cdff429..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/MongoStore.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api; - -import com.mongodb.DBObject; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -import java.util.List; - -/** - * @author Marek Posolda - */ -public interface MongoStore { - - /** - * Insert new entity - * - * @param entity to insert - */ - void insertEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context); - - /** - * Update existing entity - * - * @param entity to update - */ - void updateEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context); - - /** - * Bulk update of more entities of some type - * - * @param type - * @param query - * @param update - * @param context - * @return count of updated entities - */ - int updateEntities(Class type, DBObject query, DBObject update, MongoStoreInvocationContext context); - - T loadEntity(Class type, String id, MongoStoreInvocationContext context); - - T loadSingleEntity(Class type, DBObject query, MongoStoreInvocationContext context); - - /** - * @param type - * @param query - * @param context - * @return query result or empty list if no results available for the query. Doesn't return null - */ - List loadEntities(Class type, DBObject query, MongoStoreInvocationContext context); - - /** - * @param type - * @param query - * @param context - * @return query result or empty list if no results available for the query. Doesn't return null - */ - List loadEntities(Class type, DBObject query, DBObject sort, int firstResult, int maxResults, MongoStoreInvocationContext context); - - int countEntities(Class type, DBObject query, MongoStoreInvocationContext context); - - boolean removeEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context); - - boolean removeEntity(Class type, String id, MongoStoreInvocationContext context); - - /** - * - * @param type - * @param query - * @param callback if true, then store will first load all entities, then call "afterRemove" for every entity. If false, the entities are removed directly without load and calling "afterRemove" callback - * false has better performance (especially if we are going to remove big number of entities) - * @param context - * @return count of removed entities - */ - int removeEntities(Class type, DBObject query, boolean callback, MongoStoreInvocationContext context); - - boolean pushItemToList(MongoIdentifiableEntity entity, String listPropertyName, S itemToPush, boolean skipIfAlreadyPresent, MongoStoreInvocationContext context); - - boolean pullItemFromList(MongoIdentifiableEntity entity, String listPropertyName, S itemToPull, MongoStoreInvocationContext context); - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoStoreInvocationContext.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoStoreInvocationContext.java deleted file mode 100644 index 454cd938536..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoStoreInvocationContext.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api.context; - -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.MongoStore; - -/** - * Context, which provides callback methods to be invoked by MongoStore - * - * @author Marek Posolda - */ -public interface MongoStoreInvocationContext { - - void addCreatedEntity(MongoIdentifiableEntity entity); - - void addLoadedEntity(MongoIdentifiableEntity entity); - - T getLoadedEntity(Class type, String id); - - void addUpdateTask(MongoIdentifiableEntity entityToUpdate, MongoTask task); - - void addRemovedEntity(MongoIdentifiableEntity entity); - - void beforeDBSearch(Class entityType); - - void beforeDBBulkUpdateOrRemove(Class entityType); - - void begin(); - - void commit(); - - void rollback(); - - MongoStore getMongoStore(); -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoTask.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoTask.java deleted file mode 100644 index e0f603704ff..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/context/MongoTask.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api.context; - -/** - * @author Marek Posolda - */ -public interface MongoTask { - - void execute(); - - boolean isFullUpdate(); -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/Mapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/Mapper.java deleted file mode 100644 index af23e5892fe..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/Mapper.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api.types; - -/** - * SPI object to convert object from application type to database type and vice versa. Shouldn't be directly used by application. - * Various mappers should be registered in MapperRegistry, which is main entry point to be used by application - * - * @author Marek Posolda - */ -public interface Mapper { - - /** - * Convert object from one type to expected type - * - * @param mapperContext Encapsulates reference to converted object and other things, which might be helpful in conversion - * @return converted object - */ - S convertObject(MapperContext mapperContext); - - Class getTypeOfObjectToConvert(); - - Class getExpectedReturnType(); -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperContext.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperContext.java deleted file mode 100644 index 2516f29f3d4..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperContext.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api.types; - -import java.lang.reflect.Type; -import java.util.List; - -/** - * @author Marek Posolda - */ -public class MapperContext { - - // object to convert - private final T objectToConvert; - - // expected return type, which could be useful information in some mappers, so they are able to dynamically instantiate types - private final Class expectedReturnType; - - // in case that expected return type is generic type (like "List"), then genericTypes could contain list of expected generic arguments - private final List genericTypes; - - public MapperContext(T objectToConvert, Class expectedReturnType, List genericTypes) { - this.objectToConvert = objectToConvert; - this.expectedReturnType = expectedReturnType; - this.genericTypes = genericTypes; - } - - public T getObjectToConvert() { - return objectToConvert; - } - - public Class getExpectedReturnType() { - return expectedReturnType; - } - - public List getGenericTypes() { - return genericTypes; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperRegistry.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperRegistry.java deleted file mode 100755 index 2c4ce699421..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/api/types/MapperRegistry.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.api.types; - -import java.util.HashMap; -import java.util.Map; - -/** - * Registry of mappers, which allow to convert application object to database objects. MapperRegistry is main entry point to be used by application. - * Application can create instance of MapperRegistry and then register required Mapper objects. - * - * @author Marek Posolda - */ -public class MapperRegistry { - - // TODO: Thread-safety support (maybe...) - // Mappers of Application objects to DB objects - private Map, Mapper> appObjectMappers = new HashMap, Mapper>(); - - // Mappers of DB objects to Application objects - private Map, Map, Mapper>> dbObjectMappers = new HashMap, Map, Mapper>>(); - - - /** - * Add mapper for converting application objects to DB objects - * - * @param mapper - */ - public void addAppObjectMapper(Mapper mapper) { - appObjectMappers.put(mapper.getTypeOfObjectToConvert(), mapper); - } - - - /** - * Add mapper for converting DB objects to application objects - * - * @param mapper - */ - public void addDBObjectMapper(Mapper mapper) { - Class dbObjectType = mapper.getTypeOfObjectToConvert(); - Class appObjectType = mapper.getExpectedReturnType(); - Map, Mapper> appObjects = dbObjectMappers.get(dbObjectType); - if (appObjects == null) { - appObjects = new HashMap, Mapper>(); - dbObjectMappers.put(dbObjectType, appObjects); - } - appObjects.put(appObjectType, mapper); - } - - - public S convertDBObjectToApplicationObject(MapperContext context) { - if (context.getObjectToConvert() == null) { - return null; - } - - Object dbObject = context.getObjectToConvert(); - Class expectedApplicationObjectType = context.getExpectedReturnType(); - - Class dbObjectType = dbObject.getClass(); - Mapper mapper; - - Map, Mapper> appObjects = dbObjectMappers.get(dbObjectType); - if (appObjects == null) { - throw new IllegalArgumentException("Not found any mappers for type " + dbObjectType); - } else { - if (appObjects.size() == 1) { - mapper = (Mapper)appObjects.values().iterator().next(); - } else { - // Try to find converter for requested application type - mapper = (Mapper)getAppConverterForType(context.getExpectedReturnType(), appObjects); - } - } - - if (mapper == null) { - throw new IllegalArgumentException("Can't found mapper for type " + dbObjectType + " and expectedApplicationType " + expectedApplicationObjectType); - } - - return mapper.convertObject(context); - } - - - public S convertApplicationObjectToDBObject(Object applicationObject, Class expectedDBObjectType) { - if (applicationObject == null) { - return null; - } - - Class appObjectType = applicationObject.getClass(); - Mapper mapper = (Mapper)getAppConverterForType(appObjectType, appObjectMappers); - if (mapper == null) { - throw new IllegalArgumentException("Can't found converter for type " + appObjectType + " in registered appObjectMappers"); - } - if (!expectedDBObjectType.isAssignableFrom(mapper.getExpectedReturnType())) { - throw new IllegalArgumentException("Converter " + mapper + " has return type " + mapper.getExpectedReturnType() + - " but we need type " + expectedDBObjectType); - } - return mapper.convertObject(new MapperContext(applicationObject, expectedDBObjectType, null)); - } - - // Try to find converter for given type or all it's supertypes - private static Mapper getAppConverterForType(Class appObjectType, Map, Mapper> appObjectConverters) { - Mapper mapper = (Mapper)appObjectConverters.get(appObjectType); - if (mapper != null) { - return mapper; - } else { - Class[] interfaces = appObjectType.getInterfaces(); - for (Class interface1 : interfaces) { - mapper = getAppConverterForType(interface1, appObjectConverters); - if (mapper != null) { - return mapper; - } - } - - Class superType = appObjectType.getSuperclass(); - if (superType != null) { - return getAppConverterForType(superType, appObjectConverters); - } else { - return null; - } - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java deleted file mode 100755 index 3e1dd71142c..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/EntityInfo.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl; - -import org.keycloak.models.utils.reflection.Property; - -import java.util.Collection; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class EntityInfo { - - private final Class entityClass; - - private final String dbCollectionName; - - private final Map> properties; - - public EntityInfo(Class entityClass, String dbCollectionName, Map> properties) { - this.entityClass = entityClass; - this.dbCollectionName = dbCollectionName; - this.properties = properties; - } - - public Class getEntityClass() { - return entityClass; - } - - public String getDbCollectionName() { - return dbCollectionName; - } - - public Collection> getProperties() { - return properties.values(); - } - - public Property getPropertyByName(String propertyName) { - return properties.get(propertyName); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/MongoStoreImpl.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/MongoStoreImpl.java deleted file mode 100755 index f54bc14d8de..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/MongoStoreImpl.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.DBObject; -import com.mongodb.DuplicateKeyException; -import com.mongodb.MongoException; -import com.mongodb.WriteResult; -import org.jboss.logging.Logger; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoEntity; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.connections.mongo.api.context.MongoTask; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; -import org.keycloak.connections.mongo.impl.types.BasicDBListMapper; -import org.keycloak.connections.mongo.impl.types.BasicDBListToSetMapper; -import org.keycloak.connections.mongo.impl.types.BasicDBObjectMapper; -import org.keycloak.connections.mongo.impl.types.BasicDBObjectToMapMapper; -import org.keycloak.connections.mongo.impl.types.EnumToStringMapper; -import org.keycloak.connections.mongo.impl.types.ListMapper; -import org.keycloak.connections.mongo.impl.types.MapMapper; -import org.keycloak.connections.mongo.impl.types.MongoEntityMapper; -import org.keycloak.connections.mongo.impl.types.SimpleMapper; -import org.keycloak.connections.mongo.impl.types.StringToEnumMapper; -import org.keycloak.models.ModelDuplicateException; -import org.keycloak.models.ModelException; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.models.utils.reflection.Property; -import org.keycloak.models.utils.reflection.PropertyQueries; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * @author Marek Posolda - */ -public class MongoStoreImpl implements MongoStore { - - private static final Class[] SIMPLE_TYPES = { String.class, Integer.class, Boolean.class, Long.class, Double.class, Character.class, Date.class, byte[].class }; - - private final DB database; - private static final Logger logger = Logger.getLogger(MongoStoreImpl.class); - - private final MapperRegistry mapperRegistry; - private ConcurrentMap, EntityInfo> entityInfoCache = - new ConcurrentHashMap, EntityInfo>(); - - - public MongoStoreImpl(DB database, Class[] managedEntityTypes) { - this.database = database; - - mapperRegistry = new MapperRegistry(); - - for (Class simpleMapperClass : SIMPLE_TYPES) { - SimpleMapper mapper = new SimpleMapper(simpleMapperClass); - mapperRegistry.addAppObjectMapper(mapper); - mapperRegistry.addDBObjectMapper(mapper); - } - - // Specific converter for ArrayList is added just for performance purposes to avoid recursive converter lookup (most of list idm will be ArrayList) - mapperRegistry.addAppObjectMapper(new ListMapper(mapperRegistry, ArrayList.class)); - mapperRegistry.addAppObjectMapper(new ListMapper(mapperRegistry, List.class)); - mapperRegistry.addDBObjectMapper(new BasicDBListMapper(mapperRegistry)); - - mapperRegistry.addAppObjectMapper(new ListMapper(mapperRegistry, HashSet.class)); - mapperRegistry.addAppObjectMapper(new ListMapper(mapperRegistry, Set.class)); - mapperRegistry.addDBObjectMapper(new BasicDBListToSetMapper(mapperRegistry)); - - mapperRegistry.addAppObjectMapper(new MapMapper(mapperRegistry, HashMap.class)); - mapperRegistry.addAppObjectMapper(new MapMapper(mapperRegistry, Map.class)); - mapperRegistry.addDBObjectMapper(new BasicDBObjectToMapMapper(mapperRegistry)); - - // Enum converters - mapperRegistry.addAppObjectMapper(new EnumToStringMapper()); - mapperRegistry.addDBObjectMapper(new StringToEnumMapper()); - - for (Class type : managedEntityTypes) { - getEntityInfo(type); - mapperRegistry.addAppObjectMapper(new MongoEntityMapper(this, mapperRegistry, type)); - mapperRegistry.addDBObjectMapper(new BasicDBObjectMapper(this, mapperRegistry, type)); - } - } - - protected void dropDatabase() { - this.database.dropDatabase(); - logger.info("Database " + this.database.getName() + " dropped in MongoDB"); - } - - @Override - public void insertEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context) { - Class clazz = entity.getClass(); - - // Find annotations for ID, for all the properties and for the name of the collection. - EntityInfo entityInfo = getEntityInfo(clazz); - - // Create instance of BasicDBObject and add all declared properties to it (properties with null value probably should be skipped) - BasicDBObject dbObject = mapperRegistry.convertApplicationObjectToDBObject(entity, BasicDBObject.class); - - DBCollection dbCollection = database.getCollection(entityInfo.getDbCollectionName()); - - String currentId = entity.getId(); - - // Generate random ID if not set already - if (currentId == null) { - currentId = KeycloakModelUtils.generateId(); - entity.setId(currentId); - } - - // Adding "_id" - dbObject.put("_id", currentId); - - try { - dbCollection.insert(dbObject); - } catch (MongoException e) { - throw convertException(e); - } - - // Treat object as created in this transaction (It is already submitted to transaction) - context.addCreatedEntity(entity); - } - - public static ModelException convertException(MongoException e) { - if (e instanceof DuplicateKeyException) { - return new ModelDuplicateException(e); - } else { - return new ModelException(e); - } - } - - @Override - public void updateEntity(final MongoIdentifiableEntity entity, MongoStoreInvocationContext context) { - MongoTask fullUpdateTask = new MongoTask() { - - @Override - public void execute() { - Class clazz = entity.getClass(); - EntityInfo entityInfo = getEntityInfo(clazz); - BasicDBObject dbObject = mapperRegistry.convertApplicationObjectToDBObject(entity, BasicDBObject.class); - DBCollection dbCollection = database.getCollection(entityInfo.getDbCollectionName()); - - String currentId = entity.getId(); - - if (currentId == null) { - throw new IllegalStateException("Can't update entity without id: " + entity); - } else { - BasicDBObject query = new BasicDBObject("_id", currentId); - dbCollection.update(query, dbObject); - } - } - - @Override - public boolean isFullUpdate() { - return true; - } - }; - - // update is just added to context and postponed - context.addUpdateTask(entity, fullUpdateTask); - } - - @Override - public int updateEntities(Class type, DBObject query, DBObject update, MongoStoreInvocationContext context) { - context.beforeDBBulkUpdateOrRemove(type); - - DBCollection collection = getDBCollectionForType(type); - WriteResult wr = collection.update(query, update, false, true); - - logger.debugf("Updated %d collections of type %s", wr.getN(), type); - return wr.getN(); - } - - @Override - public T loadEntity(Class type, String id, MongoStoreInvocationContext context) { - // First look if we already read the object with this oid and type during this transaction. If yes, use it instead of DB lookup - T cached = context.getLoadedEntity(type, id); - if (cached != null && type.isAssignableFrom(cached.getClass())) return cached; - - DBCollection dbCollection = getDBCollectionForType(type); - - BasicDBObject idQuery = new BasicDBObject("_id", id); - DBObject dbObject = dbCollection.findOne(idQuery); - - if (dbObject == null) return null; - - MapperContext mapperContext = new MapperContext(dbObject, type, null); - T converted = mapperRegistry.convertDBObjectToApplicationObject(mapperContext); - - // Now add it to loaded objects - context.addLoadedEntity(converted); - - return converted; - } - - - @Override - public T loadSingleEntity(Class type, DBObject query, MongoStoreInvocationContext context) { - // First we should execute all pending tasks before searching DB - context.beforeDBSearch(type); - - DBCollection dbCollection = getDBCollectionForType(type); - DBObject dbObject = dbCollection.findOne(query); - - if (dbObject == null) { - return null; - } else { - return convertDBObjectToEntity(type, dbObject, context); - } - } - - - @Override - public List loadEntities(Class type, DBObject query, MongoStoreInvocationContext context) { - // First we should execute all pending tasks before searching DB - context.beforeDBSearch(type); - - DBCollection dbCollection = getDBCollectionForType(type); - DBCursor cursor = dbCollection.find(query); - - return convertCursor(type, cursor, context); - } - - @Override - public List loadEntities(Class type, DBObject query, DBObject sort, int firstResult, int maxResults, MongoStoreInvocationContext context) { - // First we should execute all pending tasks before searching DB - context.beforeDBSearch(type); - - DBCollection dbCollection = getDBCollectionForType(type); - DBCursor cursor = dbCollection.find(query); - if (firstResult != -1) { - cursor.skip(firstResult); - } - if (maxResults != -1) { - cursor.limit(maxResults); - } - if (sort != null) { - cursor.sort(sort); - } - - return convertCursor(type, cursor, context); - } - - public int countEntities(Class type, DBObject query, MongoStoreInvocationContext context) { - context.beforeDBSearch(type); - - DBCollection dbCollection = getDBCollectionForType(type); - Long count = dbCollection.count(query); - - // For now, assume that int is sufficient - return count.intValue(); - } - - @Override - public boolean removeEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context) { - return removeEntity(entity.getClass(), entity.getId(), context); - } - - - @Override - public boolean removeEntity(Class type, String id, MongoStoreInvocationContext context) { - MongoIdentifiableEntity found = loadEntity(type, id, context); - if (found == null) { - return false; - } else { - DBCollection dbCollection = getDBCollectionForType(type); - BasicDBObject dbQuery = new BasicDBObject("_id", id); - dbCollection.remove(dbQuery); - //logger.debugf("Entity of type: %s , id: %s removed from MongoDB.", type, id); - - context.addRemovedEntity(found); - return true; - } - } - - - @Override - public int removeEntities(Class type, DBObject query, boolean callback, MongoStoreInvocationContext context) { - if (callback) { - List foundObjects = loadEntities(type, query, context); - if (foundObjects.size() == 0) { - return 0; - } else { - DBCollection dbCollection = getDBCollectionForType(type); - dbCollection.remove(query); - - logger.debugf("Removed %d entities of type: %s, query: %s", foundObjects.size(), type, query); - - for (MongoIdentifiableEntity found : foundObjects) { - context.addRemovedEntity(found);; - } - return foundObjects.size(); - } - } else { - - context.beforeDBBulkUpdateOrRemove(type); - - DBCollection dbCollection = getDBCollectionForType(type); - WriteResult writeResult = dbCollection.remove(query); - int removedCount = writeResult.getN(); - - logger.debugf("Removed directly %d entities of type: %s, query: %s", removedCount, type, query); - return removedCount; - } - } - - @Override - public boolean pushItemToList(final MongoIdentifiableEntity entity, final String listPropertyName, S itemToPush, boolean skipIfAlreadyPresent, MongoStoreInvocationContext context) { - final Class type = entity.getClass(); - EntityInfo entityInfo = getEntityInfo(type); - - // Add item to list directly in this object - Property listProperty = entityInfo.getPropertyByName(listPropertyName); - if (listProperty == null) { - throw new IllegalArgumentException("Property " + listPropertyName + " doesn't exist on object " + entity); - } - - List list = (List)listProperty.getValue(entity); - if (list == null) { - list = new ArrayList(); - listProperty.setValue(entity, list); - } - - // Skip if item is already in list - if (skipIfAlreadyPresent && list.contains(itemToPush)) { - return false; - } - - // Update java object - list.add(itemToPush); - - // Add update of list to pending tasks - final List listt = list; - context.addUpdateTask(entity, new MongoTask() { - - @Override - public void execute() { - // Now DB update of new list with usage of $set - BasicDBList dbList = mapperRegistry.convertApplicationObjectToDBObject(listt, BasicDBList.class); - - BasicDBObject query = new BasicDBObject("_id", entity.getId()); - BasicDBObject listObject = new BasicDBObject(listPropertyName, dbList); - BasicDBObject setCommand = new BasicDBObject("$set", listObject); - getDBCollectionForType(type).update(query, setCommand); - } - - @Override - public boolean isFullUpdate() { - return false; - } - }); - - return true; - } - - - @Override - public boolean pullItemFromList(final MongoIdentifiableEntity entity, final String listPropertyName, final S itemToPull, MongoStoreInvocationContext context) { - final Class type = entity.getClass(); - EntityInfo entityInfo = getEntityInfo(type); - - // Remove item from list directly in this object - Property listProperty = entityInfo.getPropertyByName(listPropertyName); - if (listProperty == null) { - throw new IllegalArgumentException("Property " + listPropertyName + " doesn't exist on object " + entity); - } - List list = (List)listProperty.getValue(entity); - - // If list is null, we skip both object and DB update - if (list == null || !list.contains(itemToPull)) { - return false; - } else { - - // Update java object - list.remove(itemToPull); - - // Add update of list to pending tasks - context.addUpdateTask(entity, new MongoTask() { - - @Override - public void execute() { - // Pull item from DB - Object dbItemToPull = mapperRegistry.convertApplicationObjectToDBObject(itemToPull, Object.class); - BasicDBObject query = new BasicDBObject("_id", entity.getId()); - BasicDBObject pullObject = new BasicDBObject(listPropertyName, dbItemToPull); - BasicDBObject pullCommand = new BasicDBObject("$pull", pullObject); - getDBCollectionForType(type).update(query, pullCommand); - } - - @Override - public boolean isFullUpdate() { - return false; - } - }); - - return true; - } - } - - // Possibility to add user-defined mappers - public void addAppObjectConverter(Mapper mapper) { - mapperRegistry.addAppObjectMapper(mapper); - } - - public void addDBObjectConverter(Mapper mapper) { - mapperRegistry.addDBObjectMapper(mapper); - } - - public EntityInfo getEntityInfo(Class entityClass) { - EntityInfo entityInfo = entityInfoCache.get(entityClass); - if (entityInfo == null) { - Map> properties = PropertyQueries.createQuery(entityClass).getWritableResultList(); - - MongoCollection classAnnotation = entityClass.getAnnotation(MongoCollection.class); - - String dbCollectionName = classAnnotation==null ? null : classAnnotation.collectionName(); - entityInfo = new EntityInfo(entityClass, dbCollectionName, properties); - - EntityInfo existing = entityInfoCache.putIfAbsent(entityClass, entityInfo); - if (existing != null) { - entityInfo = existing; - } - } - - return entityInfo; - } - - protected List convertCursor(Class type, DBCursor cursor, MongoStoreInvocationContext context) { - List result = new ArrayList(); - - try { - for (DBObject dbObject : cursor) { - T entity = convertDBObjectToEntity(type, dbObject, context); - result.add(entity); - } - } finally { - cursor.close(); - } - - return result; - } - - protected T convertDBObjectToEntity(Class type, DBObject dbObject, MongoStoreInvocationContext context) { - // First look if we already have loaded object cached. If yes, we will use cached instance - String id = dbObject.get("_id").toString(); - T object = context.getLoadedEntity(type, id); - - if (object == null) { - // So convert and use fresh instance from DB - MapperContext mapperContext = new MapperContext(dbObject, type, null); - object = mapperRegistry.convertDBObjectToApplicationObject(mapperContext); - context.addLoadedEntity(object); - } - return object; - } - - protected DBCollection getDBCollectionForType(Class type) { - EntityInfo entityInfo = getEntityInfo(type); - String dbCollectionName = entityInfo.getDbCollectionName(); - return dbCollectionName==null ? null : database.getCollection(dbCollectionName); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/SimpleMongoStoreInvocationContext.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/SimpleMongoStoreInvocationContext.java deleted file mode 100644 index ef1041cc95b..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/SimpleMongoStoreInvocationContext.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.context; - -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.connections.mongo.api.context.MongoTask; - -/** - * Context, which is not doing any postponing of tasks and does not cache anything - * - * @author Marek Posolda - */ -public class SimpleMongoStoreInvocationContext implements MongoStoreInvocationContext { - - private final MongoStore mongoStore; - - public SimpleMongoStoreInvocationContext(MongoStore mongoStore) { - this.mongoStore = mongoStore; - } - - @Override - public void addCreatedEntity(MongoIdentifiableEntity entity) { - } - - @Override - public void addLoadedEntity(MongoIdentifiableEntity entity) { - } - - @Override - public T getLoadedEntity(Class type, String id) { - return null; - } - - @Override - public void addUpdateTask(MongoIdentifiableEntity entityToUpdate, MongoTask task) { - task.execute(); - } - - @Override - public void addRemovedEntity(MongoIdentifiableEntity entity) { - entity.afterRemove(this); - } - - @Override - public void beforeDBSearch(Class entityType) { - } - - @Override - public void beforeDBBulkUpdateOrRemove(Class entityType) { - } - - @Override - public void begin() { - } - - @Override - public void commit() { - } - - @Override - public void rollback() { - } - - @Override - public MongoStore getMongoStore() { - return mongoStore; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/TransactionMongoStoreInvocationContext.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/TransactionMongoStoreInvocationContext.java deleted file mode 100644 index 3fd2cee4314..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/context/TransactionMongoStoreInvocationContext.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.context; - -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.connections.mongo.api.context.MongoTask; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -/** - * Invocation context, which has some very basic support for transactions, and is able to cache loaded objects. - * It always execute all pending update tasks before start searching for other objects - * - * It's per-request object (not thread safe) - * - * @author Marek Posolda - */ -public class TransactionMongoStoreInvocationContext implements MongoStoreInvocationContext { - - // Assumption is that all objects has unique ID (unique across all the types) - private Map loadedObjects = new HashMap(); - - private Map> pendingUpdateTasks = new HashMap>(); - - private final MongoStore mongoStore; - - public TransactionMongoStoreInvocationContext(MongoStore mongoStore) { - this.mongoStore = mongoStore; - } - - @Override - public void addCreatedEntity(MongoIdentifiableEntity entity) { - // For now just add it to list of loaded objects - addLoadedEntity(entity); - } - - @Override - public void addLoadedEntity(MongoIdentifiableEntity entity) { - loadedObjects.put(entity.getId(), entity); - } - - @Override - public T getLoadedEntity(Class type, String id) { - return (T)loadedObjects.get(id); - } - - @Override - public void addUpdateTask(MongoIdentifiableEntity entityToUpdate, MongoTask task) { - Set currentObjectTasks = pendingUpdateTasks.get(entityToUpdate); - if (currentObjectTasks == null) { - currentObjectTasks = new LinkedHashSet(); - pendingUpdateTasks.put(entityToUpdate, currentObjectTasks); - } else { - // if task is full update, then remove all other tasks as we need to do full update of object anyway - if (task.isFullUpdate()) { - currentObjectTasks.clear(); - } else { - // If it already contains task for fullUpdate, then we don't need to add ours as we need to do full update of object anyway - for (MongoTask current : currentObjectTasks) { - if (current.isFullUpdate()) { - return; - } - } - } - } - - currentObjectTasks.add(task); - } - - @Override - public void addRemovedEntity(MongoIdentifiableEntity entity) { - // Remove all pending tasks and object from cache - pendingUpdateTasks.remove(entity); - loadedObjects.remove(entity.getId()); - - entity.afterRemove(this); - } - - @Override - public void beforeDBSearch(Class entityType) { - // Now execute pending update tasks of type, which will be searched - Set toRemove = new HashSet(); - - for (MongoIdentifiableEntity currentEntity : pendingUpdateTasks.keySet()) { - if (currentEntity.getClass().equals(entityType)) { - Set mongoTasks = pendingUpdateTasks.get(currentEntity); - for (MongoTask currentTask : mongoTasks) { - currentTask.execute(); - } - - toRemove.add(currentEntity); - } - } - - // Now remove all done tasks - for (MongoIdentifiableEntity entity : toRemove) { - pendingUpdateTasks.remove(entity); - } - } - - @Override - public void beforeDBBulkUpdateOrRemove(Class entityType) { - beforeDBSearch(entityType); - Set toRemove = new HashSet(); - - for (Map.Entry entry : loadedObjects.entrySet()) { - MongoIdentifiableEntity entity = entry.getValue(); - if (entity.getClass().equals(entityType)) { - toRemove.add(entry.getKey()); - } - } - - // Now remove all loadedObjects - for (String objectId : toRemove) { - loadedObjects.remove(objectId); - } - } - - @Override - public void begin() { - loadedObjects.clear(); - pendingUpdateTasks.clear(); - } - - @Override - public void commit() { - // Now execute all pending update tasks - for (Set mongoTasks : pendingUpdateTasks.values()) { - for (MongoTask currentTask : mongoTasks) { - currentTask.execute(); - } - } - - // And clear it - loadedObjects.clear(); - pendingUpdateTasks.clear(); - } - - @Override - public void rollback() { - // Just clear the map without executions of tasks TODO: Attempt to do complete rollback (removal of created objects, restoring of removed objects, rollback of updates) - loadedObjects.clear(); - pendingUpdateTasks.clear(); - } - - @Override - public MongoStore getMongoStore() { - return mongoStore; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListMapper.java deleted file mode 100755 index 98cc65ab14b..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListMapper.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBList; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Marek Posolda - */ -public class BasicDBListMapper implements Mapper { - - private final MapperRegistry mapperRegistry; - - public BasicDBListMapper(MapperRegistry mapperRegistry) { - this.mapperRegistry = mapperRegistry; - } - - @Override - public List convertObject(MapperContext context) { - BasicDBList dbList = context.getObjectToConvert(); - ArrayList appObjects = new ArrayList(); - Class expectedListElementType = (Class) context.getGenericTypes().get(0); - - for (Object dbObject : dbList) { - MapperContext newContext = new MapperContext(dbObject, expectedListElementType, null); - appObjects.add(mapperRegistry.convertDBObjectToApplicationObject(newContext)); - } - return appObjects; - } - - @Override - public Class getTypeOfObjectToConvert() { - return BasicDBList.class; - } - - @Override - public Class getExpectedReturnType() { - return List.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListToSetMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListToSetMapper.java deleted file mode 100644 index 5bb3fea6863..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBListToSetMapper.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBList; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author Marek Posolda - */ -public class BasicDBListToSetMapper implements Mapper { - - private final MapperRegistry mapperRegistry; - - public BasicDBListToSetMapper(MapperRegistry mapperRegistry) { - this.mapperRegistry = mapperRegistry; - } - - @Override - public Set convertObject(MapperContext context) { - BasicDBList dbList = context.getObjectToConvert(); - Set appObjects = new HashSet(); - Class expectedListElementType = (Class) context.getGenericTypes().get(0); - - for (Object dbObject : dbList) { - MapperContext newContext = new MapperContext(dbObject, expectedListElementType, null); - appObjects.add(mapperRegistry.convertDBObjectToApplicationObject(newContext)); - } - return appObjects; - } - - @Override - public Class getTypeOfObjectToConvert() { - return BasicDBList.class; - } - - @Override - public Class getExpectedReturnType() { - return Set.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectMapper.java deleted file mode 100644 index 999d4e536af..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectMapper.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBObject; -import org.jboss.logging.Logger; -import org.keycloak.common.util.reflections.Types; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; -import org.keycloak.connections.mongo.impl.EntityInfo; -import org.keycloak.connections.mongo.impl.MongoStoreImpl; -import org.keycloak.models.utils.reflection.Property; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.List; - -/** - * @author Marek Posolda - */ -public class BasicDBObjectMapper implements Mapper { - - private static final Logger logger = Logger.getLogger(BasicDBObjectMapper.class); - - private final MongoStoreImpl mongoStoreImpl; - private final MapperRegistry mapperRegistry; - private final Class expectedEntityType; - - public BasicDBObjectMapper(MongoStoreImpl mongoStoreImpl, MapperRegistry mapperRegistry, Class expectedEntityType) { - this.mongoStoreImpl = mongoStoreImpl; - this.mapperRegistry = mapperRegistry; - this.expectedEntityType = expectedEntityType; - } - - @Override - public S convertObject(MapperContext context) { - BasicDBObject dbObject = context.getObjectToConvert(); - if (dbObject == null) { - return null; - } - - EntityInfo entityInfo = mongoStoreImpl.getEntityInfo(expectedEntityType); - - S entity; - try { - entity = expectedEntityType.newInstance(); - } catch (Exception e) { - throw new RuntimeException(e); - } - - for (String key : dbObject.keySet()) { - Object value = dbObject.get(key); - Property property; - - if ("_id".equals(key)) { - // Current property is "id" - if (entity instanceof MongoIdentifiableEntity) { - ((MongoIdentifiableEntity)entity).setId(value.toString()); - } - - } else if ((property = entityInfo.getPropertyByName(key)) != null) { - // It's declared property with @DBField annotation - setPropertyValue(entity, value, property); - - } else { - // Show warning if it's unknown - logger.warn("Property with key " + key + " not known for type " + expectedEntityType); - } - } - - return entity; - } - - private void setPropertyValue(Object entity, Object valueFromDB, Property property) { - if (valueFromDB == null) { - property.setValue(entity, null); - return; - } - - MapperContext context; - - Type type = property.getBaseType(); - - // This can be the case when we have parameterized type (like "List") - if (type instanceof ParameterizedType) { - ParameterizedType parameterized = (ParameterizedType) type; - Type[] genericTypeArguments = parameterized.getActualTypeArguments(); - - List genericTypes = Arrays.asList(genericTypeArguments); - - Class expectedReturnType = (Class)parameterized.getRawType(); - context = new MapperContext(valueFromDB, expectedReturnType, genericTypes); - } else { - Class expectedReturnType = (Class)type; - // handle primitives - expectedReturnType = Types.boxedClass(expectedReturnType); - context = new MapperContext(valueFromDB, expectedReturnType, null); - } - - Object appObject = mapperRegistry.convertDBObjectToApplicationObject(context); - - if (Types.boxedClass(property.getJavaClass()).isAssignableFrom(appObject.getClass())) { - property.setValue(entity, appObject); - } else { - throw new IllegalStateException("Converted object " + appObject + " is not of type " + context.getExpectedReturnType() + - ". So can't be assigned as property " + property.getName() + " of " + entity.getClass()); - } - } - - @Override - public Class getTypeOfObjectToConvert() { - return BasicDBObject.class; - } - - @Override - public Class getExpectedReturnType() { - return expectedEntityType; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectToMapMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectToMapMapper.java deleted file mode 100644 index 7d91f6f835b..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/BasicDBObjectToMapMapper.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBObject; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Marek Posolda - */ -public class BasicDBObjectToMapMapper implements Mapper { - - private final MapperRegistry mapperRegistry; - - public BasicDBObjectToMapMapper(MapperRegistry mapperRegistry) { - this.mapperRegistry = mapperRegistry; - } - - @Override - public Map convertObject(MapperContext context) { - BasicDBObject dbObjectToConvert = context.getObjectToConvert(); - Type expectedElementValueType = context.getGenericTypes().get(1); - - HashMap result = new HashMap(); - for (Map.Entry entry : dbObjectToConvert.entrySet()) { - String key = entry.getKey(); - Object dbValue = entry.getValue(); - - // Workaround as manually inserted numbers into mongo may be treated as "Double" - if (dbValue instanceof Double && expectedElementValueType == Integer.class) { - dbValue = ((Double)dbValue).intValue(); - } - - MapperContext newContext = getMapperContext(dbValue, expectedElementValueType); - Object value = mapperRegistry.convertDBObjectToApplicationObject(newContext); - - if (key.contains(MapMapper.DOT_PLACEHOLDER)) { - key = key.replaceAll(MapMapper.DOT_PLACEHOLDER, "."); - } - - result.put(key, value); - } - return result; - } - - @Override - public Class getTypeOfObjectToConvert() { - return BasicDBObject.class; - } - - @Override - public Class getExpectedReturnType() { - return Map.class; - } - - private MapperContext getMapperContext(Object dbValue, Type expectedElementValueType) { - if (expectedElementValueType instanceof Class) { - Class clazz = (Class) expectedElementValueType; - return new MapperContext<>(dbValue, clazz, null); - } else if (expectedElementValueType instanceof ParameterizedType) { - ParameterizedType parameterized = (ParameterizedType) expectedElementValueType; - Class expectedClazz = (Class) parameterized.getRawType(); - Type[] generics = parameterized.getActualTypeArguments(); - - return new MapperContext<>(dbValue, expectedClazz, Arrays.asList(generics)); - } else { - throw new IllegalArgumentException("Unexpected type: '" + expectedElementValueType + "' for converting " + dbValue); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/EnumToStringMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/EnumToStringMapper.java deleted file mode 100644 index b90887c88ad..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/EnumToStringMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; - -/** - * @author Marek Posolda - */ -public class EnumToStringMapper implements Mapper { - - @Override - public String convertObject(MapperContext context) { - Enum objectToConvert = context.getObjectToConvert(); - - return objectToConvert.toString(); - } - - @Override - public Class getTypeOfObjectToConvert() { - return Enum.class; - } - - @Override - public Class getExpectedReturnType() { - return String.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/ListMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/ListMapper.java deleted file mode 100755 index 5b59229cde6..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/ListMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBList; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; - -import java.util.Collection; - -/** - * @author Marek Posolda - */ -public class ListMapper implements Mapper { - - private final MapperRegistry mapperRegistry; - private final Class listType; - - public ListMapper(MapperRegistry mapperRegistry, Class listType) { - this.mapperRegistry = mapperRegistry; - this.listType = listType; - } - - @Override - public BasicDBList convertObject(MapperContext context) { - T appObjectsList = context.getObjectToConvert(); - - BasicDBList dbObjects = new BasicDBList(); - for (Object appObject : appObjectsList) { - Object dbObject = mapperRegistry.convertApplicationObjectToDBObject(appObject, Object.class); - - dbObjects.add(dbObject); - } - return dbObjects; - } - - @Override - public Class getTypeOfObjectToConvert() { - return listType; - } - - @Override - public Class getExpectedReturnType() { - return BasicDBList.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MapMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MapMapper.java deleted file mode 100644 index be58508405b..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MapMapper.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBObject; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; - -import java.util.Map; -import java.util.Set; - -/** - * For now, we support just convert from Map - * - * @author Marek Posolda - */ -public class MapMapper implements Mapper { - - // Just some dummy way of encoding . character as it's not allowed by mongo in key fields - static final String DOT_PLACEHOLDER = "###"; - - private final MapperRegistry mapperRegistry; - private final Class mapType; - - public MapMapper(MapperRegistry mapperRegistry, Class mapType) { - this.mapperRegistry = mapperRegistry; - this.mapType = mapType; - } - - @Override - public BasicDBObject convertObject(MapperContext context) { - T mapToConvert = context.getObjectToConvert(); - return convertMap(mapToConvert, mapperRegistry); - } - - public static BasicDBObject convertMap(Map mapToConvert, MapperRegistry mapperRegistry) { - BasicDBObject dbObject = new BasicDBObject(); - Set entries = mapToConvert.entrySet(); - for (Map.Entry entry : entries) { - String key = (String)entry.getKey(); - Object value = entry.getValue(); - - Object dbValue = mapperRegistry==null ? entry.getValue() : mapperRegistry.convertApplicationObjectToDBObject(value, Object.class); - - if (key.contains(".")) { - key = key.replaceAll("\\.", DOT_PLACEHOLDER); - } - - dbObject.put(key, dbValue); - } - return dbObject; - } - - @Override - public Class getTypeOfObjectToConvert() { - return mapType; - } - - @Override - public Class getExpectedReturnType() { - return BasicDBObject.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MongoEntityMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MongoEntityMapper.java deleted file mode 100755 index 67849f4d072..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/MongoEntityMapper.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import com.mongodb.BasicDBObject; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; -import org.keycloak.connections.mongo.api.types.MapperRegistry; -import org.keycloak.connections.mongo.impl.EntityInfo; -import org.keycloak.connections.mongo.impl.MongoStoreImpl; -import org.keycloak.models.utils.reflection.Property; - -import java.util.Collection; - -/** - * @author Marek Posolda - */ -public class MongoEntityMapper implements Mapper { - - private final MongoStoreImpl mongoStoreImpl; - private final MapperRegistry mapperRegistry; - private final Class expectedMongoEntityType; - - public MongoEntityMapper(MongoStoreImpl mongoStoreImpl, MapperRegistry mapperRegistry, Class expectedMongoEntityType) { - this.mongoStoreImpl = mongoStoreImpl; - this.mapperRegistry = mapperRegistry; - this.expectedMongoEntityType = expectedMongoEntityType; - } - - @Override - public BasicDBObject convertObject(MapperContext context) { - T applicationObject = context.getObjectToConvert(); - - EntityInfo entityInfo = mongoStoreImpl.getEntityInfo(applicationObject.getClass()); - - // Create instance of BasicDBObject and add all declared properties to it - BasicDBObject dbObject = new BasicDBObject(); - Collection> props = entityInfo.getProperties(); - for (Property property : props) { - String propName = property.getName(); - - // Ignore "id" property - if (!"id".equals(propName) || !(applicationObject instanceof MongoIdentifiableEntity)) { - Object propValue = property.getValue(applicationObject); - if (propValue != null) { - Object dbValue = propValue == null ? null : mapperRegistry.convertApplicationObjectToDBObject(propValue, Object.class); - dbObject.put(propName, dbValue); - } - } - } - - return dbObject; - } - - @Override - public Class getTypeOfObjectToConvert() { - return expectedMongoEntityType; - } - - @Override - public Class getExpectedReturnType() { - return BasicDBObject.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/SimpleMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/SimpleMapper.java deleted file mode 100644 index 007257cb3f3..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/SimpleMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; - -/** - * Just returns input - * - * @author Marek Posolda - */ -public class SimpleMapper implements Mapper { - - private final Class expectedType; - - public SimpleMapper(Class expectedType) { - this.expectedType = expectedType; - } - - @Override - public T convertObject(MapperContext context) { - T objectToConvert = context.getObjectToConvert(); - return objectToConvert; - } - - @Override - public Class getTypeOfObjectToConvert() { - return expectedType; - } - - @Override - public Class getExpectedReturnType() { - return expectedType; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/StringToEnumMapper.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/StringToEnumMapper.java deleted file mode 100644 index 4a8cb416075..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/impl/types/StringToEnumMapper.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.impl.types; - -import org.keycloak.connections.mongo.api.types.Mapper; -import org.keycloak.connections.mongo.api.types.MapperContext; - -/** - * @author Marek Posolda - */ -public class StringToEnumMapper implements Mapper { - - @Override - public Enum convertObject(MapperContext context) { - String enumValue = context.getObjectToConvert(); - - Class clazz = context.getExpectedReturnType(); - return Enum.valueOf(clazz, enumValue); - } - - @Override - public Class getTypeOfObjectToConvert() { - return String.class; - } - - @Override - public Class getExpectedReturnType() { - return Enum.class; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProvider.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProvider.java deleted file mode 100644 index a11f729d60b..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProvider.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.lock; - -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCursor; -import com.mongodb.DBObject; -import com.mongodb.DuplicateKeyException; -import com.mongodb.WriteResult; -import org.jboss.logging.Logger; -import org.keycloak.common.util.HostUtils; -import org.keycloak.common.util.Time; -import org.keycloak.models.dblock.DBLockProvider; - -/** - * @author Marek Posolda - */ -public class MongoDBLockProvider implements DBLockProvider { - - private static final String DB_LOCK_COLLECTION = "dblock"; - private static final Logger logger = Logger.getLogger(MongoDBLockProvider .class); - - private final MongoDBLockProviderFactory factory; - private final DB db; - - public MongoDBLockProvider(MongoDBLockProviderFactory factory, DB db) { - this.factory = factory; - this.db = db; - } - - - @Override - public void waitForLock() { - boolean locked = false; - long startTime = Time.toMillis(Time.currentTime()); - long timeToGiveUp = startTime + (factory.getLockWaitTimeoutMillis()); - - while (!locked && Time.toMillis(Time.currentTime()) < timeToGiveUp) { - locked = acquireLock(); - if (!locked) { - int remainingTime = ((int)(timeToGiveUp / 1000)) - Time.currentTime(); - logger.debugf("Waiting for changelog lock... Remaining time: %d seconds", remainingTime); - try { - Thread.sleep(factory.getLockRecheckTimeMillis()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - if (!locked) { - DBObject query = new BasicDBObject("_id", 1); - DBCursor cursor = db.getCollection(DB_LOCK_COLLECTION).find(query); - String lockedBy; - if (cursor.hasNext()) { - DBObject dbObj = cursor.next(); - lockedBy = dbObj.get("lockedBy") + " since " + Time.toDate(((int)((long) dbObj.get("lockedSince") / 1000))); - } else { - lockedBy = "UNKNOWN"; - } - throw new IllegalStateException("Could not acquire change log lock. Currently locked by " + lockedBy); - } - } - - - private boolean acquireLock() { - DBObject query = new BasicDBObject("locked", false); - - BasicDBObject update = new BasicDBObject("locked", true); - update.append("_id", 1); - update.append("lockedSince", Time.toMillis(Time.currentTime())); - update.append("lockedBy", HostUtils.getHostName()); // Maybe replace with something better, but doesn't matter for now - - try { - WriteResult wr = db.getCollection(DB_LOCK_COLLECTION).update(query, update, true, false); - if (wr.getN() == 1) { - logger.debugf("Successfully acquired DB lock"); - factory.setHasLock(true); - return true; - } else { - return false; - } - } catch (DuplicateKeyException dke) { - logger.debugf("Failed acquire lock. Reason: %s", dke.getMessage()); - } - - return false; - } - - - @Override - public void releaseLock() { - DBObject query = new BasicDBObject("locked", true); - - BasicDBObject update = new BasicDBObject("locked", false); - update.append("_id", 1); - update.append("lockedBy", null); - update.append("lockedSince", null); - - try { - WriteResult wr = db.getCollection(DB_LOCK_COLLECTION).update(query, update, true, false); - if (wr.getN() > 0) { - factory.setHasLock(false); - logger.debugf("Successfully released DB lock"); - } else { - logger.warnf("Attempt to release DB lock, but nothing was released"); - } - } catch (DuplicateKeyException dke) { - logger.debugf("Failed release lock. Reason: %s", dke.getMessage()); - } - } - - @Override - public boolean hasLock() { - return factory.hasLock(); - } - - @Override - public boolean supportsForcedUnlock() { - return true; - } - - @Override - public void destroyLockInfo() { - db.getCollection(DB_LOCK_COLLECTION).remove(new BasicDBObject()); - logger.debugf("Destroyed lock collection"); - } - - @Override - public void close() { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProviderFactory.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProviderFactory.java deleted file mode 100644 index 19d536b809f..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/lock/MongoDBLockProviderFactory.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.lock; - -import com.mongodb.DB; -import org.jboss.logging.Logger; -import org.keycloak.Config; -import org.keycloak.common.util.Time; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.connections.mongo.MongoConnectionProviderFactory; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.dblock.DBLockProviderFactory; - -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @author Marek Posolda - */ -public class MongoDBLockProviderFactory implements DBLockProviderFactory { - - private static final Logger logger = Logger.getLogger(MongoDBLockProviderFactory.class); - - private long lockRecheckTimeMillis; - private long lockWaitTimeoutMillis; - - // True if this node has a lock acquired - private AtomicBoolean hasLock = new AtomicBoolean(false); - - protected long getLockRecheckTimeMillis() { - return lockRecheckTimeMillis; - } - - protected long getLockWaitTimeoutMillis() { - return lockWaitTimeoutMillis; - } - - @Override - public void init(Config.Scope config) { - int lockRecheckTime = config.getInt("lockRecheckTime", 2); - int lockWaitTimeout = config.getInt("lockWaitTimeout", 900); - this.lockRecheckTimeMillis = Time.toMillis(lockRecheckTime); - this.lockWaitTimeoutMillis = Time.toMillis(lockWaitTimeout); - logger.debugf("Mongo lock provider configured with lockWaitTime: %d seconds, lockRecheckTime: %d seconds", lockWaitTimeout, lockRecheckTime); - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - - @Override - public MongoDBLockProvider create(KeycloakSession session) { - MongoConnectionProviderFactory mongoConnectionFactory = (MongoConnectionProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(MongoConnectionProvider.class); - DB db = mongoConnectionFactory.getDBBeforeUpdate(); - return new MongoDBLockProvider(this, db); - } - - @Override - public void setTimeouts(long lockRecheckTimeMillis, long lockWaitTimeoutMillis) { - this.lockRecheckTimeMillis = lockRecheckTimeMillis; - this.lockWaitTimeoutMillis = lockWaitTimeoutMillis; - } - - @Override - public void close() { - - } - - @Override - public String getId() { - return "mongo"; - } - - public boolean hasLock() { - return hasLock.get(); - } - - public void setHasLock(boolean hasLock) { - this.hasLock.set(hasLock); - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProvider.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProvider.java deleted file mode 100644 index e7224c96637..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater; - -import com.mongodb.DB; -import org.keycloak.models.KeycloakSession; -import org.keycloak.provider.Provider; - -/** - * @author Stian Thorgersen - */ -public interface MongoUpdaterProvider extends Provider { - - void update(KeycloakSession session, DB db); - - void validate(KeycloakSession session, DB db); - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProviderFactory.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProviderFactory.java deleted file mode 100644 index 8eccea04179..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterProviderFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater; - -import org.keycloak.provider.ProviderFactory; - -/** - * @author Stian Thorgersen - */ -public interface MongoUpdaterProviderFactory extends ProviderFactory { -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterSpi.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterSpi.java deleted file mode 100644 index 17c290f8930..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/MongoUpdaterSpi.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater; - -import org.keycloak.provider.Provider; -import org.keycloak.provider.ProviderFactory; -import org.keycloak.provider.Spi; - -/** - * @author Stian Thorgersen - */ -public class MongoUpdaterSpi implements Spi { - - @Override - public boolean isInternal() { - return true; - } - - @Override - public String getName() { - return "connectionsMongoUpdater"; - } - - @Override - public Class getProviderClass() { - return MongoUpdaterProvider.class; - } - - @Override - public Class getProviderFactoryClass() { - return MongoUpdaterProviderFactory.class; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProvider.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProvider.java deleted file mode 100755 index c82531bd842..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProvider.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl; - -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.jboss.logging.Logger; -import org.keycloak.connections.mongo.updater.MongoUpdaterProvider; -import org.keycloak.connections.mongo.updater.impl.updates.Update; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_0_0_Final; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_1_0_Beta1; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_2_0_Beta1; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_2_0_CR1; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_3_0; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_4_0; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_7_0; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_8_0; -import org.keycloak.connections.mongo.updater.impl.updates.Update1_9_2; -import org.keycloak.connections.mongo.updater.impl.updates.Update2_3_0; -import org.keycloak.connections.mongo.updater.impl.updates.Update2_4_0; -import org.keycloak.connections.mongo.updater.impl.updates.Update2_5_0; -import org.keycloak.models.KeycloakSession; - -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -/** - * @author Stian Thorgersen - */ -public class DefaultMongoUpdaterProvider implements MongoUpdaterProvider { - - public static final Logger log = Logger.getLogger(DefaultMongoUpdaterProvider.class); - - public static final String CHANGE_LOG_COLLECTION = "databaseChangeLog"; - - private Class[] updates = new Class[]{ - Update1_0_0_Final.class, - Update1_1_0_Beta1.class, - Update1_2_0_Beta1.class, - Update1_2_0_CR1.class, - Update1_3_0.class, - Update1_4_0.class, - Update1_7_0.class, - Update1_8_0.class, - Update1_9_2.class, - Update2_3_0.class, - Update2_4_0.class, - Update2_5_0.class - }; - - @Override - public void update(KeycloakSession session, DB db) { - log.debug("Starting database update"); - try { - boolean changeLogExists = db.collectionExists(CHANGE_LOG_COLLECTION); - DBCollection changeLog = db.getCollection(CHANGE_LOG_COLLECTION); - - List executed = getExecuted(db, changeLogExists, changeLog); - List updatesToRun = getUpdatesToRun(executed); - - if (!updatesToRun.isEmpty()) { - if (executed.isEmpty()) { - log.info("Initializing database schema"); - } else { - if (log.isDebugEnabled()) { - log.debugv("Updating database from {0} to {1}", executed.get(executed.size() - 1), updatesToRun.get(updatesToRun.size() - 1).getId()); - } else { - log.info("Updating database"); - } - } - - int order = executed.size(); - for (Update u : updatesToRun) { - log.debugv("Executing updates for {0}", u.getId()); - - u.setLog(log); - u.setDb(db); - u.update(session); - - createLog(changeLog, u, ++order); - - log.debugv("Completed updates for {0}", u.getId()); - } - log.debug("Completed database update"); - } else { - log.debug("Skip database update. Database is already up to date"); - } - } catch (Exception e) { - throw new RuntimeException("Failed to update database", e); - } - } - - - @Override - public void validate(KeycloakSession session, DB db) { - log.debug("Validating database"); - - boolean changeLogExists = db.collectionExists(CHANGE_LOG_COLLECTION); - DBCollection changeLog = db.getCollection(CHANGE_LOG_COLLECTION); - - List executed = getExecuted(db, changeLogExists, changeLog); - List updatesToRun = getUpdatesToRun(executed); - - if (!updatesToRun.isEmpty()) { - String errorMessage = (executed.isEmpty()) - ? "Failed to validate Mongo database schema. Database is empty. Please change databaseSchema to 'update'" - : String.format("Failed to validate Mongo database schema. Schema needs updating database from %s to %s. Please change databaseSchema to 'update'", - executed.get(executed.size() - 1), updatesToRun.get(updatesToRun.size() - 1).getId()); - - throw new RuntimeException(errorMessage); - } else { - log.debug("Validation passed. Database is up to date"); - } - } - - - private List getExecuted(DB db, boolean changeLogExists, DBCollection changeLog) { - boolean realmExists = db.collectionExists("realms"); - - List executed = new LinkedList<>(); - if (!changeLogExists && realmExists) { - Update1_0_0_Final u = new Update1_0_0_Final(); - executed.add(u.getId()); - createLog(changeLog, u, 1); - } else if (changeLogExists) { - DBCursor cursor = changeLog.find().sort(new BasicDBObject("orderExecuted", 1)); - while (cursor.hasNext()) { - executed.add((String) cursor.next().get("_id")); - } - } - return executed; - } - - - private List getUpdatesToRun(List executed) { - try { - List updatesToRun = new LinkedList<>(); - for (Class updateClass : updates) { - Update u = updateClass.newInstance(); - if (!executed.contains(u.getId())) { - updatesToRun.add(u); - } - } - return updatesToRun; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - - private void createLog(DBCollection changeLog, Update update, int orderExecuted) { - changeLog.insert(new BasicDBObject("_id", update.getId()).append("dateExecuted", new Date()).append("orderExecuted", orderExecuted)); - } - - - @Override - public void close() { - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProviderFactory.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProviderFactory.java deleted file mode 100755 index 2554bb771a5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/DefaultMongoUpdaterProviderFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl; - -import org.keycloak.Config; -import org.keycloak.connections.mongo.updater.MongoUpdaterProvider; -import org.keycloak.connections.mongo.updater.MongoUpdaterProviderFactory; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; - -/** - * @author Stian Thorgersen - */ -public class DefaultMongoUpdaterProviderFactory implements MongoUpdaterProviderFactory { - - @Override - public MongoUpdaterProvider create(KeycloakSession session) { - return new DefaultMongoUpdaterProvider(); - } - - @Override - public void init(Config.Scope config) { - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - @Override - public void close() { - } - - @Override - public String getId() { - return "default"; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/AbstractMigrateUserFedToComponent.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/AbstractMigrateUserFedToComponent.java deleted file mode 100644 index d4db6d32090..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/AbstractMigrateUserFedToComponent.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.jboss.logging.Logger; -import org.keycloak.storage.UserStorageProvider; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public abstract class AbstractMigrateUserFedToComponent extends Update { - private final Logger logger = Logger.getLogger(getClass()); - - public void portUserFedToComponent(String providerId) { - DBCollection realms = db.getCollection("realms"); - DBCursor cursor = realms.find(); - while (cursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) cursor.next(); - - String realmId = realm.getString("_id"); - Set removedProviders = new HashSet<>(); - - BasicDBList componentEntities = (BasicDBList) realm.get("componentEntities"); - BasicDBList federationProviders = (BasicDBList) realm.get("userFederationProviders"); - for (Object obj : federationProviders) { - BasicDBObject fedProvider = (BasicDBObject)obj; - if (fedProvider.getString("providerName").equals(providerId)) { - String id = fedProvider.getString("id"); - removedProviders.add(id); - int priority = fedProvider.getInt("priority"); - String displayName = fedProvider.getString("displayName"); - int fullSyncPeriod = fedProvider.getInt("fullSyncPeriod"); - int changedSyncPeriod = fedProvider.getInt("changedSyncPeriod"); - int lastSync = fedProvider.getInt("lastSync"); - BasicDBObject component = new BasicDBObject(); - component.put("id", id); - component.put("name", displayName); - component.put("providerType", UserStorageProvider.class.getName()); - component.put("providerId", providerId); - component.put("parentId", realmId); - - BasicDBObject config = new BasicDBObject(); - config.put("priority", Collections.singletonList(Integer.toString(priority))); - config.put("fullSyncPeriod", Collections.singletonList(Integer.toString(fullSyncPeriod))); - config.put("changedSyncPeriod", Collections.singletonList(Integer.toString(changedSyncPeriod))); - config.put("lastSync", Collections.singletonList(Integer.toString(lastSync))); - - BasicDBObject fedConfig = (BasicDBObject)fedProvider.get("config"); - if (fedConfig != null) { - for (Map.Entry attr : new HashSet<>(fedConfig.entrySet())) { - String attrName = attr.getKey(); - String attrValue = attr.getValue().toString(); - config.put(attrName, Collections.singletonList(attrValue)); - - } - } - - - component.put("config", config); - - componentEntities.add(component); - - } - } - Iterator it = federationProviders.iterator(); - while (it.hasNext()) { - BasicDBObject fedProvider = (BasicDBObject)it.next(); - String id = fedProvider.getString("id"); - if (removedProviders.contains(id)) { - it.remove(); - } - - } - realms.update(new BasicDBObject().append("_id", realmId), realm); - } - } - - public void portUserFedMappersToComponent(String providerId, String mapperType) { - //logger.info("*** port mappers"); - DBCollection realms = db.getCollection("realms"); - DBCursor cursor = realms.find(); - while (cursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) cursor.next(); - - String realmId = realm.getString("_id"); - Set removedProviders = new HashSet<>(); - - BasicDBList componentEntities = (BasicDBList) realm.get("componentEntities"); - BasicDBList federationProviders = (BasicDBList) realm.get("userFederationProviders"); - BasicDBList fedMappers = (BasicDBList) realm.get("userFederationMappers"); - for (Object obj : federationProviders) { - BasicDBObject fedProvider = (BasicDBObject)obj; - String providerName = fedProvider.getString("providerName"); - //logger.info("looking for mappers of fed provider: " + providerName); - if (providerName.equals(providerId)) { - String id = fedProvider.getString("id"); - //logger.info("found fed provider: " + id + ", looking at mappers"); - for (Object obj2 : fedMappers) { - BasicDBObject fedMapper = (BasicDBObject)obj2; - String federationProviderId = fedMapper.getString("federationProviderId"); - //logger.info("looking at mapper with federationProviderId: " + federationProviderId); - if (federationProviderId.equals(id)) { - String name = fedMapper.getString("name"); - String mapperId = fedMapper.getString("id"); - removedProviders.add(mapperId); - String mapperProviderId = fedMapper.getString("federationMapperType"); - BasicDBObject component = new BasicDBObject(); - component.put("id", mapperId); - component.put("name", name); - component.put("providerType", mapperType); - component.put("providerId", mapperProviderId); - component.put("parentId", id); - - BasicDBObject fedConfig = (BasicDBObject)fedMapper.get("config"); - BasicDBObject config = new BasicDBObject(); - if (fedConfig != null) { - for (Map.Entry attr : new HashSet<>(fedConfig.entrySet())) { - String attrName = attr.getKey(); - String attrValue = attr.getValue().toString(); - config.put(attrName, Collections.singletonList(attrValue)); - - } - } - component.put("config", config); - componentEntities.add(component); - } - } - } - } - Iterator it = fedMappers.iterator(); - while (it.hasNext()) { - BasicDBObject fedMapper = (BasicDBObject)it.next(); - String id = fedMapper.getString("id"); - if (removedProviders.contains(id)) { - it.remove(); - } - - } - realms.update(new BasicDBObject().append("_id", realmId), realm); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update.java deleted file mode 100755 index 7fcc94573e3..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import org.jboss.logging.Logger; -import org.keycloak.models.KeycloakSession; - -import java.util.Arrays; - -/** - * @author Stian Thorgersen - */ -public abstract class Update { - - protected DB db; - - protected Logger log; - - public abstract String getId(); - - public abstract void update(KeycloakSession session) throws ClassNotFoundException; - - protected DBCollection createCollection(String name) { - if (db.collectionExists(name)) { - throw new RuntimeException("Failed to create collection {0}: collection already exists"); - } - - DBCollection col = db.getCollection(name); - log.debugv("Created collection {0}", name); - return col; - } - - protected void ensureIndex(String name, String field, boolean unique, boolean sparse) { - ensureIndex(name, new String[]{field}, unique, sparse); - } - - protected void ensureIndex(String name, String[] fields, boolean unique, boolean sparse) { - DBCollection col = db.getCollection(name); - - BasicDBObject o = new BasicDBObject(); - for (String f : fields) { - o.append(f, 1); - } - - col.createIndex(o, new BasicDBObject("unique", unique).append("sparse", sparse)); - log.debugv("Created index {0}, fields={1}, unique={2}, sparse={3}", name, Arrays.toString(fields), unique, sparse); - } - - protected void deleteEntries(String collection) { - db.getCollection(collection).remove(new BasicDBObject()); - log.debugv("Deleted entries from {0}", collection); - } - - protected void removeField(String collection, String field) { - db.getCollection(collection).update(new BasicDBObject(), new BasicDBObject("$unset" , new BasicDBObject(field, 1)), false, true); - } - - protected void renameCollection(String collection, String newName) { - db.getCollection(collection).rename(newName); - } - - public void setLog(Logger log) { - this.log = log; - } - - public void setDb(DB db) { - this.db = db; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_0_0_Final.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_0_0_Final.java deleted file mode 100644 index bf11ad11e99..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_0_0_Final.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import org.keycloak.connections.mongo.updater.impl.DefaultMongoUpdaterProvider; -import org.keycloak.models.KeycloakSession; - -/** - * @author Stian Thorgersen - */ -public class Update1_0_0_Final extends Update { - - @Override - public String getId() { - return "1.0.0.Final"; - } - - @Override - public void update(KeycloakSession session) throws ClassNotFoundException { - DBCollection realmsCollection = db.getCollection("realms"); - realmsCollection.createIndex(new BasicDBObject("name", 1), new BasicDBObject("unique", true)); - - DefaultMongoUpdaterProvider.log.debugv("Created collection {0}", "realms"); - - createCollection("users"); - ensureIndex("users", new String[] { "realmId", "username"}, true, false); - ensureIndex("users", "emailIndex", true, true); - - createCollection("roles"); - ensureIndex("roles", "nameIndex", true, false); - - createCollection("applications"); - ensureIndex("applications", new String[]{"realmId", "name"}, true, false); - - createCollection("oauthClients"); - ensureIndex("oauthClients", new String[] { "realmId", "name"}, true, false); - - createCollection("userFailures"); - - createCollection("sessions"); - - createCollection("clientSessions"); - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_1_0_Beta1.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_1_0_Beta1.java deleted file mode 100644 index 43f73c42818..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_1_0_Beta1.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.utils.KeycloakModelUtils; - -/** - * @author Stian Thorgersen - */ -public class Update1_1_0_Beta1 extends Update { - - @Override - public String getId() { - return "1.1.0.Beta1"; - } - - @Override - public void update(KeycloakSession session) { - deleteEntries("clientSessions"); - deleteEntries("sessions"); - - addRealmCodeSecret(); - } - - private void addRealmCodeSecret() { - DBCollection realms = db.getCollection("realms"); - - DBObject query = new QueryBuilder() - .and("codeSecret").is(null).get(); - - DBCursor objects = realms.find(query); - while (objects.hasNext()) { - DBObject object = objects.next(); - object.put("codeSecret", KeycloakModelUtils.generateCodeSecret()); - realms.save(object); - - log.debugv("Added realm.codeSecret, id={0}", object.get("id")); - } - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_Beta1.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_Beta1.java deleted file mode 100644 index 8097e1c6625..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_Beta1.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.BasicDBObjectBuilder; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.DBObject; -import org.keycloak.Config; -import org.keycloak.connections.mongo.impl.types.MapMapper; -import org.keycloak.migration.MigrationProvider; -import org.keycloak.models.AdminRoles; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.representations.idm.ProtocolMapperRepresentation; - -import java.util.List; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class Update1_2_0_Beta1 extends Update { - - @Override - public String getId() { - return "1.2.0.Beta1"; - } - - @Override - public void update(KeycloakSession session) { - deleteEntries("clientSessions"); - deleteEntries("sessions"); - - convertSocialToIdFedRealms(); - convertSocialToIdFedUsers(); - addAccessCodeLoginTimeout(); - addNewAdminRoles(); - addDefaultProtocolMappers(session); - } - - - private void convertSocialToIdFedRealms() { - DBCollection realms = db.getCollection("realms"); - DBCursor realmsCursor = realms.find(); - - try { - while (realmsCursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) realmsCursor.next(); - boolean updateProfileOnInitialSocialLogin = realm.getBoolean("updateProfileOnInitialSocialLogin"); - BasicDBObject socialConfig = (BasicDBObject) realm.get("socialConfig"); - - BasicDBList identityProviders = (BasicDBList) realm.get("identityProviders"); - if (identityProviders == null) { - identityProviders = new BasicDBList(); - realm.put("identityProviders", identityProviders); - } - - if (socialConfig != null) { - for (Map.Entry entry : socialConfig.entrySet()) { - if (entry.getKey().endsWith("###key")) { - String socialProviderId = entry.getKey().substring(0, entry.getKey().indexOf("###")); - String clientId = (String) entry.getValue(); - String clientSecret = socialConfig.getString(socialProviderId + "###secret"); - - DBObject identityProviderConfig = new BasicDBObjectBuilder() - .add("clientId", clientId) - .add("clientSecret", clientSecret).get(); - - DBObject identityProvider = new BasicDBObjectBuilder() - .add("internalId", KeycloakModelUtils.generateId()) - .add("providerId", socialProviderId) - .add("alias", socialProviderId) - .add("updateProfileFirstLogin", updateProfileOnInitialSocialLogin) - .add("enabled", true) - .add("storeToken", false) - .add("authenticateByDefault", false) - .add("config", identityProviderConfig).get(); - - identityProviders.add(identityProvider); - log.debugv("Converted social provider {0} to identity provider", socialProviderId); - } - } - } - - // Remove obsolete keys from realm - realm.remove("social"); - realm.remove("updateProfileOnInitialSocialLogin"); - realm.remove("socialConfig"); - - // Update realm in DB now - realms.save(realm); - - log.debugv("Social providers of realm {0} converted to identity providers", realm.get("_id")); - } - } finally { - realmsCursor.close(); - } - } - - private void convertSocialToIdFedUsers() { - DBCollection users = db.getCollection("users"); - DBCursor usersCursor = users.find(); - - try { - while (usersCursor.hasNext()) { - BasicDBObject user = (BasicDBObject) usersCursor.next(); - - BasicDBList socialLinks = (BasicDBList) user.get("socialLinks"); - if (socialLinks != null) { - BasicDBList federatedIdentities = (BasicDBList) user.get("federatedIdentities"); - if (federatedIdentities == null) { - federatedIdentities = new BasicDBList(); - user.put("federatedIdentities", federatedIdentities); - } - - for (Object socialLinkObj : socialLinks) { - BasicDBObject socialLink = (BasicDBObject) socialLinkObj; - BasicDBObject idFedLink = new BasicDBObject(); - idFedLink.put("userName", socialLink.get("socialUsername")); - idFedLink.put("userId", socialLink.get("socialUserId")); - idFedLink.put("identityProvider", socialLink.get("socialProvider")); - - federatedIdentities.add(idFedLink); - } - - // Remove obsolete keys and save user - user.remove("socialLinks"); - users.save(user); - - if (log.isTraceEnabled()) { - log.tracev("Social links of user {0} converted to identity links", user.get("_id")); - } - } - } - } finally { - usersCursor.close(); - } - - log.debug("Social links of users converted to identity links"); - } - - private void addAccessCodeLoginTimeout() { - DBCollection realms = db.getCollection("realms"); - DBCursor realmsCursor = realms.find(); - - try { - while (realmsCursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) realmsCursor.next(); - realm.put("accessCodeLifespanLogin", 1800); - realms.save(realm); - } - } finally { - realmsCursor.close(); - } - } - - private void addNewAdminRoles() { - DBCollection realms = db.getCollection("realms"); - String adminRealmName = Config.getAdminRealm(); - - DBCursor realmsCursor = realms.find(); - try { - while (realmsCursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) realmsCursor.next(); - if (adminRealmName.equals(realm.get("name"))) { - addNewAdminRolesToMasterRealm(realm); - } else { - addNewAdminRolesToRealm(realm); - } - } - } finally { - realmsCursor.close(); - } - } - - private void addNewAdminRolesToMasterRealm(BasicDBObject adminRealm) { - DBCollection realms = db.getCollection("realms"); - DBCollection applications = db.getCollection("applications"); - DBCollection roles = db.getCollection("roles"); - - DBCursor realmsCursor = realms.find(); - try { - while (realmsCursor.hasNext()) { - BasicDBObject currentRealm = (BasicDBObject) realmsCursor.next(); - String masterAdminAppName = currentRealm.getString("name") + "-realm"; - - BasicDBObject masterAdminApp = (BasicDBObject) applications.findOne(new BasicDBObject().append("realmId", adminRealm.get("_id")).append("name", masterAdminAppName)); - - String viewIdProvidersRoleId = insertApplicationRole(roles, AdminRoles.VIEW_IDENTITY_PROVIDERS, masterAdminApp.getString("_id")); - String manageIdProvidersRoleId = insertApplicationRole(roles, AdminRoles.MANAGE_IDENTITY_PROVIDERS, masterAdminApp.getString("_id")); - - BasicDBObject adminRole = (BasicDBObject) roles.findOne(new BasicDBObject().append("realmId", adminRealm.get("_id")).append("name", AdminRoles.ADMIN)); - BasicDBList adminCompositeRoles = (BasicDBList) adminRole.get("compositeRoleIds"); - adminCompositeRoles.add(viewIdProvidersRoleId); - adminCompositeRoles.add(manageIdProvidersRoleId); - roles.save(adminRole); - - log.debugv("Added roles {0} and {1} to application {2}", AdminRoles.VIEW_IDENTITY_PROVIDERS, AdminRoles.MANAGE_IDENTITY_PROVIDERS, masterAdminAppName); - } - } finally { - realmsCursor.close(); - } - } - - private void addNewAdminRolesToRealm(BasicDBObject currentRealm) { - DBCollection applications = db.getCollection("applications"); - DBCollection roles = db.getCollection("roles"); - - BasicDBObject adminApp = (BasicDBObject) applications.findOne(new BasicDBObject().append("realmId", currentRealm.get("_id")).append("name", "realm-management")); - - String viewIdProvidersRoleId = insertApplicationRole(roles, AdminRoles.VIEW_IDENTITY_PROVIDERS, adminApp.getString("_id")); - String manageIdProvidersRoleId = insertApplicationRole(roles, AdminRoles.MANAGE_IDENTITY_PROVIDERS, adminApp.getString("_id")); - - BasicDBObject adminRole = (BasicDBObject) roles.findOne(new BasicDBObject().append("applicationId", adminApp.get("_id")).append("name", AdminRoles.REALM_ADMIN)); - BasicDBList adminCompositeRoles = (BasicDBList) adminRole.get("compositeRoleIds"); - adminCompositeRoles.add(viewIdProvidersRoleId); - adminCompositeRoles.add(manageIdProvidersRoleId); - - roles.save(adminRole); - log.debugv("Added roles {0} and {1} to application realm-management of realm {2}", AdminRoles.VIEW_IDENTITY_PROVIDERS, AdminRoles.MANAGE_IDENTITY_PROVIDERS, currentRealm.get("name")); - } - - private void addDefaultProtocolMappers(KeycloakSession session) { - addDefaultMappers(session, db.getCollection("applications")); - addDefaultMappers(session, db.getCollection("oauthClients")); - } - - private void addDefaultMappers(KeycloakSession session, DBCollection clients) { - DBCursor clientsCursor = clients.find(); - try { - while (clientsCursor.hasNext()) { - BasicDBObject currentClient = (BasicDBObject) clientsCursor.next(); - - BasicDBList dbProtocolMappers = new BasicDBList(); - currentClient.put("protocolMappers", dbProtocolMappers); - - Object claimMask = currentClient.get("allowedClaimsMask"); - MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class); - List protocolMappers = migrationProvider.getMappersForClaimMask((Long) claimMask); - - for (ProtocolMapperRepresentation protocolMapper : protocolMappers) { - BasicDBObject dbMapper = new BasicDBObject(); - dbMapper.put("id", KeycloakModelUtils.generateId()); - dbMapper.put("protocol", protocolMapper.getProtocol()); - dbMapper.put("name", protocolMapper.getName()); - dbMapper.put("consentRequired", protocolMapper.isConsentRequired()); - dbMapper.put("consentText", protocolMapper.getConsentText()); - dbMapper.put("protocolMapper", protocolMapper.getProtocolMapper()); - - Map config = protocolMapper.getConfig(); - BasicDBObject dbConfig = MapMapper.convertMap(config, null); - dbMapper.put("config", dbConfig); - - dbProtocolMappers.add(dbMapper); - } - - // Remove obsolete keys from client - currentClient.remove("allowedClaimsMask"); - - log.debugv("Added default mappers to application {1}", currentClient.get("name")); - clients.save(currentClient); - } - } finally { - clientsCursor.close(); - } - } - - private String insertApplicationRole(DBCollection roles, String roleName, String applicationId) { - BasicDBObject role = new BasicDBObject(); - String roleId = KeycloakModelUtils.generateId(); - role.append("_id", roleId); - role.append("name", roleName); - role.append("applicationId", applicationId); - role.append("nameIndex", applicationId + "//" + roleName); - roles.insert(role); - return roleId; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_CR1.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_CR1.java deleted file mode 100644 index b5a5929ce55..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_2_0_CR1.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.models.KeycloakSession; - -/** - * @author Marek Posolda - */ -public class Update1_2_0_CR1 extends Update { - - @Override - public String getId() { - return "1.2.0.CR1"; - } - - @Override - public void update(KeycloakSession session) { - deleteEntries("clientSessions"); - deleteEntries("sessions"); - - convertApplicationsToClients(); - convertOAuthClientsToClients(); - - db.getCollection("realms").update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("adminAppId", "masterAdminClient")), false, true); - - ensureIndex("userConsents", new String[]{"clientId", "userId"}, true, false); - } - - private void convertApplicationsToClients() { - DBCollection applications = db.getCollection("applications"); - applications.dropIndex("realmId_1_name_1"); - - applications.update(new BasicDBObject(), new BasicDBObject("$set", new BasicDBObject("consentRequired", false)), false, true); - applications.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("name", "clientId")), false, true); - renameCollection("applications", "clients"); - log.debugv("Converted applications to clients"); - - DBCollection roles = db.getCollection("roles"); - roles.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("applicationId", "clientId")), false, true); - log.debugv("Renamed roles.applicationId to roles.clientId"); - - ensureIndex("clients", new String[]{"realmId", "clientId"}, true, false); - } - - private void convertOAuthClientsToClients() { - DBCollection clients = db.getCollection("clients"); - DBCollection oauthClients = db.getCollection("oauthClients"); - oauthClients.dropIndex("realmId_1_name_1"); - - oauthClients.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("name", "clientId")), false, true); - oauthClients.update(new BasicDBObject(), new BasicDBObject("$set", new BasicDBObject("consentRequired", true)), false, true); - - DBCursor curs = oauthClients.find(); - while (curs.hasNext()) { - clients.insert(curs.next()); - } - - oauthClients.drop(); - log.debugv("Converted oauthClients to clients"); - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_3_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_3_0.java deleted file mode 100644 index 61acd98e989..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_3_0.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.models.KeycloakSession; -import org.keycloak.representations.idm.IdentityProviderRepresentation; - -/** - * @author Marek Posolda - */ -public class Update1_3_0 extends Update { - - @Override - public String getId() { - return "1.3.0"; - } - - @Override - public void update(KeycloakSession session) { - deleteEntries("clientSessions"); - deleteEntries("sessions"); - - removeField("realms", "passwordCredentialGrantAllowed"); - - updateIdentityProviders(); - } - - private void updateIdentityProviders() { - DBCollection realms = db.getCollection("realms"); - DBCursor realmsCursor = realms.find(); - - try { - while (realmsCursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) realmsCursor.next(); - - BasicDBList identityProviders = (BasicDBList) realm.get("identityProviders"); - if (identityProviders != null) { - for (Object ipObj : identityProviders) { - BasicDBObject identityProvider = (BasicDBObject) ipObj; - - boolean updateProfileFirstLogin = identityProvider.getBoolean("updateProfileFirstLogin"); - String upflMode = updateProfileFirstLogin ? IdentityProviderRepresentation.UPFLM_ON : IdentityProviderRepresentation.UPFLM_OFF; - identityProvider.put("updateProfileFirstLoginMode", upflMode); - identityProvider.removeField("updateProfileFirstLogin"); - - identityProvider.put("trustEmail", false); - } - } - - realms.save(realm); - } - } finally { - realmsCursor.close(); - } - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_4_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_4_0.java deleted file mode 100755 index 774410cab3c..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_4_0.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.models.KeycloakSession; - -import java.util.HashSet; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class Update1_4_0 extends Update { - - @Override - public String getId() { - return "1.4.0"; - } - - @Override - public void update(KeycloakSession session) throws ClassNotFoundException { - deleteEntries("clientSessions"); - deleteEntries("sessions"); - - // Remove warning - removeField("realms", "authenticators"); - - updateUserAttributes(); - } - - private void updateUserAttributes() { - DBCollection users = db.getCollection("users"); - DBCursor usersCursor = users.find(); - - try { - while (usersCursor.hasNext()) { - BasicDBObject user = (BasicDBObject) usersCursor.next(); - - BasicDBObject attributes = (BasicDBObject) user.get("attributes"); - if (attributes != null) { - for (Map.Entry attr : new HashSet<>(attributes.entrySet())) { - String attrName = attr.getKey(); - Object attrValue = attr.getValue(); - if (attrValue != null && attrValue instanceof String) { - BasicDBList asList = new BasicDBList(); - asList.add(attrValue); - attributes.put(attrName, asList); - } - } - - user.put("attributes", attributes); - - users.save(user); - } - } - } finally { - usersCursor.close(); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_7_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_7_0.java deleted file mode 100644 index e0b25a2c688..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_7_0.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.models.KeycloakSession; - -/** - * @author Marek Posolda - */ -public class Update1_7_0 extends Update { - - @Override - public String getId() { - return "1.7.0"; - } - - @Override - public void update(KeycloakSession session) throws ClassNotFoundException { - DBCollection clients = db.getCollection("clients"); - DBCursor clientsCursor = clients.find(); - - try { - while (clientsCursor.hasNext()) { - BasicDBObject client = (BasicDBObject) clientsCursor.next(); - - boolean directGrantsOnly = client.getBoolean("directGrantsOnly", false); - client.append("standardFlowEnabled", !directGrantsOnly); - client.append("implicitFlowEnabled", false); - client.append("directAccessGrantsEnabled", directGrantsOnly); - client.removeField("directGrantsOnly"); - - clients.save(client); - } - } finally { - clientsCursor.close(); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_8_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_8_0.java deleted file mode 100644 index 34ffeea054f..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_8_0.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.WriteResult; -import org.keycloak.credential.hash.Pbkdf2PasswordHashProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.UserCredentialModel; - -/** - * @author Marek Posolda - */ -public class Update1_8_0 extends Update { - - @Override - public String getId() { - return "1.8.0"; - } - - @Override - public void update(KeycloakSession session) { - BasicDBList orArgs = new BasicDBList(); - orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD)); - orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD_HISTORY)); - - BasicDBObject elemMatch = new BasicDBObject("$or", orArgs); - elemMatch.put("algorithm", new BasicDBObject("$exists", false)); - - BasicDBObject query = new BasicDBObject("credentials", new BasicDBObject("$elemMatch", elemMatch)); - - BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("credentials.$.algorithm", Pbkdf2PasswordHashProvider.ID)); - - DBCollection users = db.getCollection("users"); - - // Not sure how to do in single query - int countModified = 1; - while (countModified > 0) { - WriteResult wr = users.update(query, update, false, true); - countModified = wr.getN(); - log.debugf("%d credentials modified in current iteration during upgrade to 1.8", countModified); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_9_2.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_9_2.java deleted file mode 100644 index 340887dd107..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update1_9_2.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.WriteResult; -import org.keycloak.credential.hash.Pbkdf2PasswordHashProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.UserCredentialModel; -import org.keycloak.models.utils.HmacOTP; - -/** - * @author Marek Posolda - */ -public class Update1_9_2 extends Update { - - @Override - public String getId() { - return "1.9.2"; - } - - @Override - public void update(KeycloakSession session) { - BasicDBList orArgs = new BasicDBList(); - orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD)); - orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD_HISTORY)); - - BasicDBObject elemMatch = new BasicDBObject("$or", orArgs); - elemMatch.put("algorithm", HmacOTP.HMAC_SHA1); - - BasicDBObject query = new BasicDBObject("credentials", new BasicDBObject("$elemMatch", elemMatch)); - - BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("credentials.$.algorithm", Pbkdf2PasswordHashProvider.ID)); - - DBCollection users = db.getCollection("users"); - - // Not sure how to do in single query - int countModified = 1; - while (countModified > 0) { - WriteResult wr = users.update(query, update, false, true); - countModified = wr.getN(); - log.debugf("%d credentials modified in current iteration during upgrade to 1.8", countModified); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_3_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_3_0.java deleted file mode 100644 index 063676102c5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_3_0.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.keys.KeyProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.mongo.keycloak.entities.ComponentEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.Collections; - -/** - * @author Marek Posolda - */ -public class Update2_3_0 extends Update { - - @Override - public String getId() { - return "2.3.0"; - } - - @Override - public void update(KeycloakSession session) { - - DBCollection realms = db.getCollection("realms"); - DBCursor cursor = realms.find(); - while (cursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) cursor.next(); - - String realmId = realm.getString("_id"); - - String privateKeyPem = realm.getString("privateKeyPem"); - String certificatePem = realm.getString("certificatePem"); - - BasicDBList entities = (BasicDBList) realm.get("componentEntities"); - - BasicDBObject component = new BasicDBObject(); - component.put("id", KeycloakModelUtils.generateId()); - component.put("name", "rsa"); - component.put("providerType", KeyProvider.class.getName()); - component.put("providerId", "rsa"); - component.put("parentId", realmId); - - BasicDBObject config = new BasicDBObject(); - config.put("priority", Collections.singletonList("100")); - config.put("privateKey", Collections.singletonList(privateKeyPem)); - config.put("certificate", Collections.singletonList(certificatePem)); - - component.put("config", config); - - entities.add(component); - - realm.remove("privateKeyPem"); - realm.remove("certificatePem"); - realm.remove("publicKeyPem"); - realm.remove("codeSecret"); - - realms.update(new BasicDBObject().append("_id", realmId), realm); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_4_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_4_0.java deleted file mode 100644 index 883a0519a07..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_4_0.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.jboss.logging.Logger; -import org.keycloak.keys.KeyProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.LDAPConstants; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.storage.UserStorageProvider; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * @author Marek Posolda - */ -public class Update2_4_0 extends AbstractMigrateUserFedToComponent { - - @Override - public String getId() { - return "2.4.0"; - } - - @Override - public void update(KeycloakSession session) { - portUserFedMappersToComponent(LDAPConstants.LDAP_PROVIDER, "org.keycloak.storage.ldap.mappers.LDAPStorageMapper"); - portUserFedToComponent(LDAPConstants.LDAP_PROVIDER); - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_5_0.java b/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_5_0.java deleted file mode 100644 index c95617b4a61..00000000000 --- a/model/mongo/src/main/java/org/keycloak/connections/mongo/updater/impl/updates/Update2_5_0.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.connections.mongo.updater.impl.updates; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.models.KeycloakSession; -import org.keycloak.provider.ProviderFactory; -import org.keycloak.storage.UserStorageProvider; - -import java.util.List; - -/** - * @author Marek Posolda - */ -public class Update2_5_0 extends AbstractMigrateUserFedToComponent { - - @Override - public String getId() { - return "2.5.0"; - } - - @Override - public void update(KeycloakSession session) { - List factories = session.getKeycloakSessionFactory().getProviderFactories(UserStorageProvider.class); - for (ProviderFactory factory : factories) { - portUserFedToComponent(factory.getId()); - } - - DBCollection realms = db.getCollection("realms"); - try (DBCursor realmsCursor = realms.find()) { - while (realmsCursor.hasNext()) { - BasicDBObject realm = (BasicDBObject) realmsCursor.next(); - realm.append("loginWithEmailAllowed", true); - realm.append("duplicateEmailsAllowed", false); - realms.save(realm); - } - } - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoAdminEventQuery.java b/model/mongo/src/main/java/org/keycloak/events/mongo/MongoAdminEventQuery.java deleted file mode 100755 index 9a2e6e441c5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoAdminEventQuery.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.events.mongo; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.events.admin.AdminEvent; -import org.keycloak.events.admin.AdminEventQuery; -import org.keycloak.events.admin.OperationType; -import org.keycloak.events.admin.ResourceType; - -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.regex.Pattern; - -public class MongoAdminEventQuery implements AdminEventQuery{ - - private Integer firstResult; - private Integer maxResults; - private DBCollection audit; - private final BasicDBObject query; - - public MongoAdminEventQuery(DBCollection audit) { - this.audit = audit; - query = new BasicDBObject(); - } - - @Override - public AdminEventQuery realm(String realmId) { - query.put("realmId", realmId); - return this; - } - - @Override - public AdminEventQuery operation(OperationType... operations) { - List operationStrings = new LinkedList(); - for (OperationType e : operations) { - operationStrings.add(e.toString()); - } - query.put("operationType", new BasicDBObject("$in", operationStrings)); - return this; - } - - @Override - public AdminEventQuery resourceType(ResourceType... resourceTypes) { - - List resourceTypeStrings = new LinkedList(); - for (ResourceType e : resourceTypes) { - resourceTypeStrings.add(e.toString()); - } - query.put("resourceType", new BasicDBObject("$in", resourceTypeStrings)); - - return this; - } - - @Override - public AdminEventQuery authRealm(String authRealmId) { - query.put("authRealmId", authRealmId); - return this; - } - - @Override - public AdminEventQuery authClient(String authClientId) { - query.put("authClientId", authClientId); - return this; - } - - @Override - public AdminEventQuery authUser(String authUserId) { - query.put("authUserId", authUserId); - return this; - } - - @Override - public AdminEventQuery authIpAddress(String ipAddress) { - query.put("authIpAddress", ipAddress); - return this; - } - - @Override - public AdminEventQuery resourcePath(String resourcePath) { - query.put("resourcePath", Pattern.compile(resourcePath)); - return this; - } - - @Override - public AdminEventQuery fromTime(Date fromTime) { - BasicDBObject time = query.containsField("time") ? (BasicDBObject) query.get("time") : new BasicDBObject(); - time.append("$gte", fromTime.getTime()); - query.put("time", time); - return this; - } - - @Override - public AdminEventQuery toTime(Date toTime) { - BasicDBObject time = query.containsField("time") ? (BasicDBObject) query.get("time") : new BasicDBObject(); - time.append("$lte", toTime.getTime()); - query.put("time", time); - return this; - } - - @Override - public AdminEventQuery firstResult(int firstResult) { - this.firstResult = firstResult; - return this; - } - - @Override - public AdminEventQuery maxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } - - @Override - public List getResultList() { - DBCursor cur = audit.find(query).sort(new BasicDBObject("time", -1)); - if (firstResult != null) { - cur.skip(firstResult); - } - if (maxResults != null) { - cur.limit(maxResults); - } - - List events = new LinkedList(); - while (cur.hasNext()) { - events.add(MongoEventStoreProvider.convertAdminEvent((BasicDBObject) cur.next())); - } - - return events; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventQuery.java b/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventQuery.java deleted file mode 100755 index d02f9bfe5b1..00000000000 --- a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventQuery.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.events.mongo; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import org.keycloak.events.Event; -import org.keycloak.events.EventQuery; -import org.keycloak.events.EventType; - -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -/** - * @author Stian Thorgersen - */ -public class MongoEventQuery implements EventQuery { - - private Integer firstResult; - private Integer maxResults; - private DBCollection audit; - private final BasicDBObject query; - - public MongoEventQuery(DBCollection audit) { - this.audit = audit; - query = new BasicDBObject(); - } - - @Override - public EventQuery type(EventType... types) { - List eventStrings = new LinkedList(); - for (EventType e : types) { - eventStrings.add(e.toString()); - } - query.put("type", new BasicDBObject("$in", eventStrings)); - return this; - } - - @Override - public EventQuery realm(String realmId) { - query.put("realmId", realmId); - return this; - } - - @Override - public EventQuery client(String clientId) { - query.put("clientId", clientId); - return this; - } - - @Override - public EventQuery user(String userId) { - query.put("userId", userId); - return this; - } - - @Override - public EventQuery fromDate(Date fromDate) { - BasicDBObject time = query.containsField("time") ? (BasicDBObject) query.get("time") : new BasicDBObject(); - time.append("$gte", fromDate.getTime()); - query.put("time", time); - return this; - } - - @Override - public EventQuery toDate(Date toDate) { - BasicDBObject time = query.containsField("time") ? (BasicDBObject) query.get("time") : new BasicDBObject(); - time.append("$lte", toDate.getTime()); - query.put("time", time); - return this; - } - - @Override - public EventQuery ipAddress(String ipAddress) { - query.put("ipAddress", ipAddress); - return this; - } - - @Override - public EventQuery firstResult(int firstResult) { - this.firstResult = firstResult; - return this; - } - - @Override - public EventQuery maxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } - - @Override - public List getResultList() { - DBCursor cur = audit.find(query).sort(new BasicDBObject("time", -1)); - if (firstResult != null) { - cur.skip(firstResult); - } - if (maxResults != null) { - cur.limit(maxResults); - } - - List events = new LinkedList(); - while (cur.hasNext()) { - events.add(MongoEventStoreProvider.convertEvent((BasicDBObject) cur.next())); - } - - return events; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProvider.java b/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProvider.java deleted file mode 100755 index e875c5bc9e5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProvider.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.events.mongo; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBObject; -import org.keycloak.events.Event; -import org.keycloak.events.EventQuery; -import org.keycloak.events.EventStoreProvider; -import org.keycloak.events.EventType; -import org.keycloak.events.admin.AdminEvent; -import org.keycloak.events.admin.AdminEventQuery; -import org.keycloak.events.admin.AuthDetails; -import org.keycloak.events.admin.OperationType; -import org.keycloak.events.admin.ResourceType; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Stian Thorgersen - */ -public class MongoEventStoreProvider implements EventStoreProvider { - - private DBCollection events; - private DBCollection adminEvents; - - public MongoEventStoreProvider(DBCollection events, DBCollection adminEvents) { - this.events = events; - this.adminEvents = adminEvents; - } - - @Override - public EventQuery createQuery() { - return new MongoEventQuery(events); - } - - @Override - public void clear() { - events.remove(new BasicDBObject()); - } - - @Override - public void clear(String realmId) { - events.remove(new BasicDBObject("realmId", realmId)); - } - - @Override - public void clear(String realmId, long olderThan) { - BasicDBObject q = new BasicDBObject(); - q.put("realmId", realmId); - q.put("time", new BasicDBObject("$lt", olderThan)); - events.remove(q); - } - - @Override - public void onEvent(Event event) { - events.insert(convertEvent(event)); - } - - @Override - public AdminEventQuery createAdminQuery() { - return new MongoAdminEventQuery(adminEvents); - } - - @Override - public void clearAdmin() { - adminEvents.remove(new BasicDBObject()); - } - - @Override - public void clearAdmin(String realmId) { - adminEvents.remove(new BasicDBObject("realmId", realmId)); - } - - @Override - public void clearAdmin(String realmId, long olderThan) { - BasicDBObject q = new BasicDBObject(); - q.put("realmId", realmId); - q.put("time", new BasicDBObject("$lt", olderThan)); - adminEvents.remove(q); - } - - @Override - public void onEvent(AdminEvent adminEvent, boolean includeRepresentation) { - adminEvents.insert(convertAdminEvent(adminEvent, includeRepresentation)); - } - - @Override - public void close() { - } - - static DBObject convertEvent(Event event) { - BasicDBObject e = new BasicDBObject(); - e.put("time", event.getTime()); - e.put("type", event.getType().toString()); - e.put("realmId", event.getRealmId()); - e.put("clientId", event.getClientId()); - e.put("userId", event.getUserId()); - e.put("sessionId", event.getSessionId()); - e.put("ipAddress", event.getIpAddress()); - e.put("error", event.getError()); - - BasicDBObject details = new BasicDBObject(); - if (event.getDetails() != null) { - for (Map.Entry entry : event.getDetails().entrySet()) { - details.put(entry.getKey(), entry.getValue()); - } - } - e.put("details", details); - - return e; - } - - static Event convertEvent(BasicDBObject o) { - Event event = new Event(); - event.setTime(o.getLong("time")); - event.setType(EventType.valueOf(o.getString("type"))); - event.setRealmId(o.getString("realmId")); - event.setClientId(o.getString("clientId")); - event.setUserId(o.getString("userId")); - event.setSessionId(o.getString("sessionId")); - event.setIpAddress(o.getString("ipAddress")); - event.setError(o.getString("error")); - - BasicDBObject d = (BasicDBObject) o.get("details"); - if (d != null) { - Map details = new HashMap(); - for (Object k : d.keySet()) { - details.put((String) k, d.getString((String) k)); - } - event.setDetails(details); - } - - return event; - } - - private static DBObject convertAdminEvent(AdminEvent adminEvent, boolean includeRepresentation) { - BasicDBObject e = new BasicDBObject(); - e.put("time", adminEvent.getTime()); - e.put("realmId", adminEvent.getRealmId()); - e.put("operationType", adminEvent.getOperationType().toString()); - setAuthDetails(e, adminEvent.getAuthDetails()); - e.put("resourcePath", adminEvent.getResourcePath()); - e.put("error", adminEvent.getError()); - - if(includeRepresentation) { - e.put("representation", adminEvent.getRepresentation()); - } - - return e; - } - - static AdminEvent convertAdminEvent(BasicDBObject o) { - AdminEvent adminEvent = new AdminEvent(); - adminEvent.setTime(o.getLong("time")); - adminEvent.setRealmId(o.getString("realmId")); - adminEvent.setOperationType(OperationType.valueOf(o.getString("operationType"))); - if (o.getString("resourceType") != null) { - adminEvent.setResourceType(ResourceType.valueOf(o.getString("resourceType"))); - } - setAuthDetails(adminEvent, o); - adminEvent.setResourcePath(o.getString("resourcePath")); - adminEvent.setError(o.getString("error")); - - if(o.getString("representation") != null) { - adminEvent.setRepresentation(o.getString("representation")); - } - return adminEvent; - } - - private static void setAuthDetails(BasicDBObject e, AuthDetails authDetails) { - e.put("authRealmId", authDetails.getRealmId()); - e.put("authClientId", authDetails.getClientId()); - e.put("authUserId", authDetails.getUserId()); - e.put("authIpAddress", authDetails.getIpAddress()); - } - - private static void setAuthDetails(AdminEvent adminEvent, BasicDBObject o) { - AuthDetails authDetails = new AuthDetails(); - authDetails.setRealmId(o.getString("authRealmId")); - authDetails.setClientId(o.getString("authClientId")); - authDetails.setUserId(o.getString("authUserId")); - authDetails.setIpAddress(o.getString("authIpAddress")); - adminEvent.setAuthDetails(authDetails); - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProviderFactory.java b/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProviderFactory.java deleted file mode 100755 index 57aaa734305..00000000000 --- a/model/mongo/src/main/java/org/keycloak/events/mongo/MongoEventStoreProviderFactory.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.events.mongo; - -import com.mongodb.DBCollection; -import com.mongodb.WriteConcern; -import org.jboss.logging.Logger; -import org.keycloak.Config; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.events.EventStoreProvider; -import org.keycloak.events.EventStoreProviderFactory; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; - -/** - * @author Stian Thorgersen - */ -public class MongoEventStoreProviderFactory implements EventStoreProviderFactory { - - protected static final Logger logger = Logger.getLogger(MongoEventStoreProviderFactory.class); - - public static final String ID = "mongo"; - - @Override - public EventStoreProvider create(KeycloakSession session) { - MongoConnectionProvider connection = session.getProvider(MongoConnectionProvider.class); - - DBCollection collection = connection.getDB().getCollection("events"); - DBCollection adminCollection = connection.getDB().getCollection("adminEvents"); - - collection.setWriteConcern(WriteConcern.UNACKNOWLEDGED); - adminCollection.setWriteConcern(WriteConcern.UNACKNOWLEDGED); - - return new MongoEventStoreProvider(collection, adminCollection); - } - - @Override - public void init(Config.Scope config) { - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - - @Override - public void close() { - } - - @Override - public String getId() { - return ID; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/AbstractMongoAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/AbstractMongoAdapter.java deleted file mode 100644 index 7f6bf1abfeb..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/AbstractMongoAdapter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Marek Posolda - */ -public abstract class AbstractMongoAdapter { - - protected final MongoStoreInvocationContext invocationContext; - - public AbstractMongoAdapter(MongoStoreInvocationContext invocationContext) { - this.invocationContext = invocationContext; - } - - protected abstract T getMongoEntity(); - - protected void updateMongoEntity() { - getMongoStore().updateEntity(getMongoEntity(), invocationContext); - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - - if (o == null || getClass() != o.getClass()) return false; - - AbstractMongoAdapter that = (AbstractMongoAdapter) o; - - if (getMongoEntity() == null && that.getMongoEntity() == null) return true; - return getMongoEntity().equals(that.getMongoEntity()); - } - - @Override - public int hashCode() { - return getMongoEntity()!=null ? getMongoEntity().hashCode() : super.hashCode(); - } - - protected MongoStore getMongoStore() { - return invocationContext.getMongoStore(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientAdapter.java deleted file mode 100755 index 31394304bc1..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientAdapter.java +++ /dev/null @@ -1,770 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.ClientModel; -import org.keycloak.models.ClientTemplateModel; -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.mongo.keycloak.entities.MongoClientEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; -import org.keycloak.models.mongo.keycloak.entities.ProtocolMapperEntity; -import org.keycloak.models.mongo.utils.MongoModelUtils; -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; - -/** - * @author Marek Posolda - */ -public class ClientAdapter extends AbstractMongoAdapter implements ClientModel { - - protected final MongoClientEntity clientEntity; - private final RealmModel realm; - protected KeycloakSession session; - - public ClientAdapter(KeycloakSession session, RealmModel realm, MongoClientEntity clientEntity, MongoStoreInvocationContext invContext) { - super(invContext); - this.session = session; - this.realm = realm; - this.clientEntity = clientEntity; - } - - @Override - public MongoClientEntity getMongoEntity() { - return clientEntity; - } - - @Override - public void updateClient() { - updateMongoEntity(); - - session.getKeycloakSessionFactory().publish(new RealmModel.ClientUpdatedEvent() { - - @Override - public ClientModel getUpdatedClient() { - return ClientAdapter.this; - } - - @Override - public KeycloakSession getKeycloakSession() { - return session; - } - }); - } - - - @Override - public String getId() { - return getMongoEntity().getId(); - } - - @Override - public String getClientId() { - return getMongoEntity().getClientId(); - } - - @Override - public String getName() { - return getMongoEntity().getName(); - } - - @Override - public void setName(String name) { - getMongoEntity().setName(name); - updateMongoEntity(); - } - - @Override - public String getDescription() { return getMongoEntity().getDescription(); } - - @Override - public void setDescription(String description) { - getMongoEntity().setDescription(description); - updateMongoEntity(); - } - - @Override - public void setClientId(String clientId) { - getMongoEntity().setClientId(clientId); - updateMongoEntity(); - } - - @Override - public Set getWebOrigins() { - Set result = new HashSet(); - if (getMongoEntity().getWebOrigins() != null) { - result.addAll(getMongoEntity().getWebOrigins()); - } - return result; - } - - @Override - public void setWebOrigins(Set webOrigins) { - List result = new ArrayList(); - result.addAll(webOrigins); - getMongoEntity().setWebOrigins(result); - updateMongoEntity(); - } - - @Override - public void addWebOrigin(String webOrigin) { - getMongoStore().pushItemToList(clientEntity, "webOrigins", webOrigin, true, invocationContext); - } - - @Override - public void removeWebOrigin(String webOrigin) { - getMongoStore().pullItemFromList(clientEntity, "webOrigins", webOrigin, invocationContext); - } - - @Override - public Set getRedirectUris() { - Set result = new HashSet(); - if (getMongoEntity().getRedirectUris() != null) { - result.addAll(getMongoEntity().getRedirectUris()); - } - return result; - } - - @Override - public void setRedirectUris(Set redirectUris) { - List result = new ArrayList(); - result.addAll(redirectUris); - getMongoEntity().setRedirectUris(result); - updateMongoEntity(); - } - - @Override - public void addRedirectUri(String redirectUri) { - getMongoStore().pushItemToList(clientEntity, "redirectUris", redirectUri, true, invocationContext); - } - - @Override - public void removeRedirectUri(String redirectUri) { - getMongoStore().pullItemFromList(clientEntity, "redirectUris", redirectUri, invocationContext); - } - - @Override - public boolean isEnabled() { - return getMongoEntity().isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - getMongoEntity().setEnabled(enabled); - updateMongoEntity(); - } - - @Override - public String getClientAuthenticatorType() { - return getMongoEntity().getClientAuthenticatorType(); - } - - @Override - public void setClientAuthenticatorType(String clientAuthenticatorType) { - getMongoEntity().setClientAuthenticatorType(clientAuthenticatorType); - updateMongoEntity(); - } - - @Override - public boolean validateSecret(String secret) { - return secret.equals(getMongoEntity().getSecret()); - } - - @Override - public String getSecret() { - return getMongoEntity().getSecret(); - } - - @Override - public void setSecret(String secret) { - getMongoEntity().setSecret(secret); - updateMongoEntity(); - } - - @Override - public String getRegistrationToken() { - return getMongoEntity().getRegistrationToken(); - } - - @Override - public void setRegistrationToken(String registrationToken) { - getMongoEntity().setRegistrationToken(registrationToken); - updateMongoEntity(); - } - - @Override - public boolean isPublicClient() { - return getMongoEntity().isPublicClient(); - } - - @Override - public void setPublicClient(boolean flag) { - getMongoEntity().setPublicClient(flag); - updateMongoEntity(); - } - - - @Override - public boolean isFrontchannelLogout() { - return getMongoEntity().isFrontchannelLogout(); - } - - @Override - public void setFrontchannelLogout(boolean flag) { - getMongoEntity().setFrontchannelLogout(flag); - updateMongoEntity(); - } - - @Override - public boolean isFullScopeAllowed() { - return getMongoEntity().isFullScopeAllowed(); - } - - @Override - public void setFullScopeAllowed(boolean value) { - getMongoEntity().setFullScopeAllowed(value); - updateMongoEntity(); - - } - - @Override - public RealmModel getRealm() { - return realm; - } - - @Override - public int getNotBefore() { - return getMongoEntity().getNotBefore(); - } - - @Override - public void setNotBefore(int notBefore) { - getMongoEntity().setNotBefore(notBefore); - updateMongoEntity(); - } - - @Override - public Set getScopeMappings() { - Set result = new HashSet(); - List roles = MongoModelUtils.getAllScopesOfClient(this, invocationContext); - - for (MongoRoleEntity role : roles) { - if (realm.getId().equals(role.getRealmId())) { - result.add(new RoleAdapter(session, realm, role, realm, invocationContext)); - } else { - // Likely applicationRole, but we don't have this application yet - result.add(new RoleAdapter(session, realm, role, invocationContext)); - } - } - return result; - } - - @Override - public Set getRealmScopeMappings() { - Set allScopes = getScopeMappings(); - - // 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 : allScopes) { - MongoRoleEntity roleEntity = ((RoleAdapter) role).getRole(); - - if (realm.getId().equals(roleEntity.getRealmId())) { - realmRoles.add(role); - } - } - return realmRoles; - } - - @Override - public void addScopeMapping(RoleModel role) { - getMongoStore().pushItemToList(this.getMongoEntity(), "scopeIds", role.getId(), true, invocationContext); - } - - @Override - public void deleteScopeMapping(RoleModel role) { - getMongoStore().pullItemFromList(this.getMongoEntity(), "scopeIds", role.getId(), invocationContext); - } - - @Override - public String getProtocol() { - return getMongoEntity().getProtocol(); - } - - @Override - public void setProtocol(String protocol) { - getMongoEntity().setProtocol(protocol); - updateMongoEntity(); - - } - - @Override - public void setAttribute(String name, String value) { - getMongoEntity().getAttributes().put(name, value); - updateMongoEntity(); - - } - - @Override - public void removeAttribute(String name) { - getMongoEntity().getAttributes().remove(name); - updateMongoEntity(); - } - - @Override - public String getAttribute(String name) { - return getMongoEntity().getAttributes().get(name); - } - - @Override - public Map getAttributes() { - Map copy = new HashMap(); - copy.putAll(getMongoEntity().getAttributes()); - return copy; - } - - @Override - public Set getProtocolMappers() { - Set result = new HashSet(); - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - 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); - result.add(mapping); - } - return result; - } - - @Override - public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) { - if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) { - throw new ModelDuplicateException("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()); - getMongoEntity().getProtocolMappers().add(entity); - updateMongoEntity(); - return entityToModel(entity); - } - - @Override - public void removeProtocolMapper(ProtocolMapperModel mapping) { - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - if (entity.getId().equals(mapping.getId())) { - session.users().preRemove(mapping); - - getMongoEntity().getProtocolMappers().remove(entity); - updateMongoEntity(); - break; - } - } - - } - - protected ProtocolMapperEntity getProtocolMapperyEntityById(String id) { - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - if (entity.getId().equals(id)) { - return entity; - } - } - return null; - - } - protected ProtocolMapperEntity getProtocolMapperEntityByName(String protocol, String name) { - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - if (entity.getProtocol().equals(protocol) && entity.getName().equals(name)) { - return entity; - } - } - return null; - - } - - - @Override - public void updateProtocolMapper(ProtocolMapperModel mapping) { - ProtocolMapperEntity entity = getProtocolMapperyEntityById(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()); - } - updateMongoEntity(); - - } - - @Override - public ProtocolMapperModel getProtocolMapperById(String id) { - ProtocolMapperEntity entity = getProtocolMapperyEntityById(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 boolean isSurrogateAuthRequired() { - return getMongoEntity().isSurrogateAuthRequired(); - } - - @Override - public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { - getMongoEntity().setSurrogateAuthRequired(surrogateAuthRequired); - updateMongoEntity(); - } - - @Override - public String getManagementUrl() { - return getMongoEntity().getManagementUrl(); - } - - @Override - public void setManagementUrl(String url) { - getMongoEntity().setManagementUrl(url); - updateMongoEntity(); - } - - @Override - public void setRootUrl(String url) { - getMongoEntity().setRootUrl(url); - updateMongoEntity(); - } - - @Override - public String getRootUrl() { - return getMongoEntity().getRootUrl(); - } - - @Override - public void setBaseUrl(String url) { - getMongoEntity().setBaseUrl(url); - updateMongoEntity(); - } - - @Override - public String getBaseUrl() { - return getMongoEntity().getBaseUrl(); - } - - @Override - public boolean isBearerOnly() { - return getMongoEntity().isBearerOnly(); - } - - @Override - public void setBearerOnly(boolean only) { - getMongoEntity().setBearerOnly(only); - updateMongoEntity(); - } - - @Override - public boolean isConsentRequired() { - return getMongoEntity().isConsentRequired(); - } - - @Override - public void setConsentRequired(boolean consentRequired) { - getMongoEntity().setConsentRequired(consentRequired); - updateMongoEntity(); - } - - @Override - public boolean isStandardFlowEnabled() { - return getMongoEntity().isStandardFlowEnabled(); - } - - @Override - public void setStandardFlowEnabled(boolean standardFlowEnabled) { - getMongoEntity().setStandardFlowEnabled(standardFlowEnabled); - updateMongoEntity(); - } - - @Override - public boolean isImplicitFlowEnabled() { - return getMongoEntity().isImplicitFlowEnabled(); - } - - @Override - public void setImplicitFlowEnabled(boolean implicitFlowEnabled) { - getMongoEntity().setImplicitFlowEnabled(implicitFlowEnabled); - updateMongoEntity(); - } - - @Override - public boolean isDirectAccessGrantsEnabled() { - return getMongoEntity().isDirectAccessGrantsEnabled(); - } - - @Override - public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) { - getMongoEntity().setDirectAccessGrantsEnabled(directAccessGrantsEnabled); - updateMongoEntity(); - } - - @Override - public boolean isServiceAccountsEnabled() { - return getMongoEntity().isServiceAccountsEnabled(); - } - - @Override - public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) { - getMongoEntity().setServiceAccountsEnabled(serviceAccountsEnabled); - updateMongoEntity(); - } - - @Override - public RoleModel getRole(String name) { - return session.realms().getClientRole(realm, this, name); - } - - @Override - public RoleModel addRole(String name) { - return session.realms().addClientRole(realm, this, name); - } - - @Override - public RoleModel addRole(String id, String name) { - return session.realms().addClientRole(realm, this, id, name); - } - - @Override - public boolean removeRole(RoleModel role) { - return session.realms().removeRole(realm, role); - } - - @Override - public Set getRoles() { - return session.realms().getClientRoles(realm, this); - } - - @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 List getDefaultRoles() { - return getMongoEntity().getDefaultRoles(); - } - - @Override - public void addDefaultRole(String name) { - RoleModel role = getRole(name); - if (role == null) { - addRole(name); - } - - getMongoStore().pushItemToList(getMongoEntity(), "defaultRoles", name, true, invocationContext); - } - - @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); - } - - getMongoEntity().setDefaultRoles(roleNames); - updateMongoEntity(); - } - - @Override - public void removeDefaultRoles(String... defaultRoles) { - List roleNames = new ArrayList(); - for (String role : getMongoEntity().getDefaultRoles()) { - if (!RealmAdapter.contains(role, defaultRoles)) roleNames.add(role); - } - getMongoEntity().setDefaultRoles(roleNames); - updateMongoEntity(); - } - - - @Override - public int getNodeReRegistrationTimeout() { - return getMongoEntity().getNodeReRegistrationTimeout(); - } - - @Override - public void setNodeReRegistrationTimeout(int timeout) { - getMongoEntity().setNodeReRegistrationTimeout(timeout); - updateMongoEntity(); - } - - @Override - public Map getRegisteredNodes() { - return getMongoEntity().getRegisteredNodes() == null ? Collections.emptyMap() : Collections.unmodifiableMap(getMongoEntity().getRegisteredNodes()); - } - - @Override - public void registerNode(String nodeHost, int registrationTime) { - MongoClientEntity entity = getMongoEntity(); - if (entity.getRegisteredNodes() == null) { - entity.setRegisteredNodes(new HashMap()); - } - - entity.getRegisteredNodes().put(nodeHost, registrationTime); - updateMongoEntity(); - } - - @Override - public void unregisterNode(String nodeHost) { - MongoClientEntity entity = getMongoEntity(); - if (entity.getRegisteredNodes() == null) return; - - entity.getRegisteredNodes().remove(nodeHost); - updateMongoEntity(); - } - - @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(); - } - - @Override - public ClientTemplateModel getClientTemplate() { - if (getMongoEntity().getClientTemplate() == null) return null; - return session.realms().getClientTemplateById(getMongoEntity().getClientTemplate(), realm); - } - - @Override - public void setClientTemplate(ClientTemplateModel template) { - if (template == null) { - getMongoEntity().setClientTemplate(null); - } else { - getMongoEntity().setClientTemplate(template.getId()); - } - - updateMongoEntity(); - - } - - @Override - public boolean useTemplateScope() { - return getMongoEntity().isUseTemplateScope(); - } - - @Override - public void setUseTemplateScope(boolean flag) { - getMongoEntity().setUseTemplateScope(flag); - updateMongoEntity(); - - } - - @Override - public boolean useTemplateMappers() { - return getMongoEntity().isUseTemplateMappers(); - } - - @Override - public void setUseTemplateMappers(boolean flag) { - getMongoEntity().setUseTemplateMappers(flag); - updateMongoEntity(); - - } - - @Override - public boolean useTemplateConfig() { - return getMongoEntity().isUseTemplateConfig(); - } - - @Override - public void setUseTemplateConfig(boolean flag) { - getMongoEntity().setUseTemplateConfig(flag); - updateMongoEntity(); - - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientTemplateAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientTemplateAdapter.java deleted file mode 100755 index 22a4dfa8854..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/ClientTemplateAdapter.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.ClientTemplateModel; -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.mongo.keycloak.entities.MongoClientTemplateEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; -import org.keycloak.models.mongo.keycloak.entities.ProtocolMapperEntity; -import org.keycloak.models.mongo.utils.MongoModelUtils; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author Bill Burke - */ -public class ClientTemplateAdapter extends AbstractMongoAdapter implements ClientTemplateModel { - - protected final MongoClientTemplateEntity clientTemplateEntity; - private final RealmModel realm; - protected KeycloakSession session; - - public ClientTemplateAdapter(KeycloakSession session, RealmModel realm, MongoClientTemplateEntity clientEntity, MongoStoreInvocationContext invContext) { - super(invContext); - this.session = session; - this.realm = realm; - this.clientTemplateEntity = clientEntity; - } - - @Override - public MongoClientTemplateEntity getMongoEntity() { - return clientTemplateEntity; - } - - @Override - public RealmModel getRealm() { - return realm; - } - - - @Override - public String getId() { - return getMongoEntity().getId(); - } - - @Override - public String getName() { - return getMongoEntity().getName(); - } - - @Override - public void setName(String name) { - getMongoEntity().setName(name); - updateMongoEntity(); - } - - @Override - public String getDescription() { return getMongoEntity().getDescription(); } - - @Override - public String getProtocol() { - return getMongoEntity().getProtocol(); - } - - @Override - public void setProtocol(String protocol) { - getMongoEntity().setProtocol(protocol); - updateMongoEntity(); - - } - - - @Override - public void setDescription(String description) { - getMongoEntity().setDescription(description); - updateMongoEntity(); - } - - @Override - public Set getProtocolMappers() { - Set result = new HashSet(); - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - 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); - result.add(mapping); - } - return result; - } - - @Override - public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) { - if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) { - throw new ModelDuplicateException("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()); - getMongoEntity().getProtocolMappers().add(entity); - updateMongoEntity(); - return entityToModel(entity); - } - - @Override - public void removeProtocolMapper(ProtocolMapperModel mapping) { - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - if (entity.getId().equals(mapping.getId())) { - session.users().preRemove(mapping); - - getMongoEntity().getProtocolMappers().remove(entity); - updateMongoEntity(); - break; - } - } - - } - - protected ProtocolMapperEntity getProtocolMapperyEntityById(String id) { - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - if (entity.getId().equals(id)) { - return entity; - } - } - return null; - - } - protected ProtocolMapperEntity getProtocolMapperEntityByName(String protocol, String name) { - for (ProtocolMapperEntity entity : getMongoEntity().getProtocolMappers()) { - if (entity.getProtocol().equals(protocol) && entity.getName().equals(name)) { - return entity; - } - } - return null; - - } - - - @Override - public void updateProtocolMapper(ProtocolMapperModel mapping) { - ProtocolMapperEntity entity = getProtocolMapperyEntityById(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()); - } - updateMongoEntity(); - - } - - @Override - public ProtocolMapperModel getProtocolMapperById(String id) { - ProtocolMapperEntity entity = getProtocolMapperyEntityById(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 boolean isFullScopeAllowed() { - return getMongoEntity().isFullScopeAllowed(); - } - - @Override - public void setFullScopeAllowed(boolean value) { - getMongoEntity().setFullScopeAllowed(value); - updateMongoEntity(); - - } - @Override - public Set getScopeMappings() { - Set result = new HashSet(); - List roles = MongoModelUtils.getAllScopesOfTemplate(this, invocationContext); - - for (MongoRoleEntity role : roles) { - if (realm.getId().equals(role.getRealmId())) { - result.add(new RoleAdapter(session, realm, role, realm, invocationContext)); - } else { - // Likely applicationRole, but we don't have this application yet - result.add(new RoleAdapter(session, realm, role, invocationContext)); - } - } - return result; - } - - @Override - public Set getRealmScopeMappings() { - Set allScopes = getScopeMappings(); - - // 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 : allScopes) { - MongoRoleEntity roleEntity = ((RoleAdapter) role).getRole(); - - if (realm.getId().equals(roleEntity.getRealmId())) { - realmRoles.add(role); - } - } - return realmRoles; - } - - @Override - public void addScopeMapping(RoleModel role) { - getMongoStore().pushItemToList(this.getMongoEntity(), "scopeIds", role.getId(), true, invocationContext); - } - - @Override - public void deleteScopeMapping(RoleModel role) { - getMongoStore().pullItemFromList(this.getMongoEntity(), "scopeIds", role.getId(), invocationContext); - } - - @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; - } - return false; - } - - @Override - public boolean isPublicClient() { - return getMongoEntity().isPublicClient(); - } - - @Override - public void setPublicClient(boolean flag) { - getMongoEntity().setPublicClient(flag); - updateMongoEntity(); - } - - - @Override - public boolean isFrontchannelLogout() { - return getMongoEntity().isFrontchannelLogout(); - } - - @Override - public void setFrontchannelLogout(boolean flag) { - getMongoEntity().setFrontchannelLogout(flag); - updateMongoEntity(); - } - - @Override - public void setAttribute(String name, String value) { - getMongoEntity().getAttributes().put(name, value); - updateMongoEntity(); - - } - - @Override - public void removeAttribute(String name) { - getMongoEntity().getAttributes().remove(name); - updateMongoEntity(); - } - - @Override - public String getAttribute(String name) { - return getMongoEntity().getAttributes().get(name); - } - - @Override - public Map getAttributes() { - Map copy = new HashMap(); - copy.putAll(getMongoEntity().getAttributes()); - return copy; - } - - @Override - public boolean isBearerOnly() { - return getMongoEntity().isBearerOnly(); - } - - @Override - public void setBearerOnly(boolean only) { - getMongoEntity().setBearerOnly(only); - updateMongoEntity(); - } - - @Override - public boolean isConsentRequired() { - return getMongoEntity().isConsentRequired(); - } - - @Override - public void setConsentRequired(boolean consentRequired) { - getMongoEntity().setConsentRequired(consentRequired); - updateMongoEntity(); - } - - @Override - public boolean isStandardFlowEnabled() { - return getMongoEntity().isStandardFlowEnabled(); - } - - @Override - public void setStandardFlowEnabled(boolean standardFlowEnabled) { - getMongoEntity().setStandardFlowEnabled(standardFlowEnabled); - updateMongoEntity(); - } - - @Override - public boolean isImplicitFlowEnabled() { - return getMongoEntity().isImplicitFlowEnabled(); - } - - @Override - public void setImplicitFlowEnabled(boolean implicitFlowEnabled) { - getMongoEntity().setImplicitFlowEnabled(implicitFlowEnabled); - updateMongoEntity(); - } - - @Override - public boolean isDirectAccessGrantsEnabled() { - return getMongoEntity().isDirectAccessGrantsEnabled(); - } - - @Override - public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) { - getMongoEntity().setDirectAccessGrantsEnabled(directAccessGrantsEnabled); - updateMongoEntity(); - } - - @Override - public boolean isServiceAccountsEnabled() { - return getMongoEntity().isServiceAccountsEnabled(); - } - - @Override - public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) { - getMongoEntity().setServiceAccountsEnabled(serviceAccountsEnabled); - updateMongoEntity(); - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || !(o instanceof ClientTemplateModel)) return false; - - ClientTemplateModel that = (ClientTemplateModel) o; - return that.getId().equals(getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java deleted file mode 100755 index d4ad3afbc82..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.ClientModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelException; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.mongo.keycloak.entities.MongoGroupEntity; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.models.utils.RoleUtils; - -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; - -/** - * - * @author Bill Burke - */ -public class GroupAdapter extends AbstractMongoAdapter implements GroupModel { - - private final MongoGroupEntity group; - private RealmModel realm; - private KeycloakSession session; - - public GroupAdapter(KeycloakSession session, RealmModel realm, MongoGroupEntity group, MongoStoreInvocationContext invContext) { - super(invContext); - 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); - updateGroup(); - } - - protected void updateGroup() { - super.updateMongoEntity(); - } - - @Override - public MongoGroupEntity getMongoEntity() { - return group; - } - - @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); - updateGroup(); - } - - @Override - public void setAttribute(String name, List values) { - if (group.getAttributes() == null) { - group.setAttributes(new HashMap>()); - } - - group.getAttributes().put(name, values); - updateGroup(); - } - - @Override - public void removeAttribute(String name) { - if (group.getAttributes() == null) return; - - group.getAttributes().remove(name); - updateGroup(); - } - - @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 RoleUtils.hasRole(roles, role); - } - - @Override - public void grantRole(RoleModel role) { - getMongoStore().pushItemToList(group, "roleIds", role.getId(), true, invocationContext); - } - - @Override - public Set getRoleMappings() { - if (group.getRoleIds() == null || group.getRoleIds().isEmpty()) return Collections.EMPTY_SET; - Set roles = new HashSet<>(); - for (String id : group.getRoleIds()) { - RoleModel roleById = realm.getRoleById(id); - if (roleById == null) { - throw new ModelException("role does not exist in group role mappings"); - } - roles.add(roleById); - } - 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; - - getMongoStore().pullItemFromList(group, "roleIds", role.getId(), invocationContext); - } - - @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() { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .and("parentId").is(getId()) - .get(); - List groups = getMongoStore().loadEntities(MongoGroupEntity.class, query, invocationContext); - - Set subGroups = new HashSet<>(); - - if (groups == null) return subGroups; - for (MongoGroupEntity group : groups) { - subGroups.add(realm.getGroupById(group.getId())); - } - - return subGroups; - } - - @Override - public void setParent(GroupModel parent) { - if (parent == null) group.setParentId(null); - else if (parent.getId().equals(getId())) { - return; - } - else { - group.setParentId(parent.getId()); - } - updateGroup(); - - } - - @Override - public void addChild(GroupModel subGroup) { - if (subGroup.getId().equals(getId())) { - return; - } - subGroup.setParent(this); - updateGroup(); - - } - - @Override - public void removeChild(GroupModel subGroup) { - if (subGroup.getId().equals(getId())) { - return; - } - subGroup.setParent(null); - updateGroup(); - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java deleted file mode 100755 index 7e4e91ce8af..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.migration.MigrationModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.mongo.keycloak.entities.MongoMigrationModelEntity; - -/** - * @author Marek Posolda - */ -public class MigrationModelAdapter extends AbstractMongoAdapter implements MigrationModel { - - protected final MongoMigrationModelEntity entity; - - public MigrationModelAdapter(KeycloakSession session, MongoMigrationModelEntity entity, MongoStoreInvocationContext invContext) { - super(invContext); - this.entity = entity; - } - - @Override - public MongoMigrationModelEntity getMongoEntity() { - return entity; - } - - @Override - public String getStoredVersion() { - return getMongoEntity().getVersion(); - } - - @Override - public void setStoredVersion(String version) { - getMongoEntity().setVersion(version); - updateMongoEntity(); - - } - - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java deleted file mode 100755 index 14e5b033a03..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.migration.MigrationModel; -import org.keycloak.models.ClientModel; -import org.keycloak.models.ClientTemplateModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RealmProvider; -import org.keycloak.models.RoleContainerModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoClientTemplateEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoGroupEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoMigrationModelEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * @author Marek Posolda - */ -public class MongoRealmProvider implements RealmProvider { - - private final MongoStoreInvocationContext invocationContext; - private final KeycloakSession session; - - public MongoRealmProvider(KeycloakSession session, MongoStoreInvocationContext invocationContext) { - this.session = session; - this.invocationContext = invocationContext; - } - - @Override - public void close() { - // TODO - } - - @Override - public MigrationModel getMigrationModel() { - MongoMigrationModelEntity entity = getMongoStore().loadEntity(MongoMigrationModelEntity.class, MongoMigrationModelEntity.MIGRATION_MODEL_ID, invocationContext); - if (entity == null) { - entity = new MongoMigrationModelEntity(); - getMongoStore().insertEntity(entity, invocationContext); - } - return new MigrationModelAdapter(session, entity, invocationContext); - } - - @Override - public RealmModel createRealm(String name) { - return createRealm(KeycloakModelUtils.generateId(), name); - } - - @Override - public RealmModel createRealm(String id, String name) { - MongoRealmEntity newRealm = new MongoRealmEntity(); - newRealm.setId(id); - newRealm.setName(name); - - getMongoStore().insertEntity(newRealm, invocationContext); - - final RealmModel model = new RealmAdapter(session, newRealm, invocationContext); - session.getKeycloakSessionFactory().publish(new RealmModel.RealmCreationEvent() { - @Override - public RealmModel getCreatedRealm() { - return model; - } - }); - return model; - } - - @Override - public RealmModel getRealm(String id) { - MongoRealmEntity realmEntity = getMongoStore().loadEntity(MongoRealmEntity.class, id, invocationContext); - return realmEntity != null ? new RealmAdapter(session, realmEntity, invocationContext) : null; - } - - @Override - public List getRealms() { - DBObject query = new BasicDBObject(); - List realms = getMongoStore().loadEntities(MongoRealmEntity.class, query, invocationContext); - - List results = new ArrayList(); - for (MongoRealmEntity realmEntity : realms) { - RealmModel realm = session.realms().getRealm(realmEntity.getId()); - if (realm != null) results.add(realm); - } - return results; - } - - @Override - public RealmModel getRealmByName(String name) { - DBObject query = new QueryBuilder() - .and("name").is(name) - .get(); - MongoRealmEntity realm = getMongoStore().loadSingleEntity(MongoRealmEntity.class, query, invocationContext); - - if (realm == null) return null; - return session.realms().getRealm(realm.getId()); - } - - @Override - public boolean removeRealm(String id) { - final RealmModel realm = getRealm(id); - if (realm == null) return false; - session.users().preRemove(realm); - boolean removed = getMongoStore().removeEntity(MongoRealmEntity.class, id, invocationContext); - - if (removed) { - session.getKeycloakSessionFactory().publish(new RealmModel.RealmRemovedEvent() { - @Override - public RealmModel getRealm() { - return realm; - } - - @Override - public KeycloakSession getKeycloakSession() { - return session; - } - }); - } - - return removed; - } - - protected MongoStore getMongoStore() { - return invocationContext.getMongoStore(); - } - - @Override - public RoleModel getRoleById(String id, RealmModel realm) { - MongoRoleEntity role = getMongoStore().loadEntity(MongoRoleEntity.class, id, invocationContext); - if (role == null) return null; - if (role.getRealmId() != null && !role.getRealmId().equals(realm.getId())) return null; - if (role.getClientId() != null && realm.getClientById(role.getClientId()) == null) return null; - return new RoleAdapter(session, realm, role, null, invocationContext); - } - - @Override - public GroupModel getGroupById(String id, RealmModel realm) { - MongoGroupEntity group = getMongoStore().loadEntity(MongoGroupEntity.class, id, invocationContext); - if (group == null) return null; - if (group.getRealmId() != null && !group.getRealmId().equals(realm.getId())) return null; - return new GroupAdapter(session, realm, group, invocationContext); - } - - @Override - public void moveGroup(RealmModel realm, GroupModel group, GroupModel toParent) { - if (toParent != null && group.getId().equals(toParent.getId())) { - return; - } - if (group.getParentId() != null) { - group.getParent().removeChild(group); - } - group.setParent(toParent); - if (toParent != null) toParent.addChild(group); - else session.realms().addTopLevelGroup(realm, group); - - } - - @Override - public List getGroups(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - List groups = getMongoStore().loadEntities(MongoGroupEntity.class, query, invocationContext); - if (groups == null) return Collections.EMPTY_LIST; - - List result = new LinkedList<>(); - - if (groups == null) return result; - for (MongoGroupEntity group : groups) { - result.add(getGroupById(group.getId(), realm)); - } - - return Collections.unmodifiableList(result); - } - - @Override - public List getTopLevelGroups(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .and("parentId").is(null) - .get(); - List groups = getMongoStore().loadEntities(MongoGroupEntity.class, query, invocationContext); - if (groups == null) return Collections.EMPTY_LIST; - - List result = new LinkedList<>(); - - if (groups == null) return result; - for (MongoGroupEntity group : groups) { - result.add(getGroupById(group.getId(), realm)); - } - - return Collections.unmodifiableList(result); - } - - @Override - public boolean removeGroup(RealmModel realm, GroupModel group) { - session.users().preRemove(realm, group); - realm.removeDefaultGroup(group); - for (GroupModel subGroup : group.getSubGroups()) { - removeGroup(realm, subGroup); - } - moveGroup(realm, group, null); - return getMongoStore().removeEntity(MongoGroupEntity.class, group.getId(), invocationContext); - } - - @Override - public GroupModel createGroup(RealmModel realm, String name) { - String id = KeycloakModelUtils.generateId(); - return createGroup(realm, id, name); - } - - @Override - public GroupModel createGroup(RealmModel realm, String id, String name) { - if (id == null) id = KeycloakModelUtils.generateId(); - MongoGroupEntity group = new MongoGroupEntity(); - group.setId(id); - group.setName(name); - group.setRealmId(realm.getId()); - - getMongoStore().insertEntity(group, invocationContext); - - return new GroupAdapter(session, realm, group, invocationContext); - } - - @Override - public void addTopLevelGroup(RealmModel realm, GroupModel subGroup) { - subGroup.setParent(null); - } - - @Override - public ClientModel getClientById(String id, RealmModel realm) { - MongoClientEntity appData = getMongoStore().loadEntity(MongoClientEntity.class, id, invocationContext); - - // Check if application belongs to this realm - if (appData == null || !realm.getId().equals(appData.getRealmId())) { - return null; - } - - return new ClientAdapter(session, realm, appData, invocationContext); - } - - @Override - public ClientModel addClient(RealmModel realm, String clientId) { - return addClient(realm, KeycloakModelUtils.generateId(), clientId); - } - - @Override - public ClientModel addClient(RealmModel realm, String id, String clientId) { - MongoClientEntity clientEntity = new MongoClientEntity(); - clientEntity.setId(id); - clientEntity.setClientId(clientId); - clientEntity.setRealmId(realm.getId()); - clientEntity.setEnabled(true); - clientEntity.setStandardFlowEnabled(true); - getMongoStore().insertEntity(clientEntity, invocationContext); - - if (clientId == null) { - clientEntity.setClientId(clientEntity.getId()); - getMongoStore().updateEntity(clientEntity, invocationContext); - } - - final ClientModel model = new ClientAdapter(session, realm, clientEntity, invocationContext); - session.getKeycloakSessionFactory().publish(new RealmModel.ClientCreationEvent() { - @Override - public ClientModel getCreatedClient() { - return model; - } - }); - return model; - } - - @Override - public List getClients(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - List clientEntities = getMongoStore().loadEntities(MongoClientEntity.class, query, invocationContext); - - if (clientEntities.isEmpty()) return Collections.EMPTY_LIST; - List result = new ArrayList(); - for (MongoClientEntity clientEntity : clientEntities) { - result.add(session.realms().getClientById(clientEntity.getId(), realm)); - } - return Collections.unmodifiableList(result); - } - - @Override - public RoleModel addRealmRole(RealmModel realm, String name) { - return addRealmRole(realm, KeycloakModelUtils.generateId(), name); - } - - @Override - public RoleModel addRealmRole(RealmModel realm, String id, String name) { - MongoRoleEntity roleEntity = new MongoRoleEntity(); - roleEntity.setId(id); - roleEntity.setName(name); - roleEntity.setRealmId(realm.getId()); - - getMongoStore().insertEntity(roleEntity, invocationContext); - - return new RoleAdapter(session, realm, roleEntity, realm, invocationContext); - } - - @Override - public Set getRealmRoles(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - List roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext); - - - if (roles == null) return Collections.EMPTY_SET; - Set result = new HashSet(); - for (MongoRoleEntity role : roles) { - result.add(session.realms().getRoleById(role.getId(), realm)); - } - - return Collections.unmodifiableSet(result); - - } - - @Override - public Set getClientRoles(RealmModel realm, ClientModel client) { - DBObject query = new QueryBuilder() - .and("clientId").is(client.getId()) - .get(); - List roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext); - - Set result = new HashSet(); - for (MongoRoleEntity role : roles) { - result.add(session.realms().getRoleById(role.getId(), realm)); - } - - return result; - } - - @Override - public RoleModel getRealmRole(RealmModel realm, String name) { - DBObject query = new QueryBuilder() - .and("name").is(name) - .and("realmId").is(realm.getId()) - .get(); - MongoRoleEntity role = getMongoStore().loadSingleEntity(MongoRoleEntity.class, query, invocationContext); - if (role == null) { - return null; - } else { - return session.realms().getRoleById(role.getId(), realm); - } - } - - @Override - public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) { - DBObject query = new QueryBuilder() - .and("name").is(name) - .and("clientId").is(client.getId()) - .get(); - MongoRoleEntity role = getMongoStore().loadSingleEntity(MongoRoleEntity.class, query, invocationContext); - if (role == null) { - return null; - } else { - return session.realms().getRoleById(role.getId(), realm); - } - } - - @Override - public RoleModel addClientRole(RealmModel realm, ClientModel client, String name) { - return addClientRole(realm, client, KeycloakModelUtils.generateId(), name); - } - - @Override - public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name) { - MongoRoleEntity roleEntity = new MongoRoleEntity(); - roleEntity.setId(id); - roleEntity.setName(name); - roleEntity.setClientId(client.getId()); - - getMongoStore().insertEntity(roleEntity, invocationContext); - - return new RoleAdapter(session, realm, roleEntity, client, invocationContext); - } - - @Override - public boolean removeRole(RealmModel realm, RoleModel role) { - session.users().preRemove(realm, role); - RoleContainerModel container = role.getContainer(); - if (container.getDefaultRoles().contains(role.getName())) { - container.removeDefaultRoles(role.getName()); - } - - return getMongoStore().removeEntity(MongoRoleEntity.class, role.getId(), invocationContext); - } - - @Override - public boolean removeClient(String id, RealmModel realm) { - if (id == null) return false; - final ClientModel client = getClientById(id, realm); - if (client == null) return false; - - session.users().preRemove(realm, client); - boolean removed = getMongoStore().removeEntity(MongoClientEntity.class, id, invocationContext); - - if (removed) { - session.getKeycloakSessionFactory().publish(new RealmModel.ClientRemovedEvent() { - @Override - public ClientModel getClient() { - return client; - } - - @Override - public KeycloakSession getKeycloakSession() { - return session; - } - }); - } - - return removed; - } - - @Override - public ClientModel getClientByClientId(String clientId, RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .and("clientId").is(clientId) - .get(); - MongoClientEntity appEntity = getMongoStore().loadSingleEntity(MongoClientEntity.class, query, invocationContext); - if (appEntity == null) return null; - return session.realms().getClientById(appEntity.getId(), realm); - - } - - @Override - public ClientTemplateModel getClientTemplateById(String id, RealmModel realm) { - MongoClientTemplateEntity appData = getMongoStore().loadEntity(MongoClientTemplateEntity.class, id, invocationContext); - - // Check if application belongs to this realm - if (appData == null || !realm.getId().equals(appData.getRealmId())) { - return null; - } - - return new ClientTemplateAdapter(session, realm, appData, invocationContext); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProviderFactory.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProviderFactory.java deleted file mode 100755 index c48c52871a3..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProviderFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.jboss.logging.Logger; -import org.keycloak.Config; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.RealmProvider; -import org.keycloak.models.RealmProviderFactory; - -/** - * KeycloakSessionFactory implementation based on MongoDB - * - * @author Marek Posolda - */ -public class MongoRealmProviderFactory implements RealmProviderFactory { - protected static final Logger logger = Logger.getLogger(MongoRealmProviderFactory.class); - - - @Override - public String getId() { - return "mongo"; - } - - @Override - public void init(Config.Scope config) { - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - - @Override - public RealmProvider create(KeycloakSession session) { - MongoConnectionProvider connection = session.getProvider(MongoConnectionProvider.class); - return new MongoRealmProvider(session, connection.getInvocationContext()); - } - - @Override - public void close() { - } - -} - diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java deleted file mode 100755 index 35802886945..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java +++ /dev/null @@ -1,864 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.common.util.MultivaluedHashMap; -import org.keycloak.common.util.Time; -import org.keycloak.component.ComponentModel; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.credential.CredentialModel; -import org.keycloak.credential.UserCredentialStore; -import org.keycloak.models.ClientModel; -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.ProtocolMapperModel; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RequiredActionProviderModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserConsentModel; -import org.keycloak.models.UserManager; -import org.keycloak.models.UserModel; -import org.keycloak.models.UserProvider; -import org.keycloak.models.cache.CachedUserModel; -import org.keycloak.models.mongo.keycloak.entities.CredentialEntity; -import org.keycloak.models.mongo.keycloak.entities.FederatedIdentityEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoUserConsentEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoUserEntity; -import org.keycloak.models.mongo.keycloak.entities.UserConsentEntity; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.models.utils.UserModelDelegate; -import org.keycloak.storage.UserStorageProvider; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * @author Marek Posolda - */ -public class MongoUserProvider implements UserProvider, UserCredentialStore { - - private final MongoStoreInvocationContext invocationContext; - private final KeycloakSession session; - - public MongoUserProvider(KeycloakSession session, MongoStoreInvocationContext invocationContext) { - this.session = session; - this.invocationContext = invocationContext; - } - - @Override - public void close() { - } - - @Override - public UserAdapter getUserById(String id, RealmModel realm) { - MongoUserEntity user = getMongoStore().loadEntity(MongoUserEntity.class, id, invocationContext); - - // Check that it's user from this realm - if (user == null || !realm.getId().equals(user.getRealmId())) { - return null; - } else { - return new UserAdapter(session, realm, user, invocationContext); - } - } - - @Override - public UserModel getUserByUsername(String username, RealmModel realm) { - DBObject query = new QueryBuilder() - .and("username").is(username.toLowerCase()) - .and("realmId").is(realm.getId()) - .get(); - MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext); - - if (user == null) { - return null; - } else { - return new UserAdapter(session, realm, user, invocationContext); - } - } - - @Override - public UserModel getUserByEmail(String email, RealmModel realm) { - DBObject query = new QueryBuilder() - .and("email").is(email.toLowerCase()) - .and("realmId").is(realm.getId()) - .get(); - List users = getMongoStore().loadEntities(MongoUserEntity.class, query, invocationContext); - - if (users.isEmpty()) return null; - - ensureEmailConstraint(users, realm); - - return new UserAdapter(session, realm, users.get(0), invocationContext); - } - - @Override - public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - queryBuilder.and("groupIds").is(group.getId()); - DBObject sort = new BasicDBObject("username", 1); - - List users = getMongoStore().loadEntities(MongoUserEntity.class, queryBuilder.get(), sort, firstResult, maxResults, invocationContext); - return convertUserEntities(realm, users); - } - - protected MongoStore getMongoStore() { - return invocationContext.getMongoStore(); - } - - @Override - public List getGroupMembers(RealmModel realm, GroupModel group) { - return getGroupMembers(realm, group, -1, -1); - } - - @Override - public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) { - DBObject query = new QueryBuilder() - .and("federatedIdentities.identityProvider").is(socialLink.getIdentityProvider()) - .and("federatedIdentities.userId").is(socialLink.getUserId()) - .and("realmId").is(realm.getId()) - .get(); - MongoUserEntity userEntity = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext); - return userEntity == null ? null : new UserAdapter(session, realm, userEntity, invocationContext); - } - - @Override - public UserModel getServiceAccount(ClientModel client) { - DBObject query = new QueryBuilder() - .and("serviceAccountClientLink").is(client.getId()) - .and("realmId").is(client.getRealm().getId()) - .get(); - MongoUserEntity userEntity = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext); - return userEntity == null ? null : new UserAdapter(session, client.getRealm(), userEntity, invocationContext); - } - - protected List convertUserEntities(RealmModel realm, List userEntities) { - List userModels = new ArrayList(); - for (MongoUserEntity user : userEntities) { - userModels.add(new UserAdapter(session, realm, user, invocationContext)); - } - return userModels; - } - - @Override - public List getUsers(RealmModel realm) { - return getUsers(realm, false); - } - - @Override - public List getUsers(RealmModel realm, int firstResult, int maxResults) { - return getUsers(realm, firstResult, maxResults, false); - } - - - - @Override - public List getUsers(RealmModel realm, boolean includeServiceAccounts) { - return getUsers(realm, -1, -1, includeServiceAccounts); - } - - @Override - public int getUsersCount(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - return getMongoStore().countEntities(MongoUserEntity.class, query, invocationContext); - } - - @Override - public List getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - - if (!includeServiceAccounts) { - queryBuilder = queryBuilder.and("serviceAccountClientLink").is(null); - } - - DBObject query = queryBuilder.get(); - DBObject sort = new BasicDBObject("username", 1); - List users = getMongoStore().loadEntities(MongoUserEntity.class, query, sort, firstResult, maxResults, invocationContext); - return convertUserEntities(realm, users); - } - - @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 + ")"); - - QueryBuilder nameBuilder; - int spaceInd = search.lastIndexOf(" "); - - // 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 (spaceInd != -1) { - String firstName = search.substring(0, spaceInd); - String lastName = search.substring(spaceInd + 1); - Pattern firstNamePattern = Pattern.compile("(?i:" + firstName + "$)"); - Pattern lastNamePattern = Pattern.compile("(?i:^" + lastName + ")"); - nameBuilder = new QueryBuilder().and( - new QueryBuilder().put("firstName").regex(firstNamePattern).get(), - new QueryBuilder().put("lastName").regex(lastNamePattern).get() - ); - } else { - // Case when we have search without spaces like "foo". The firstName OR lastName could be "foo" (everything case-insensitive) - nameBuilder = new QueryBuilder().or( - new QueryBuilder().put("firstName").regex(caseInsensitivePattern).get(), - new QueryBuilder().put("lastName").regex(caseInsensitivePattern).get() - ); - } - - QueryBuilder builder = new QueryBuilder().and( - new QueryBuilder().and("realmId").is(realm.getId()).get(), - new QueryBuilder().and("serviceAccountClientLink").is(null).get(), - new QueryBuilder().or( - new QueryBuilder().put("username").regex(caseInsensitivePattern).get(), - new QueryBuilder().put("email").regex(caseInsensitivePattern).get(), - nameBuilder.get() - - ).get() - ); - - DBObject sort = new BasicDBObject("username", 1); - - List users = getMongoStore().loadEntities(MongoUserEntity.class, builder.get(), sort, firstResult, maxResults, invocationContext); - return convertUserEntities(realm, users); - } - - @Override - public List searchForUser(Map attributes, RealmModel realm) { - return searchForUser(attributes, realm, -1, -1); - } - - @Override - public List searchForUser(Map attributes, RealmModel realm, int firstResult, int maxResults) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - - for (Map.Entry entry : attributes.entrySet()) { - if (entry.getKey().equalsIgnoreCase(UserModel.USERNAME)) { - queryBuilder.and(UserModel.USERNAME).regex(Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE)); - } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) { - queryBuilder.and(UserModel.FIRST_NAME).regex(Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE)); - - } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) { - queryBuilder.and(UserModel.LAST_NAME).regex(Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE)); - - } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) { - queryBuilder.and(UserModel.EMAIL).regex(Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE)); - } - } - - DBObject sort = new BasicDBObject("username", 1); - - List users = getMongoStore().loadEntities(MongoUserEntity.class, queryBuilder.get(), sort, firstResult, maxResults, invocationContext); - return convertUserEntities(realm, users); - } - - @Override - public List searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - queryBuilder.and("attributes." + attrName).is(attrValue); - - List users = getMongoStore().loadEntities(MongoUserEntity.class, queryBuilder.get(), invocationContext); - return convertUserEntities(realm, users); - } - - @Override - public Set getFederatedIdentities(UserModel userModel, RealmModel realm) { - UserAdapter user = getUserById(userModel.getId(), realm); - MongoUserEntity userEntity = user.getUser(); - 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(), federatedIdentityEntity.getToken()); - result.add(model); - } - return result; - } - - @Override - public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) { - UserAdapter mongoUser = getUserById(user.getId(), realm); - MongoUserEntity userEntity = mongoUser.getUser(); - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, socialProvider); - - return federatedIdentityEntity != null ? new FederatedIdentityModel(federatedIdentityEntity.getIdentityProvider(), federatedIdentityEntity.getUserId(), - federatedIdentityEntity.getUserName(), federatedIdentityEntity.getToken()) : null; - } - - @Override - public UserAdapter addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { - 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)); - } - } - for (GroupModel g : realm.getDefaultGroups()) { - userModel.joinGroup(g); - } - } - - if (addDefaultRequiredActions) { - for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) { - if (r.isEnabled() && r.isDefaultAction()) { - userModel.addRequiredAction(r.getAlias()); - } - } - } - - - return userModel; - } - - protected UserAdapter addUserEntity(RealmModel realm, String id, String username) { - MongoUserEntity userEntity = new MongoUserEntity(); - userEntity.setId(id); - userEntity.setUsername(username); - userEntity.setCreatedTimestamp(System.currentTimeMillis()); - // Compatibility with JPA model, which has user disabled by default - // userEntity.setEnabled(true); - userEntity.setRealmId(realm.getId()); - - getMongoStore().insertEntity(userEntity, invocationContext); - return new UserAdapter(session, realm, userEntity, invocationContext); - } - - @Override - public boolean removeUser(RealmModel realm, UserModel user) { - return getMongoStore().removeEntity(MongoUserEntity.class, user.getId(), invocationContext); - } - - - @Override - public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel identity) { - UserAdapter mongoUser = getUserById(user.getId(), realm); - MongoUserEntity userEntity = mongoUser.getUser(); - FederatedIdentityEntity federatedIdentityEntity = new FederatedIdentityEntity(); - federatedIdentityEntity.setIdentityProvider(identity.getIdentityProvider()); - federatedIdentityEntity.setUserId(identity.getUserId()); - federatedIdentityEntity.setUserName(identity.getUserName().toLowerCase()); - federatedIdentityEntity.setToken(identity.getToken()); - - getMongoStore().pushItemToList(userEntity, "federatedIdentities", federatedIdentityEntity, true, invocationContext); - } - - @Override - public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) { - UserAdapter mongoUser = getUserById(federatedUser.getId(), realm); - MongoUserEntity userEntity = mongoUser.getUser(); - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, federatedIdentityModel.getIdentityProvider()); - - //pushItemToList updates the whole federatedIdentities array in Mongo so we just need to remove this object from the Java - //List and pushItemToList will handle the DB update. - userEntity.getFederatedIdentities().remove(federatedIdentityEntity); - federatedIdentityEntity.setToken(federatedIdentityModel.getToken()); - getMongoStore().pushItemToList(userEntity, "federatedIdentities", federatedIdentityEntity, true, invocationContext); - } - - @Override - public boolean removeFederatedIdentity(RealmModel realm, UserModel userModel, String socialProvider) { - UserAdapter user = getUserById(userModel.getId(), realm); - MongoUserEntity userEntity = user.getUser(); - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, socialProvider); - if (federatedIdentityEntity == null) { - return false; - } - return getMongoStore().pullItemFromList(userEntity, "federatedIdentities", federatedIdentityEntity, invocationContext); - } - - private FederatedIdentityEntity findFederatedIdentityLink(MongoUserEntity 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 UserModel addUser(RealmModel realm, String username) { - return this.addUser(realm, null, username, true, true); - } - - @Override - public void grantToAllUsers(RealmModel realm, RoleModel role) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - - DBObject update = new QueryBuilder() - .and("$push").is(new BasicDBObject("roleIds", role.getId())) - .get(); - - int count = getMongoStore().updateEntities(MongoUserEntity.class, query, update, invocationContext); - } - - @Override - public void preRemove(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - getMongoStore().removeEntities(MongoUserEntity.class, query, true, invocationContext); - } - - @Override - public void preRemove(RealmModel realm, ClientModel client) { - // Remove all role mappings and consents mapped to all roles of this client - for (RoleModel role : client.getRoles()) { - preRemove(realm, role); - } - - // Finally remove all consents of this client - DBObject query = new QueryBuilder() - .and("clientId").is(client.getId()) - .get(); - getMongoStore().removeEntities(MongoUserConsentEntity.class, query, false, invocationContext); - } - - @Override - public void preRemove(ProtocolMapperModel protocolMapper) { - // Remove this protocol mapper from all consents, which has it - DBObject query = new QueryBuilder() - .and("grantedProtocolMappers").is(protocolMapper.getId()) - .get(); - DBObject pull = new BasicDBObject("$pull", query); - getMongoStore().updateEntities(MongoUserConsentEntity.class, query, pull, invocationContext); - } - - @Override - public void preRemove(RealmModel realm, GroupModel group) { - // Remove this role from all users, which has it - DBObject query = new QueryBuilder() - .and("groupIds").is(group.getId()) - .get(); - - DBObject pull = new BasicDBObject("$pull", query); - getMongoStore().updateEntities(MongoUserEntity.class, query, pull, invocationContext); - } - - @Override - public void preRemove(RealmModel realm, RoleModel role) { - // Remove this role from all users, which has it - DBObject query = new QueryBuilder() - .and("roleIds").is(role.getId()) - .get(); - - DBObject pull = new BasicDBObject("$pull", query); - getMongoStore().updateEntities(MongoUserEntity.class, query, pull, invocationContext); - - // Remove this role from all consents, which has it - query = new QueryBuilder() - .and("grantedRoles").is(role.getId()) - .get(); - pull = new BasicDBObject("$pull", query); - getMongoStore().updateEntities(MongoUserConsentEntity.class, query, pull, invocationContext); - } - - @Override - public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { - String clientId = consent.getClient().getId(); - if (getConsentEntityByClientId(userId, clientId) != null) { - throw new ModelDuplicateException("Consent already exists for client [" + clientId + "] and user [" + userId + "]"); - } - - long currentTime = Time.currentTimeMillis(); - - MongoUserConsentEntity consentEntity = new MongoUserConsentEntity(); - consentEntity.setUserId(userId); - consentEntity.setClientId(clientId); - consentEntity.setCreatedDate(currentTime); - consentEntity.setLastUpdatedDate(currentTime); - fillEntityFromModel(consent, consentEntity); - getMongoStore().insertEntity(consentEntity, invocationContext); - } - - @Override - public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientId) { - UserConsentEntity consentEntity = getConsentEntityByClientId(userId, clientId); - return consentEntity!=null ? toConsentModel(realm, consentEntity) : null; - } - - @Override - public List getConsents(RealmModel realm, String userId) { - List result = new ArrayList(); - - DBObject query = new QueryBuilder() - .and("userId").is(userId) - .get(); - List grantedConsents = getMongoStore().loadEntities(MongoUserConsentEntity.class, query, invocationContext); - - for (UserConsentEntity consentEntity : grantedConsents) { - UserConsentModel model = toConsentModel(realm, consentEntity); - result.add(model); - } - - return result; - } - - private MongoUserConsentEntity getConsentEntityByClientId(String userId, String clientId) { - DBObject query = new QueryBuilder() - .and("userId").is(userId) - .and("clientId").is(clientId) - .get(); - return getMongoStore().loadSingleEntity(MongoUserConsentEntity.class, query, invocationContext); - } - - private UserConsentModel toConsentModel(RealmModel realm, UserConsentEntity entity) { - ClientModel client = realm.getClientById(entity.getClientId()); - if (client == null) { - throw new ModelException("Client with id " + entity.getClientId() + " is not available"); - } - UserConsentModel model = new UserConsentModel(client); - model.setCreatedDate(entity.getCreatedDate()); - model.setLastUpdatedDate(entity.getLastUpdatedDate()); - - for (String roleId : entity.getGrantedRoles()) { - RoleModel roleModel = realm.getRoleById(roleId); - if (roleModel != null) { - model.addGrantedRole(roleModel); - } - } - - for (String protMapperId : entity.getGrantedProtocolMappers()) { - ProtocolMapperModel protocolMapper = client.getProtocolMapperById(protMapperId); - model.addGrantedProtocolMapper(protocolMapper); - } - return model; - } - - // Fill roles and protocolMappers to entity - private void fillEntityFromModel(UserConsentModel consent, MongoUserConsentEntity consentEntity) { - List roleIds = new LinkedList(); - for (RoleModel role : consent.getGrantedRoles()) { - roleIds.add(role.getId()); - } - consentEntity.setGrantedRoles(roleIds); - - List protMapperIds = new LinkedList(); - for (ProtocolMapperModel protMapperModel : consent.getGrantedProtocolMappers()) { - protMapperIds.add(protMapperModel.getId()); - } - consentEntity.setGrantedProtocolMappers(protMapperIds); - consentEntity.setLastUpdatedDate(Time.currentTimeMillis()); - } - - @Override - public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) { - String clientId = consent.getClient().getId(); - MongoUserConsentEntity consentEntity = getConsentEntityByClientId(userId, clientId); - if (consentEntity == null) { - throw new ModelException("Consent not found for client [" + clientId + "] and user [" + userId + "]"); - } else { - fillEntityFromModel(consent, consentEntity); - getMongoStore().updateEntity(consentEntity, invocationContext); - } - } - - @Override - public boolean revokeConsentForClient(RealmModel realm, String userId, String clientId) { - MongoUserConsentEntity entity = getConsentEntityByClientId(userId, clientId); - if (entity == null) { - return false; - } - - return getMongoStore().removeEntity(entity, invocationContext); - } - - @Override - public void preRemove(RealmModel realm, ComponentModel component) { - if (!component.getProviderType().equals(UserStorageProvider.class.getName())) return; - String providerId = component.getId(); - removeImportedUsers(realm, providerId); - } - - @Override - public void removeImportedUsers(RealmModel realm, String providerId) { - DBObject query = new QueryBuilder() - .and("federationLink").is(providerId) - .get(); - - List mongoUsers = getMongoStore().loadEntities(MongoUserEntity.class, query, invocationContext); - UserManager userManager = new UserManager(session); - - for (MongoUserEntity userEntity : mongoUsers) { - // Doing this way to ensure UserRemovedEvent triggered with proper callbacks. - UserAdapter user = new UserAdapter(session, realm, userEntity, invocationContext); - userManager.removeUser(realm, user, this); - } - } - - @Override - public void unlinkUsers(RealmModel realm, String storageProviderId) { - DBObject query = new QueryBuilder() - .and("federationLink").is(storageProviderId) - .get(); - - List mongoUsers = getMongoStore().loadEntities(MongoUserEntity.class, query, invocationContext); - - for (MongoUserEntity userEntity : mongoUsers) { - // Doing this way to ensure UserRemovedEvent triggered with proper callbacks. - UserAdapter user = new UserAdapter(session, realm, userEntity, invocationContext); - user.setFederationLink(null); - } - - } - - @Override - public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) { - MongoUserEntity mongoUser = getMongoUserEntity(user); - CredentialEntity credentialEntity = getCredentialEntity(cred, mongoUser); - if (credentialEntity == null) return; - // old store may not have id set - if (credentialEntity.getId() == null) credentialEntity.setId(KeycloakModelUtils.generateId()); - setValues(cred, credentialEntity); - getMongoStore().updateEntity(mongoUser, invocationContext); - - } - - public CredentialEntity getCredentialEntity(CredentialModel cred, MongoUserEntity mongoUser) { - CredentialEntity credentialEntity = null; - // old store may not have id set - for (CredentialEntity entity : mongoUser.getCredentials()) { - if (cred.getId() != null && cred.getId().equals(entity.getId())) { - credentialEntity = entity; - break; - } else if (cred.getType().equals(entity.getType())) { - credentialEntity = entity; - break; - } - } - return credentialEntity; - } - - public MongoUserEntity getMongoUserEntity(UserModel user) { - if (user instanceof UserAdapter) { - UserAdapter adapter = (UserAdapter)user; - return adapter.getMongoEntity(); - } else if (user instanceof CachedUserModel) { - UserModel delegate = ((CachedUserModel)user).getDelegateForUpdate(); - return getMongoUserEntity(delegate); - } else if (user instanceof UserModelDelegate){ - UserModel delegate = ((UserModelDelegate) user).getDelegate(); - return getMongoUserEntity(delegate); - } else { - return getMongoStore().loadEntity(MongoUserEntity.class, user.getId(), invocationContext); - } - } - - @Override - public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) { - MongoUserEntity mongoUser = getMongoUserEntity(user); - CredentialEntity credentialEntity = new CredentialEntity(); - credentialEntity.setId(KeycloakModelUtils.generateId()); - setValues(cred, credentialEntity); - cred.setId(credentialEntity.getId()); - mongoUser.getCredentials().add(credentialEntity); - getMongoStore().updateEntity(mongoUser, invocationContext); - cred.setId(credentialEntity.getId()); - return cred; - } - - public void setValues(CredentialModel cred, CredentialEntity credentialEntity) { - credentialEntity.setType(cred.getType()); - credentialEntity.setDevice(cred.getDevice()); - credentialEntity.setValue(cred.getValue()); - credentialEntity.setSalt(cred.getSalt()); - credentialEntity.setDevice(cred.getDevice()); - credentialEntity.setHashIterations(cred.getHashIterations()); - credentialEntity.setCounter(cred.getCounter()); - credentialEntity.setAlgorithm(cred.getAlgorithm()); - credentialEntity.setDigits(cred.getDigits()); - credentialEntity.setPeriod(cred.getPeriod()); - if (cred.getConfig() == null) { - credentialEntity.setConfig(null); - } - else { - if (credentialEntity.getConfig() == null) credentialEntity.setConfig(new MultivaluedHashMap<>()); - credentialEntity.getConfig().clear(); - credentialEntity.getConfig().putAll(cred.getConfig()); - } - } - - @Override - public boolean removeStoredCredential(RealmModel realm, UserModel user, String id) { - MongoUserEntity mongoUser = getMongoUserEntity(user); - Iterator it = mongoUser.getCredentials().iterator(); - while (it.hasNext()) { - CredentialEntity entity = it.next(); - if (id.equals(entity.getId())) { - it.remove(); - getMongoStore().updateEntity(mongoUser, invocationContext); - return true; - } - } - return false; - } - - @Override - public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) { - MongoUserEntity mongoUser = getMongoUserEntity(user); - for (CredentialEntity credEntity : mongoUser.getCredentials()) { - if(id.equals(credEntity.getId())) { - if (credEntity.getId() == null) { - credEntity.setId(KeycloakModelUtils.generateId()); - getMongoStore().updateEntity(mongoUser, invocationContext); - } - return toModel(credEntity); - } - - } - return null; - } - - public CredentialModel toModel(CredentialEntity credEntity) { - CredentialModel credModel = new CredentialModel(); - credModel.setId(credEntity.getId()); - credModel.setType(credEntity.getType()); - credModel.setDevice(credEntity.getDevice()); - credModel.setCreatedDate(credEntity.getCreatedDate()); - credModel.setValue(credEntity.getValue()); - credModel.setSalt(credEntity.getSalt()); - credModel.setHashIterations(credEntity.getHashIterations()); - credModel.setAlgorithm(credEntity.getAlgorithm()); - credModel.setCounter(credEntity.getCounter()); - credModel.setPeriod(credEntity.getPeriod()); - credModel.setDigits(credEntity.getDigits()); - if (credEntity.getConfig() != null) { - credModel.setConfig(new MultivaluedHashMap<>()); - credModel.getConfig().putAll(credEntity.getConfig()); - } - return credModel; - } - - @Override - public List getStoredCredentials(RealmModel realm, UserModel user) { - List list = new LinkedList<>(); - MongoUserEntity mongoUser = getMongoUserEntity(user); - boolean update = false; - for (CredentialEntity credEntity : mongoUser.getCredentials()) { - if (credEntity.getId() == null) { - credEntity.setId(KeycloakModelUtils.generateId()); - update = true; - } - CredentialModel credModel = toModel(credEntity); - list.add(credModel); - - } - if (update) getMongoStore().updateEntity(mongoUser, invocationContext); - return list; - - } - - @Override - public List getStoredCredentialsByType(RealmModel realm, UserModel user, String type) { - List list = new LinkedList<>(); - MongoUserEntity mongoUser = getMongoUserEntity(user); - boolean update = false; - for (CredentialEntity credEntity : mongoUser.getCredentials()) { - if (credEntity.getId() == null) { - credEntity.setId(KeycloakModelUtils.generateId()); - update = true; - } - if (credEntity.getType().equals(type)) { - CredentialModel credModel = toModel(credEntity); - list.add(credModel); - } - } - if (update) getMongoStore().updateEntity(mongoUser, invocationContext); - return list; - } - - @Override - public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, UserModel user, String name, String type) { - MongoUserEntity mongoUser = getMongoUserEntity(user); - boolean update = false; - CredentialModel credModel = null; - for (CredentialEntity credEntity : mongoUser.getCredentials()) { - if (credEntity.getId() == null) { - credEntity.setId(KeycloakModelUtils.generateId()); - update = true; - } - if (credEntity.getType().equals(type) && name.equals(credEntity.getDevice())) { - credModel = toModel(credEntity); - break; - } - } - if (update) getMongoStore().updateEntity(mongoUser, invocationContext); - return credModel; - } - - // Could override this to provide a custom behavior. - protected void ensureEmailConstraint(List users, RealmModel realm) { - MongoUserEntity user = users.get(0); - - if (users.size() > 1) { - // Realm settings have been changed from allowing duplicate emails to not allowing them - // but duplicates haven't been removed. - throw new ModelDuplicateException("Multiple users with email '" + user.getEmail() + "' exist in Keycloak."); - } - - if (realm.isDuplicateEmailsAllowed()) { - return; - } - - if (user.getEmail() != null && user.getEmailIndex() == null) { - // Realm settings have been changed from allowing duplicate emails to not allowing them. - // We need to update the email index to reflect this change in the user entities. - user.setEmail(user.getEmail(), false); - getMongoStore().updateEntity(user, invocationContext); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProviderFactory.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProviderFactory.java deleted file mode 100755 index 29e9c55b737..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProviderFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.jboss.logging.Logger; -import org.keycloak.Config; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.UserProvider; -import org.keycloak.models.UserProviderFactory; - -/** - * KeycloakSessionFactory implementation based on MongoDB - * - * @author Marek Posolda - */ -public class MongoUserProviderFactory implements UserProviderFactory { - protected static final Logger logger = Logger.getLogger(MongoUserProviderFactory.class); - - @Override - public String getId() { - return "mongo"; - } - - @Override - public void init(Config.Scope config) { - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - - @Override - public UserProvider create(KeycloakSession session) { - MongoConnectionProvider connection = session.getProvider(MongoConnectionProvider.class); - return new MongoUserProvider(session, connection.getInvocationContext()); - } - - @Override - public void close() { - } - -} - diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProvider.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProvider.java deleted file mode 100644 index fecbd934b39..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProvider.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.ClientModel; -import org.keycloak.models.ClientSessionModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelException; -import org.keycloak.models.RealmModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.UserSessionModel; -import org.keycloak.models.mongo.keycloak.entities.MongoOfflineUserSessionEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoOnlineUserSessionEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoUserSessionEntity; -import org.keycloak.models.mongo.keycloak.entities.PersistentClientSessionEntity; -import org.keycloak.models.mongo.keycloak.entities.PersistentUserSessionEntity; -import org.keycloak.models.session.PersistentClientSessionAdapter; -import org.keycloak.models.session.PersistentClientSessionModel; -import org.keycloak.models.session.PersistentUserSessionAdapter; -import org.keycloak.models.session.PersistentUserSessionModel; -import org.keycloak.models.session.UserSessionPersisterProvider; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * @author Marek Posolda - */ -public class MongoUserSessionPersisterProvider implements UserSessionPersisterProvider { - - private final MongoStoreInvocationContext invocationContext; - private final KeycloakSession session; - - public MongoUserSessionPersisterProvider(KeycloakSession session, MongoStoreInvocationContext invocationContext) { - this.session = session; - this.invocationContext = invocationContext; - } - - protected MongoStore getMongoStore() { - return invocationContext.getMongoStore(); - } - - private MongoUserSessionEntity loadUserSession(String userSessionId, boolean offline) { - Class clazz = offline ? MongoOfflineUserSessionEntity.class : MongoOnlineUserSessionEntity.class; - return getMongoStore().loadEntity(clazz, userSessionId, invocationContext); - } - - @Override - public void createUserSession(UserSessionModel userSession, boolean offline) { - PersistentUserSessionAdapter adapter = new PersistentUserSessionAdapter(userSession); - PersistentUserSessionModel model = adapter.getUpdatedModel(); - - MongoUserSessionEntity entity = offline ? new MongoOfflineUserSessionEntity() : new MongoOnlineUserSessionEntity(); - entity.setId(model.getUserSessionId()); - entity.setRealmId(adapter.getRealm().getId()); - entity.setUserId(adapter.getUser().getId()); - entity.setLastSessionRefresh(model.getLastSessionRefresh()); - entity.setData(model.getData()); - entity.setClientSessions(new ArrayList()); - getMongoStore().insertEntity(entity, invocationContext); - } - - @Override - public void createClientSession(ClientSessionModel clientSession, boolean offline) { - PersistentClientSessionAdapter adapter = new PersistentClientSessionAdapter(clientSession); - PersistentClientSessionModel model = adapter.getUpdatedModel(); - - MongoUserSessionEntity userSession = loadUserSession(model.getUserSessionId(), offline); - if (userSession == null) { - throw new ModelException("Not userSession found with ID " + clientSession.getUserSession().getId() + ". Requested by clientSession: " + clientSession.getId()); - } else { - PersistentClientSessionEntity entity = new PersistentClientSessionEntity(); - entity.setClientSessionId(clientSession.getId()); - entity.setClientId(clientSession.getClient().getId()); - entity.setData(model.getData()); - userSession.getClientSessions().add(entity); - getMongoStore().updateEntity(userSession, invocationContext); - } - } - - @Override - public void updateUserSession(UserSessionModel userSession, boolean offline) { - PersistentUserSessionAdapter adapter; - if (userSession instanceof PersistentUserSessionAdapter) { - adapter = (PersistentUserSessionAdapter) userSession; - } else { - adapter = new PersistentUserSessionAdapter(userSession); - } - - PersistentUserSessionModel model = adapter.getUpdatedModel(); - - MongoUserSessionEntity entity = loadUserSession(model.getUserSessionId(), offline); - if (entity == null) { - throw new ModelException("UserSession with ID " + userSession.getId() + ", offline: " + offline + " not found"); - } - entity.setLastSessionRefresh(model.getLastSessionRefresh()); - entity.setData(model.getData()); - - getMongoStore().updateEntity(entity, invocationContext); - } - - @Override - public void removeUserSession(String userSessionId, boolean offline) { - MongoUserSessionEntity entity = loadUserSession(userSessionId, offline); - if (entity != null) { - getMongoStore().removeEntity(entity, invocationContext); - } - } - - @Override - public void removeClientSession(String clientSessionId, boolean offline) { - DBObject query = new QueryBuilder() - .and("clientSessions.clientSessionId").is(clientSessionId) - .get(); - Class clazz = offline ? MongoOfflineUserSessionEntity.class : MongoOnlineUserSessionEntity.class; - MongoUserSessionEntity userSession = getMongoStore().loadSingleEntity(clazz, query, invocationContext); - if (userSession != null) { - - PersistentClientSessionEntity found = null; - for (PersistentClientSessionEntity clientSession : userSession.getClientSessions()) { - if (clientSession.getClientSessionId().equals(clientSessionId)) { - found = clientSession; - break; - } - } - - if (found != null) { - userSession.getClientSessions().remove(found); - - // Remove userSession if it was last clientSession attached - if (userSession.getClientSessions().size() == 0) { - getMongoStore().removeEntity(userSession, invocationContext); - } else { - getMongoStore().updateEntity(userSession, invocationContext); - } - } - } - } - - @Override - public void onRealmRemoved(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - getMongoStore().removeEntities(MongoOnlineUserSessionEntity.class, query, false, invocationContext); - getMongoStore().removeEntities(MongoOfflineUserSessionEntity.class, query, false, invocationContext); - } - - @Override - public void onClientRemoved(RealmModel realm, ClientModel client) { - DBObject query = new QueryBuilder() - .and("clientSessions.clientId").is(client.getId()) - .get(); - - List userSessions = getMongoStore().loadEntities(MongoOnlineUserSessionEntity.class, query, invocationContext); - for (MongoOnlineUserSessionEntity userSession : userSessions) { - removeClientSessionOfClient(userSession, client.getId()); - } - - List userSessions2 = getMongoStore().loadEntities(MongoOfflineUserSessionEntity.class, query, invocationContext); - for (MongoOfflineUserSessionEntity userSession : userSessions2) { - removeClientSessionOfClient(userSession, client.getId()); - } - } - - private void removeClientSessionOfClient(MongoUserSessionEntity userSession, String clientId) { - PersistentClientSessionEntity found = null; - for (PersistentClientSessionEntity clientSession : userSession.getClientSessions()) { - if (clientSession.getClientId().equals(clientId)) { - found = clientSession; - break; - } - } - - if (found != null) { - userSession.getClientSessions().remove(found); - - // Remove userSession if it was last clientSession attached - if (userSession.getClientSessions().size() == 0) { - getMongoStore().removeEntity(userSession, invocationContext); - } else { - getMongoStore().updateEntity(userSession, invocationContext); - } - } - } - - @Override - public void onUserRemoved(RealmModel realm, UserModel user) { - onUserRemoved(realm, user.getId()); - } - - private void onUserRemoved(RealmModel realm, String userId) { - DBObject query = new QueryBuilder() - .and("userId").is(userId) - .get(); - getMongoStore().removeEntities(MongoOnlineUserSessionEntity.class, query, false, invocationContext); - getMongoStore().removeEntities(MongoOfflineUserSessionEntity.class, query, false, invocationContext); - } - - @Override - public void clearDetachedUserSessions() { - DBObject query = new QueryBuilder() - .and("clientSessions").is(Collections.emptyList()) - .get(); - getMongoStore().removeEntities(MongoOnlineUserSessionEntity.class, query, false, invocationContext); - getMongoStore().removeEntities(MongoOfflineUserSessionEntity.class, query, false, invocationContext); - } - - @Override - public int getUserSessionsCount(boolean offline) { - DBObject query = new QueryBuilder() - .get(); - - Class clazz = offline ? MongoOfflineUserSessionEntity.class : MongoOnlineUserSessionEntity.class; - return getMongoStore().countEntities(clazz, query, invocationContext); - } - - @Override - public void updateAllTimestamps(int time) { - // 1) Update timestamp of clientSessions - - DBObject timestampSubquery = new QueryBuilder() - .and("timestamp").notEquals(time).get(); - - DBObject query = new QueryBuilder() - .and("clientSessions").elemMatch(timestampSubquery).get(); - - - DBObject update = new QueryBuilder() - .and("$set").is(new BasicDBObject("clientSessions.$.timestamp", time)).get(); - - // Not sure how to do in single query :/ - int countModified = 1; - while (countModified > 0) { - countModified = getMongoStore().updateEntities(MongoOfflineUserSessionEntity.class, query, update, invocationContext); - } - - countModified = 1; - while (countModified > 0) { - countModified = getMongoStore().updateEntities(MongoOnlineUserSessionEntity.class, query, update, invocationContext); - } - - // 2) update lastSessionRefresh of userSessions - query = new QueryBuilder().get(); - - update = new QueryBuilder() - .and("$set").is(new BasicDBObject("lastSessionRefresh", time)).get(); - - getMongoStore().updateEntities(MongoOfflineUserSessionEntity.class, query, update, invocationContext); - getMongoStore().updateEntities(MongoOnlineUserSessionEntity.class, query, update, invocationContext); - } - - @Override - public List loadUserSessions(int firstResult, int maxResults, boolean offline) { - DBObject query = new QueryBuilder() - .get(); - DBObject sort = new BasicDBObject("id", 1); - - Class clazz = offline ? MongoOfflineUserSessionEntity.class : MongoOnlineUserSessionEntity.class; - - List entities = getMongoStore().loadEntities(clazz, query, sort, firstResult, maxResults, invocationContext); - - List results = new LinkedList<>(); - for (MongoUserSessionEntity entity : entities) { - RealmModel realm = session.realms().getRealm(entity.getRealmId()); - UserModel user = session.users().getUserById(entity.getUserId(), realm); - - // Case when user was deleted in the meantime - if (user == null) { - onUserRemoved(realm, entity.getUserId()); - return loadUserSessions(firstResult, maxResults, offline); - } - - PersistentUserSessionAdapter userSession = toAdapter(realm, user, entity); - results.add(userSession); - } - return results; - } - - private PersistentUserSessionAdapter toAdapter(RealmModel realm, UserModel user, PersistentUserSessionEntity entity) { - PersistentUserSessionModel model = new PersistentUserSessionModel(); - model.setUserSessionId(entity.getId()); - model.setLastSessionRefresh(entity.getLastSessionRefresh()); - model.setData(entity.getData()); - - List clientSessions = new LinkedList<>(); - PersistentUserSessionAdapter userSessionAdapter = new PersistentUserSessionAdapter(model, realm, user, clientSessions); - for (PersistentClientSessionEntity clientSessEntity : entity.getClientSessions()) { - PersistentClientSessionAdapter clientSessAdapter = toAdapter(realm, userSessionAdapter, clientSessEntity); - clientSessions.add(clientSessAdapter); - } - - return userSessionAdapter; - } - - private PersistentClientSessionAdapter toAdapter(RealmModel realm, PersistentUserSessionAdapter userSession, PersistentClientSessionEntity entity) { - ClientModel client = realm.getClientById(entity.getClientId()); - - PersistentClientSessionModel model = new PersistentClientSessionModel(); - model.setClientSessionId(entity.getClientSessionId()); - model.setClientId(entity.getClientId()); - model.setUserSessionId(userSession.getId()); - model.setUserId(userSession.getUser().getId()); - model.setTimestamp(entity.getTimestamp()); - model.setData(entity.getData()); - return new PersistentClientSessionAdapter(model, realm, client, userSession); - } - - @Override - public void close() { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProviderFactory.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProviderFactory.java deleted file mode 100644 index 083a0e67493..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserSessionPersisterProviderFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.keycloak.Config; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.session.UserSessionPersisterProvider; -import org.keycloak.models.session.UserSessionPersisterProviderFactory; - -/** - * @author Marek Posolda - */ -public class MongoUserSessionPersisterProviderFactory implements UserSessionPersisterProviderFactory { - - public static final String ID = "mongo"; - - @Override - public UserSessionPersisterProvider create(KeycloakSession session) { - MongoConnectionProvider connection = session.getProvider(MongoConnectionProvider.class); - return new MongoUserSessionPersisterProvider(session, connection.getInvocationContext()); - } - - @Override - public void init(Config.Scope config) { - - } - - @Override - public void close() { - - } - - @Override - public String getId() { - return ID; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java deleted file mode 100755 index 3854989a875..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java +++ /dev/null @@ -1,1931 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.common.enums.SslRequired; -import org.keycloak.common.util.MultivaluedHashMap; -import org.keycloak.component.ComponentFactory; -import org.keycloak.component.ComponentModel; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.AuthenticationExecutionModel; -import org.keycloak.models.AuthenticationFlowModel; -import org.keycloak.models.AuthenticatorConfigModel; -import org.keycloak.models.ClientModel; -import org.keycloak.models.ClientTemplateModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.IdentityProviderMapperModel; -import org.keycloak.models.IdentityProviderModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ModelException; -import org.keycloak.models.OTPPolicy; -import org.keycloak.models.PasswordPolicy; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RealmProvider; -import org.keycloak.models.RequiredActionProviderModel; -import org.keycloak.models.RequiredCredentialModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.mongo.keycloak.entities.AuthenticationExecutionEntity; -import org.keycloak.models.mongo.keycloak.entities.AuthenticationFlowEntity; -import org.keycloak.models.mongo.keycloak.entities.AuthenticatorConfigEntity; -import org.keycloak.models.mongo.keycloak.entities.ComponentEntity; -import org.keycloak.models.mongo.keycloak.entities.IdentityProviderEntity; -import org.keycloak.models.mongo.keycloak.entities.IdentityProviderMapperEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoClientTemplateEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; -import org.keycloak.models.mongo.keycloak.entities.RequiredActionProviderEntity; -import org.keycloak.models.mongo.keycloak.entities.RequiredCredentialEntity; -import org.keycloak.models.utils.ComponentUtil; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -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; - -/** - * @author Marek Posolda - */ -public class RealmAdapter extends AbstractMongoAdapter implements RealmModel { - - private final MongoRealmEntity realm; - private final RealmProvider model; - - private volatile transient OTPPolicy otpPolicy; - private volatile transient PasswordPolicy passwordPolicy; - private volatile transient KeycloakSession session; - - public RealmAdapter(KeycloakSession session, MongoRealmEntity realmEntity, MongoStoreInvocationContext invocationContext) { - super(invocationContext); - this.realm = realmEntity; - this.session = session; - this.model = session.realms(); - } - - @Override - public String getId() { - return realm.getId(); - } - - @Override - public String getName() { - return realm.getName(); - } - - @Override - public void setName(String name) { - realm.setName(name); - updateRealm(); - } - - @Override - public String getDisplayName() { - return realm.getDisplayName(); - } - - @Override - public void setDisplayName(String displayName) { - realm.setDisplayName(displayName); - updateRealm(); - } - - @Override - public String getDisplayNameHtml() { - return realm.getDisplayNameHtml(); - } - - @Override - public void setDisplayNameHtml(String displayNameHtml) { - realm.setDisplayNameHtml(displayNameHtml); - updateRealm(); - } - - @Override - public boolean isEnabled() { - return realm.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - realm.setEnabled(enabled); - updateRealm(); - } - - @Override - public SslRequired getSslRequired() { - return realm.getSslRequired() != null ? SslRequired.valueOf(realm.getSslRequired()) : null; - } - - @Override - public void setSslRequired(SslRequired sslRequired) { - realm.setSslRequired(sslRequired.name()); - updateRealm(); - } - - @Override - public boolean isRegistrationAllowed() { - return realm.isRegistrationAllowed(); - } - - @Override - public void setRegistrationAllowed(boolean registrationAllowed) { - realm.setRegistrationAllowed(registrationAllowed); - updateRealm(); - } - - @Override - public boolean isRegistrationEmailAsUsername() { - return realm.isRegistrationEmailAsUsername(); - } - - @Override - public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) { - realm.setRegistrationEmailAsUsername(registrationEmailAsUsername); - if (registrationEmailAsUsername) realm.setDuplicateEmailsAllowed(false); - updateRealm(); - } - - @Override - public boolean isRememberMe() { - return realm.isRememberMe(); - } - - @Override - public void setRememberMe(boolean rememberMe) { - realm.setRememberMe(rememberMe); - updateRealm(); - } - - @Override - public boolean isBruteForceProtected() { - return realm.isBruteForceProtected(); - } - - @Override - public void setBruteForceProtected(boolean value) { - realm.setBruteForceProtected(value); - updateRealm(); - } - - @Override - public int getMaxFailureWaitSeconds() { - return realm.getMaxFailureWaitSeconds(); - } - - @Override - public void setMaxFailureWaitSeconds(int val) { - realm.setMaxFailureWaitSeconds(val); - updateRealm(); - } - - @Override - public int getWaitIncrementSeconds() { - return realm.getWaitIncrementSeconds(); - } - - @Override - public void setWaitIncrementSeconds(int val) { - realm.setWaitIncrementSeconds(val); - updateRealm(); - } - - @Override - public long getQuickLoginCheckMilliSeconds() { - return realm.getQuickLoginCheckMilliSeconds(); - } - - @Override - public void setQuickLoginCheckMilliSeconds(long val) { - realm.setQuickLoginCheckMilliSeconds(val); - updateRealm(); - } - - @Override - public int getMinimumQuickLoginWaitSeconds() { - return realm.getMinimumQuickLoginWaitSeconds(); - } - - @Override - public void setMinimumQuickLoginWaitSeconds(int val) { - realm.setMinimumQuickLoginWaitSeconds(val); - updateRealm(); - } - - - @Override - public int getMaxDeltaTimeSeconds() { - return realm.getMaxDeltaTimeSeconds(); - } - - @Override - public void setMaxDeltaTimeSeconds(int val) { - realm.setMaxDeltaTimeSeconds(val); - updateRealm(); - } - - @Override - public int getFailureFactor() { - return realm.getFailureFactor(); - } - - @Override - public void setFailureFactor(int failureFactor) { - realm.setFailureFactor(failureFactor); - updateRealm(); - } - - - @Override - public boolean isVerifyEmail() { - return realm.isVerifyEmail(); - } - - @Override - public void setVerifyEmail(boolean verifyEmail) { - realm.setVerifyEmail(verifyEmail); - updateRealm(); - } - - @Override - public boolean isLoginWithEmailAllowed() { - return realm.isLoginWithEmailAllowed(); - } - - @Override - public void setLoginWithEmailAllowed(boolean loginWithEmailAllowed) { - realm.setLoginWithEmailAllowed(loginWithEmailAllowed); - if (loginWithEmailAllowed) realm.setDuplicateEmailsAllowed(false); - updateRealm(); - } - - @Override - public boolean isDuplicateEmailsAllowed() { - return realm.isDuplicateEmailsAllowed(); - } - - @Override - public void setDuplicateEmailsAllowed(boolean duplicateEmailsAllowed) { - realm.setDuplicateEmailsAllowed(duplicateEmailsAllowed); - if (duplicateEmailsAllowed) { - realm.setLoginWithEmailAllowed(false); - realm.setRegistrationEmailAsUsername(false); - } - updateRealm(); - } - - @Override - public boolean isResetPasswordAllowed() { - return realm.isResetPasswordAllowed(); - } - - @Override - public void setResetPasswordAllowed(boolean resetPassword) { - realm.setResetPasswordAllowed(resetPassword); - updateRealm(); - } - - @Override - public boolean isEditUsernameAllowed() { - return realm.isEditUsernameAllowed(); - } - - @Override - public void setEditUsernameAllowed(boolean editUsernameAllowed) { - realm.setEditUsernameAllowed(editUsernameAllowed); - updateRealm(); - } - - @Override - public PasswordPolicy getPasswordPolicy() { - if (passwordPolicy == null) { - passwordPolicy = PasswordPolicy.parse(session, realm.getPasswordPolicy()); - } - return passwordPolicy; - } - - @Override - public void setPasswordPolicy(PasswordPolicy policy) { - this.passwordPolicy = policy; - realm.setPasswordPolicy(policy.toString()); - updateRealm(); - } - - @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()); - updateRealm(); - } - - - @Override - public int getNotBefore() { - return realm.getNotBefore(); - } - - @Override - public void setNotBefore(int notBefore) { - realm.setNotBefore(notBefore); - updateRealm(); - } - - @Override - public boolean isRevokeRefreshToken() { - return realm.isRevokeRefreshToken(); - } - - @Override - public void setRevokeRefreshToken(boolean revokeRefreshToken) { - realm.setRevokeRefreshToken(revokeRefreshToken); - updateRealm(); - } - - @Override - public int getSsoSessionIdleTimeout() { - return realm.getSsoSessionIdleTimeout(); - } - - @Override - public void setSsoSessionIdleTimeout(int seconds) { - realm.setSsoSessionIdleTimeout(seconds); - updateRealm(); - } - - @Override - public int getSsoSessionMaxLifespan() { - return realm.getSsoSessionMaxLifespan(); - } - - @Override - public void setSsoSessionMaxLifespan(int seconds) { - realm.setSsoSessionMaxLifespan(seconds); - updateRealm(); - } - - @Override - public int getOfflineSessionIdleTimeout() { - return realm.getOfflineSessionIdleTimeout(); - } - - @Override - public void setOfflineSessionIdleTimeout(int seconds) { - realm.setOfflineSessionIdleTimeout(seconds); - updateRealm(); - } - - @Override - public int getAccessTokenLifespan() { - return realm.getAccessTokenLifespan(); - } - - @Override - public void setAccessTokenLifespan(int tokenLifespan) { - realm.setAccessTokenLifespan(tokenLifespan); - updateRealm(); - } - - @Override - public int getAccessTokenLifespanForImplicitFlow() { - return realm.getAccessTokenLifespanForImplicitFlow(); - } - - @Override - public void setAccessTokenLifespanForImplicitFlow(int seconds) { - realm.setAccessTokenLifespanForImplicitFlow(seconds); - updateRealm(); - } - - @Override - public int getAccessCodeLifespan() { - return realm.getAccessCodeLifespan(); - } - - @Override - public void setAccessCodeLifespan(int accessCodeLifespan) { - realm.setAccessCodeLifespan(accessCodeLifespan); - updateRealm(); - } - - @Override - public int getAccessCodeLifespanUserAction() { - return realm.getAccessCodeLifespanUserAction(); - } - - @Override - public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { - realm.setAccessCodeLifespanUserAction(accessCodeLifespanUserAction); - updateRealm(); - } - - @Override - public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) { - realm.setAccessCodeLifespanLogin(accessCodeLifespanLogin); - updateRealm(); - } - - @Override - public int getAccessCodeLifespanLogin() { - return realm.getAccessCodeLifespanLogin(); - } - - @Override - public String getLoginTheme() { - return realm.getLoginTheme(); - } - - @Override - public void setLoginTheme(String name) { - realm.setLoginTheme(name); - updateRealm(); - } - - @Override - public String getAccountTheme() { - return realm.getAccountTheme(); - } - - @Override - public void setAccountTheme(String name) { - realm.setAccountTheme(name); - updateRealm(); - } - - @Override - public String getAdminTheme() { - return realm.getAdminTheme(); - } - - @Override - public void setAdminTheme(String name) { - realm.setAdminTheme(name); - updateRealm(); - } - - @Override - public String getEmailTheme() { - return realm.getEmailTheme(); - } - - @Override - public void setEmailTheme(String name) { - realm.setEmailTheme(name); - updateRealm(); - } - - @Override - public RoleModel getRole(String name) { - return session.realms().getRealmRole(this, name); - } - - @Override - public RoleModel addRole(String name) { - return session.realms().addRealmRole(this, name); - } - - @Override - public RoleModel addRole(String id, String name) { - return session.realms().addRealmRole(this, id, name); - } - - @Override - public boolean removeRole(RoleModel role) { - return session.realms().removeRole(this, role); - } - - @Override - public Set getRoles() { - DBObject query = new QueryBuilder() - .and("realmId").is(getId()) - .get(); - List roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext); - - - if (roles == null) return Collections.EMPTY_SET; - Set result = new HashSet(); - for (MongoRoleEntity role : roles) { - result.add(new RoleAdapter(session, this, role, this, invocationContext)); - } - - return Collections.unmodifiableSet(result); - } - - @Override - public RoleModel getRoleById(String id) { - return session.realms().getRoleById(id, this); - } - - @Override - public GroupModel createGroup(String name) { - return session.realms().createGroup(this, name); - } - - @Override - public GroupModel createGroup(String id, String name) { - return session.realms().createGroup(this, id, name); - } - - @Override - public void moveGroup(GroupModel group, GroupModel toParent) { - session.realms().moveGroup(this, group, toParent); - } - - @Override - public GroupModel getGroupById(String id) { - return model.getGroupById(id, this); - } - - @Override - public List getGroups() { - return session.realms().getGroups(this); - } - - @Override - public List getTopLevelGroups() { - return session.realms().getTopLevelGroups(this); - } - - @Override - public boolean removeGroup(GroupModel group) { - return session.realms().removeGroup(this, group); - } - - - - @Override - public List getDefaultRoles() { - return Collections.unmodifiableList(realm.getDefaultRoles()); - } - - @Override - public void addDefaultRole(String name) { - RoleModel role = getRole(name); - if (role == null) { - addRole(name); - } - - getMongoStore().pushItemToList(realm, "defaultRoles", name, true, invocationContext); - } - - @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); - updateRealm(); - } - - public static boolean contains(String str, String[] array) { - for (String s : array) { - if (str.equals(s)) return true; - } - return false; - } - - - @Override - public void removeDefaultRoles(String... defaultRoles) { - List roleNames = new ArrayList(); - for (String role : realm.getDefaultRoles()) { - if (!contains(role, defaultRoles)) roleNames.add(role); - } - realm.setDefaultRoles(roleNames); - updateRealm(); - } - - @Override - public List getDefaultGroups() { - List entities = realm.getDefaultGroups(); - if (entities == null || entities.isEmpty()) return Collections.EMPTY_LIST; - List defaultGroups = new LinkedList<>(); - for (String id : entities) { - defaultGroups.add(session.realms().getGroupById(id, this)); - } - return Collections.unmodifiableList(defaultGroups); - } - - @Override - public void addDefaultGroup(GroupModel group) { - getMongoStore().pushItemToList(realm, "defaultGroups", group.getId(), true, invocationContext); - - } - - @Override - public void removeDefaultGroup(GroupModel group) { - getMongoStore().pullItemFromList(realm, "defaultGroups", group.getId(), invocationContext); - - } - - @Override - public ClientModel getClientById(String id) { - return model.getClientById(id, this); - } - - @Override - public ClientModel getClientByClientId(String clientId) { - return session.realms().getClientByClientId(clientId, this); - } - - @Override - public List getClients() { - return session.realms().getClients(this); - } - - @Override - public ClientModel addClient(String name) { - return session.realms().addClient(this, name); - } - - @Override - public ClientModel addClient(String id, String clientId) { - return session.realms().addClient(this, id, clientId); - - } - - @Override - public boolean removeClient(String id) { - if (id == null) return false; - ClientModel client = getClientById(id); - if (client == null) return false; - return session.realms().removeClient(id, this); - } - - @Override - public void addRequiredCredential(String type) { - RequiredCredentialModel credentialModel = initRequiredCredentialModel(type); - addRequiredCredential(credentialModel, realm.getRequiredCredentials()); - } - - 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); - - updateRealm(); - } - - @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); - } - } - updateRealm(); - } - - @Override - public List getRequiredCredentials() { - return convertRequiredCredentialEntities(realm.getRequiredCredentials()); - } - - protected List convertRequiredCredentialEntities(Collection credEntities) { - if (credEntities == null || credEntities.isEmpty()) return Collections.EMPTY_LIST; - List result = new LinkedList<>(); - for (RequiredCredentialEntity entity : credEntities) { - RequiredCredentialModel model = new RequiredCredentialModel(); - model.setFormLabel(entity.getFormLabel()); - model.setInput(entity.isInput()); - model.setSecret(entity.isSecret()); - model.setType(entity.getType()); - - result.add(model); - } - return Collections.unmodifiableList(result); - } - - protected void updateRealm() { - super.updateMongoEntity(); - } - - protected RequiredCredentialModel initRequiredCredentialModel(String type) { - RequiredCredentialModel model = RequiredCredentialModel.BUILT_IN.get(type); - if (model == null) { - throw new RuntimeException("Unknown credential type " + type); - } - return model; - } - - @Override - public Map getBrowserSecurityHeaders() { - return Collections.unmodifiableMap(realm.getBrowserSecurityHeaders()); - } - - @Override - public void setBrowserSecurityHeaders(Map headers) { - realm.setBrowserSecurityHeaders(headers); - updateRealm(); - } - - @Override - public Map getSmtpConfig() { - return Collections.unmodifiableMap(realm.getSmtpConfig()); - } - - @Override - public void setSmtpConfig(Map smtpConfig) { - realm.setSmtpConfig(smtpConfig); - updateRealm(); - } - - - @Override - public List getIdentityProviders() { - List entities = realm.getIdentityProviders(); - if (entities.isEmpty()) return Collections.EMPTY_LIST; - List identityProviders = new ArrayList(); - - for (IdentityProviderEntity entity: entities) { - IdentityProviderModel identityProviderModel = entityToModel(entity); - - identityProviders.add(identityProviderModel); - } - - return Collections.unmodifiableList(identityProviders); - } - - private IdentityProviderModel entityToModel(IdentityProviderEntity entity) { - IdentityProviderModel identityProviderModel = new IdentityProviderModel(); - - identityProviderModel.setProviderId(entity.getProviderId()); - identityProviderModel.setAlias(entity.getAlias()); - identityProviderModel.setDisplayName(entity.getDisplayName()); - identityProviderModel.setInternalId(entity.getInternalId()); - Map config = entity.getConfig(); - Map copy = new HashMap<>(); - copy.putAll(config); - identityProviderModel.setConfig(copy); - identityProviderModel.setEnabled(entity.isEnabled()); - identityProviderModel.setTrustEmail(entity.isTrustEmail()); - identityProviderModel.setAuthenticateByDefault(entity.isAuthenticateByDefault()); - identityProviderModel.setFirstBrokerLoginFlowId(entity.getFirstBrokerLoginFlowId()); - identityProviderModel.setPostBrokerLoginFlowId(entity.getPostBrokerLoginFlowId()); - identityProviderModel.setStoreToken(entity.isStoreToken()); - identityProviderModel.setAddReadTokenRoleOnCreate(entity.isAddReadTokenRoleOnCreate()); - return identityProviderModel; - } - - @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) { - IdentityProviderEntity entity = new IdentityProviderEntity(); - - entity.setInternalId(KeycloakModelUtils.generateId()); - entity.setAlias(identityProvider.getAlias()); - entity.setDisplayName(identityProvider.getDisplayName()); - entity.setProviderId(identityProvider.getProviderId()); - entity.setEnabled(identityProvider.isEnabled()); - entity.setTrustEmail(identityProvider.isTrustEmail()); - entity.setAddReadTokenRoleOnCreate(identityProvider.isAddReadTokenRoleOnCreate()); - entity.setStoreToken(identityProvider.isStoreToken()); - entity.setAuthenticateByDefault(identityProvider.isAuthenticateByDefault()); - entity.setFirstBrokerLoginFlowId(identityProvider.getFirstBrokerLoginFlowId()); - entity.setPostBrokerLoginFlowId(identityProvider.getPostBrokerLoginFlowId()); - entity.setConfig(identityProvider.getConfig()); - - realm.getIdentityProviders().add(entity); - updateRealm(); - } - - @Override - public void removeIdentityProviderByAlias(String alias) { - for (IdentityProviderEntity entity : realm.getIdentityProviders()) { - if (entity.getAlias().equals(alias)) { - IdentityProviderModel model = entityToModel(entity); - realm.getIdentityProviders().remove(entity); - updateRealm(); - - session.getKeycloakSessionFactory().publish(new RealmModel.IdentityProviderRemovedEvent() { - - @Override - public RealmModel getRealm() { - return RealmAdapter.this; - } - - @Override - public IdentityProviderModel getRemovedIdentityProvider() { - return model; - } - - @Override - public KeycloakSession getKeycloakSession() { - return session; - } - }); - - break; - } - } - } - - @Override - public void updateIdentityProvider(IdentityProviderModel identityProvider) { - for (IdentityProviderEntity entity : this.realm.getIdentityProviders()) { - if (entity.getInternalId().equals(identityProvider.getInternalId())) { - entity.setAlias(identityProvider.getAlias()); - entity.setDisplayName(identityProvider.getDisplayName()); - entity.setEnabled(identityProvider.isEnabled()); - entity.setTrustEmail(identityProvider.isTrustEmail()); - entity.setAuthenticateByDefault(identityProvider.isAuthenticateByDefault()); - entity.setFirstBrokerLoginFlowId(identityProvider.getFirstBrokerLoginFlowId()); - entity.setPostBrokerLoginFlowId(identityProvider.getPostBrokerLoginFlowId()); - entity.setAddReadTokenRoleOnCreate(identityProvider.isAddReadTokenRoleOnCreate()); - entity.setStoreToken(identityProvider.isStoreToken()); - entity.setConfig(identityProvider.getConfig()); - } - } - - updateRealm(); - - session.getKeycloakSessionFactory().publish(new RealmModel.IdentityProviderUpdatedEvent() { - - @Override - public RealmModel getRealm() { - return RealmAdapter.this; - } - - @Override - public IdentityProviderModel getUpdatedIdentityProvider() { - return identityProvider; - } - - @Override - public KeycloakSession getKeycloakSession() { - return session; - } - }); - } - - @Override - public boolean isEventsEnabled() { - return realm.isEventsEnabled(); - } - - @Override - public void setEventsEnabled(boolean enabled) { - realm.setEventsEnabled(enabled); - updateRealm(); - } - - @Override - public long getEventsExpiration() { - return realm.getEventsExpiration(); - } - - @Override - public void setEventsExpiration(long expiration) { - realm.setEventsExpiration(expiration); - updateRealm(); - } - - @Override - public Set getEventsListeners() { - List eventsListeners = realm.getEventsListeners(); - if (eventsListeners.isEmpty()) return Collections.EMPTY_SET; - Set copy = new HashSet<>(); - copy.addAll(eventsListeners); - return Collections.unmodifiableSet(copy); - } - - @Override - public void setEventsListeners(Set listeners) { - if (listeners != null) { - realm.setEventsListeners(new ArrayList(listeners)); - } else { - realm.setEventsListeners(Collections.EMPTY_LIST); - } - updateRealm(); - } - - @Override - public Set getEnabledEventTypes() { - List enabledEventTypes = realm.getEnabledEventTypes(); - if (enabledEventTypes.isEmpty()) return Collections.EMPTY_SET; - Set copy = new HashSet<>(); - copy.addAll(enabledEventTypes); - return Collections.unmodifiableSet(copy); - } - - @Override - public void setEnabledEventTypes(Set enabledEventTypes) { - if (enabledEventTypes != null) { - realm.setEnabledEventTypes(new ArrayList(enabledEventTypes)); - } else { - realm.setEnabledEventTypes(Collections.EMPTY_LIST); - } - updateRealm(); - } - - @Override - public boolean isAdminEventsEnabled() { - return realm.isAdminEventsEnabled(); - } - - @Override - public void setAdminEventsEnabled(boolean enabled) { - realm.setAdminEventsEnabled(enabled); - updateRealm(); - - } - - @Override - public boolean isAdminEventsDetailsEnabled() { - return realm.isAdminEventsDetailsEnabled(); - } - - @Override - public void setAdminEventsDetailsEnabled(boolean enabled) { - realm.setAdminEventsDetailsEnabled(enabled); - updateRealm(); - } - - @Override - public ClientModel getMasterAdminClient() { - MongoClientEntity appData = getMongoStore().loadEntity(MongoClientEntity.class, realm.getMasterAdminClient(), invocationContext); - if (appData == null) { - return null; - } - - MongoRealmEntity masterRealm = getMongoStore().loadEntity(MongoRealmEntity.class, appData.getRealmId(), invocationContext); - RealmModel masterRealmModel = new RealmAdapter(session, masterRealm, invocationContext); - return new ClientAdapter(session, masterRealmModel, appData, invocationContext); - } - - @Override - public void setMasterAdminClient(ClientModel client) { - String adminAppId = client != null ? client.getId() : null; - realm.setMasterAdminClient(adminAppId); - updateRealm(); - } - - @Override - public MongoRealmEntity getMongoEntity() { - return realm; - } - - @Override - public boolean isIdentityFederationEnabled() { - return this.realm.getIdentityProviders() != null && !this.realm.getIdentityProviders().isEmpty(); - } - - @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 boolean isInternationalizationEnabled() { - return realm.isInternationalizationEnabled(); - } - - @Override - public void setInternationalizationEnabled(boolean enabled) { - realm.setInternationalizationEnabled(enabled); - updateRealm(); - } - - @Override - public Set getSupportedLocales() { - List supportedLocales = realm.getSupportedLocales(); - if (supportedLocales == null || supportedLocales.isEmpty()) return Collections.EMPTY_SET; - Set copy = new HashSet<>(); - copy.addAll(supportedLocales); - return Collections.unmodifiableSet(copy); - } - - @Override - public void setSupportedLocales(Set locales) { - if (locales != null) { - realm.setSupportedLocales(new ArrayList(locales)); - } else { - realm.setSupportedLocales(Collections.EMPTY_LIST); - } - updateRealm(); - } - - @Override - public String getDefaultLocale() { - return realm.getDefaultLocale(); - } - - @Override - public void setDefaultLocale(String locale) { - realm.setDefaultLocale(locale); - updateRealm(); - } - - @Override - public Set getIdentityProviderMappers() { - List entities = getMongoEntity().getIdentityProviderMappers(); - if (entities.isEmpty()) return Collections.EMPTY_SET; - Set mappings = new HashSet(); - for (IdentityProviderMapperEntity entity : entities) { - IdentityProviderMapperModel mapping = entityToModel(entity); - mappings.add(mapping); - } - return Collections.unmodifiableSet(mappings); - } - - @Override - public Set getIdentityProviderMappersByAlias(String brokerAlias) { - Set mappings = new HashSet(); - for (IdentityProviderMapperEntity entity : getMongoEntity().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()); - - getMongoEntity().getIdentityProviderMappers().add(entity); - updateMongoEntity(); - return entityToModel(entity); - } - - protected IdentityProviderMapperEntity getIdentityProviderMapperEntity(String id) { - for (IdentityProviderMapperEntity entity : getMongoEntity().getIdentityProviderMappers()) { - if (entity.getId().equals(id)) { - return entity; - } - } - return null; - - } - - protected IdentityProviderMapperEntity getIdentityProviderMapperEntityByName(String alias, String name) { - for (IdentityProviderMapperEntity entity : getMongoEntity().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); - updateMongoEntity(); - } - } - - @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()); - } - updateMongoEntity(); - - } - - @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()); - updateRealm(); - - } - - @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()); - updateRealm(); - - } - - @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()); - updateRealm(); - - } - - @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()); - updateRealm(); - } - - public AuthenticationFlowModel getClientAuthenticationFlow() { - String flowId = realm.getClientAuthenticationFlow(); - if (flowId == null) return null; - return getAuthenticationFlowById(flowId); - } - - public void setClientAuthenticationFlow(AuthenticationFlowModel flow) { - realm.setClientAuthenticationFlow(flow.getId()); - updateRealm(); - } - - @Override - public List getAuthenticationFlows() { - List flows = getMongoEntity().getAuthenticationFlows(); - if (flows.isEmpty()) return Collections.EMPTY_LIST; - List models = new LinkedList<>(); - for (AuthenticationFlowEntity entity : flows) { - AuthenticationFlowModel model = entityToModel(entity); - models.add(model); - } - return Collections.unmodifiableList(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.setBuiltIn(entity.isBuiltIn()); - model.setTopLevel(entity.isTopLevel()); - model.setProviderId(entity.getProviderId()); - return model; - } - - @Override - public AuthenticationFlowModel getAuthenticationFlowById(String id) { - AuthenticationFlowEntity entity = getFlowEntity(id); - if (entity == null) return null; - return entityToModel(entity); - } - - protected AuthenticationFlowEntity getFlowEntity(String id) { - List flows = getMongoEntity().getAuthenticationFlows(); - for (AuthenticationFlowEntity entity : flows) { - if (id.equals(entity.getId())) return entity; - } - return null; - - } - - @Override - public void removeAuthenticationFlow(AuthenticationFlowModel model) { - if (KeycloakModelUtils.isFlowUsed(this, model)) { - throw new ModelException("Cannot remove authentication flow, it is currently in use"); - } - AuthenticationFlowEntity toDelete = getFlowEntity(model.getId()); - if (toDelete == null) return; - getMongoEntity().getAuthenticationFlows().remove(toDelete); - updateMongoEntity(); - } - - @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()); - updateMongoEntity(); - } - - @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()); - getMongoEntity().getAuthenticationFlows().add(entity); - model.setId(entity.getId()); - updateMongoEntity(); - 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 Collections.unmodifiableList(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.setFlowId(entity.getFlowId()); - model.setParentFlow(entity.getParentFlow()); - 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 = getMongoEntity().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.setParentFlow(model.getParentFlow()); - entity.setAuthenticatorConfig(model.getAuthenticatorConfig()); - AuthenticationFlowEntity flow = getFlowEntity(model.getParentFlow()); - flow.getExecutions().add(entity); - updateMongoEntity(); - 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()); - updateMongoEntity(); - } - - @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); - updateMongoEntity(); - - } - - @Override - public List getAuthenticatorConfigs() { - List entities = getMongoEntity().getAuthenticatorConfigs(); - if (entities.isEmpty()) return Collections.EMPTY_LIST; - List authenticators = new LinkedList<>(); - for (AuthenticatorConfigEntity entity : entities) { - authenticators.add(entityToModel(entity)); - } - return Collections.unmodifiableList(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()); - updateMongoEntity(); - return model; - } - - @Override - public void removeAuthenticatorConfig(AuthenticatorConfigModel model) { - AuthenticatorConfigEntity entity = getAuthenticatorConfigEntity(model.getId()); - if (entity == null) return; - getMongoEntity().getAuthenticatorConfigs().remove(entity); - updateMongoEntity(); - - } - - @Override - public AuthenticatorConfigModel getAuthenticatorConfigById(String id) { - AuthenticatorConfigEntity entity = getAuthenticatorConfigEntity(id); - if (entity == null) return null; - return entityToModel(entity); - } - - public AuthenticatorConfigEntity getAuthenticatorConfigEntity(String id) { - AuthenticatorConfigEntity entity = null; - for (AuthenticatorConfigEntity auth : getMongoEntity().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 = getAuthenticatorConfigEntity(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()); - } - updateMongoEntity(); - } - - @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()); - updateMongoEntity(); - return model; - } - - @Override - public void removeRequiredActionProvider(RequiredActionProviderModel model) { - RequiredActionProviderEntity entity = getRequiredActionProviderEntity(model.getId()); - if (entity == null) return; - getMongoEntity().getRequiredActionProviders().remove(entity); - updateMongoEntity(); - } - - @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.setName(model.getName()); - entity.setProviderId(model.getProviderId()); - entity.setEnabled(model.isEnabled()); - entity.setDefaultAction(model.isDefaultAction()); - if (entity.getConfig() == null) { - entity.setConfig(model.getConfig()); - } else { - entity.getConfig().clear(); - entity.getConfig().putAll(model.getConfig()); - } - updateMongoEntity(); - } - - @Override - public List getRequiredActionProviders() { - List entities = realm.getRequiredActionProviders(); - if (entities.isEmpty()) return Collections.EMPTY_LIST; - List actions = new LinkedList<>(); - for (RequiredActionProviderEntity entity : entities) { - actions.add(entityToModel(entity)); - } - return Collections.unmodifiableList(actions); - } - - public RequiredActionProviderEntity getRequiredActionProviderEntity(String id) { - RequiredActionProviderEntity entity = null; - for (RequiredActionProviderEntity auth : getMongoEntity().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 List getClientTemplates() { - DBObject query = new QueryBuilder() - .and("realmId").is(getId()) - .get(); - List clientEntities = getMongoStore().loadEntities(MongoClientTemplateEntity.class, query, invocationContext); - if (clientEntities.isEmpty()) return Collections.EMPTY_LIST; - List result = new LinkedList<>(); - for (MongoClientTemplateEntity clientEntity : clientEntities) { - result.add(new ClientTemplateAdapter(session, this, clientEntity, invocationContext)); - } - return Collections.unmodifiableList(result); - } - - @Override - public ClientTemplateModel addClientTemplate(String name) { - return this.addClientTemplate(null, name); - } - - @Override - public ClientTemplateModel addClientTemplate(String id, String name) { - MongoClientTemplateEntity clientEntity = new MongoClientTemplateEntity(); - clientEntity.setId(id); - clientEntity.setName(name); - clientEntity.setRealmId(getId()); - getMongoStore().insertEntity(clientEntity, invocationContext); - - final ClientTemplateModel model = new ClientTemplateAdapter(session, this, clientEntity, invocationContext); - return model; - } - - @Override - public boolean removeClientTemplate(String id) { - if (id == null) return false; - ClientTemplateModel client = getClientTemplateById(id); - if (client == null) return false; - - if (KeycloakModelUtils.isClientTemplateUsed(this, client)) { - throw new ModelException("Cannot remove client template, it is currently in use"); - } - - return getMongoStore().removeEntity(MongoClientTemplateEntity.class, id, invocationContext); - } - - @Override - public ClientTemplateModel getClientTemplateById(String id) { - return model.getClientTemplateById(id, this); - } - - @Override - public ComponentModel addComponentModel(ComponentModel model) { - model = importComponentModel(model); - ComponentUtil.notifyCreated(session, this, model); - return model; - } - - /** - * This just exists for testing purposes - * - */ - public static final String COMPONENT_PROVIDER_EXISTS_DISABLED = "component.provider.exists.disabled"; - - @Override - public ComponentModel importComponentModel(ComponentModel model) { - ComponentFactory componentFactory = null; - try { - componentFactory = ComponentUtil.getComponentFactory(session, model); - if (componentFactory == null && System.getProperty(COMPONENT_PROVIDER_EXISTS_DISABLED) == null) { - throw new IllegalArgumentException("Invalid component type"); - } - componentFactory.validateConfiguration(session, this, model); - } catch (Exception e) { - if (System.getProperty(COMPONENT_PROVIDER_EXISTS_DISABLED) == null) { - throw e; - } - - } - ComponentEntity entity = new ComponentEntity(); - if (model.getId() == null) { - entity.setId(KeycloakModelUtils.generateId()); - } else { - entity.setId(model.getId()); - } - updateComponentEntity(entity, model); - model.setId(entity.getId()); - if (model.getParentId() == null) { - entity.setParentId(this.getId()); - model.setParentId(this.getId()); - } - realm.getComponentEntities().add(entity); - updateRealm(); - return model; - } - - @Override - public void updateComponent(ComponentModel model) { - ComponentUtil.getComponentFactory(session, model).validateConfiguration(session, this, model); - - ComponentModel old = null; - for (ComponentEntity entity : realm.getComponentEntities()) { - if (entity.getId().equals(model.getId())) { - old = entityToModel(entity); - updateComponentEntity(entity, model); - break; - } - } - if (old == null) return; // wasn't updated - updateRealm(); - ComponentUtil.notifyUpdated(session, this, old, model); - - } - - private void updateComponentEntity(ComponentEntity entity, ComponentModel model) { - entity.setConfig(model.getConfig()); - entity.setParentId(model.getParentId()); - entity.setProviderType(model.getProviderType()); - entity.setSubType(model.getSubType()); - entity.setProviderId(model.getProviderId()); - entity.setName(model.getName()); - } - - @Override - public void removeComponent(ComponentModel component) { - Iterator it = realm.getComponentEntities().iterator(); - ComponentEntity found = null; - while(it.hasNext()) { - ComponentEntity next = it.next(); - if (next.getId().equals(component.getId())) { - found = next; - break; - } - } - - if (found != null) { - session.users().preRemove(this, component); - removeComponents(component.getId()); - realm.getComponentEntities().remove(found); - updateRealm(); - } - } - - @Override - public void removeComponents(String parentId) { - Iterator it = realm.getComponentEntities().iterator(); - Set toRemove = new HashSet<>(); - while(it.hasNext()) { - ComponentEntity next = it.next(); - if (next.getParentId().equals(parentId)) { - toRemove.add(next); - } - } - - for (ComponentEntity toRem : toRemove) { - session.users().preRemove(this, entityToModel(toRem)); - realm.getComponentEntities().remove(toRem); - } - - updateRealm(); - - } - - @Override - public List getComponents(String parentId, String providerType) { - List results = new LinkedList<>(); - for (ComponentEntity entity : realm.getComponentEntities()) { - if (entity.getParentId().equals(parentId) && entity.getProviderType().equals(providerType)) { - ComponentModel model = entityToModel(entity); - results.add(model); - } - - } - return results; - } - - @Override - public List getComponents(String parentId) { - List results = new LinkedList<>(); - for (ComponentEntity entity : realm.getComponentEntities()) { - if (entity.getParentId().equals(parentId)) { - ComponentModel model = entityToModel(entity); - results.add(model); - } - - } - return results; - } - - protected ComponentModel entityToModel(ComponentEntity entity) { - ComponentModel model = new ComponentModel(); - model.setId(entity.getId()); - model.setName(entity.getName()); - model.setParentId(entity.getParentId()); - model.setProviderId(entity.getProviderId()); - model.setProviderType(entity.getProviderType()); - model.setSubType(entity.getSubType()); - MultivaluedHashMap map = new MultivaluedHashMap<>(); - map.putAll(entity.getConfig()); - model.setConfig(map); - return model; - } - - @Override - public List getComponents() { - List results = new LinkedList<>(); - for (ComponentEntity entity : realm.getComponentEntities()) { - ComponentModel model = entityToModel(entity); - results.add(model); - } - return results; - } - - @Override - public ComponentModel getComponent(String id) { - for (ComponentEntity entity : realm.getComponentEntities()) { - if (id.equals(entity.getId())) { - return entityToModel(entity); - } - } - return null; - } - - @Override - public void setAttribute(String name, String value) { - realm.getAttributes().put(name, value); - updateRealm(); - } - - @Override - public void setAttribute(String name, Boolean value) { - setAttribute(name, value.toString()); - } - - @Override - public void setAttribute(String name, Integer value) { - setAttribute(name, value.toString()); - } - - @Override - public void setAttribute(String name, Long value) { - setAttribute(name, value.toString()); - } - - @Override - public void removeAttribute(String name) { - realm.getAttributes().remove(name); - updateRealm(); - } - - @Override - public String getAttribute(String name) { - return realm.getAttributes().get(name); - } - - @Override - public Integer getAttribute(String name, Integer defaultValue) { - String v = getAttribute(name); - return v != null ? Integer.parseInt(v) : defaultValue; - } - - @Override - public Long getAttribute(String name, Long defaultValue) { - String v = getAttribute(name); - return v != null ? Long.parseLong(v) : defaultValue; - } - - @Override - public Boolean getAttribute(String name, Boolean defaultValue) { - String v = getAttribute(name); - return v != null ? Boolean.parseBoolean(v) : defaultValue; - } - - @Override - public Map getAttributes() { - Map attributes = new HashMap<>(); - attributes.putAll(realm.getAttributes()); - return attributes; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RoleAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RoleAdapter.java deleted file mode 100755 index cf3c78fd005..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RoleAdapter.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleContainerModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; -import org.keycloak.models.utils.KeycloakModelUtils; - -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Wrapper around RoleData object, which will persist wrapped object after each set operation (compatibility with picketlink based idm) - * - * @author Marek Posolda - */ -public class RoleAdapter extends AbstractMongoAdapter implements RoleModel { - - private final MongoRoleEntity role; - private RoleContainerModel roleContainer; - private RealmModel realm; - private KeycloakSession session; - - public RoleAdapter(KeycloakSession session, RealmModel realm, MongoRoleEntity roleEntity, MongoStoreInvocationContext invContext) { - this(session, realm, roleEntity, null, invContext); - } - - public RoleAdapter(KeycloakSession session, RealmModel realm, MongoRoleEntity roleEntity, RoleContainerModel roleContainer, MongoStoreInvocationContext invContext) { - super(invContext); - this.role = roleEntity; - this.roleContainer = roleContainer; - this.realm = realm; - this.session = session; - } - - @Override - public String getId() { - return role.getId(); - } - - @Override - public String getName() { - return role.getName(); - } - - @Override - public void setName(String name) { - role.setName(name); - updateRole(); - } - - @Override - public String getDescription() { - return role.getDescription(); - } - - @Override - public void setDescription(String description) { - role.setDescription(description); - updateRole(); - } - - @Override - public boolean isScopeParamRequired() { - return role.isScopeParamRequired(); - } - - @Override - public void setScopeParamRequired(boolean scopeParamRequired) { - role.setScopeParamRequired(scopeParamRequired); - updateRole(); - } - - @Override - public boolean isComposite() { - return role.getCompositeRoleIds() != null && role.getCompositeRoleIds().size() > 0; - } - - protected void updateRole() { - super.updateMongoEntity(); - } - - @Override - public void addCompositeRole(RoleModel childRole) { - getMongoStore().pushItemToList(role, "compositeRoleIds", childRole.getId(), true, invocationContext); - } - - @Override - public void removeCompositeRole(RoleModel childRole) { - getMongoStore().pullItemFromList(role, "compositeRoleIds", childRole.getId(), invocationContext); - } - - @Override - public Set getComposites() { - if (role.getCompositeRoleIds() == null || role.getCompositeRoleIds().isEmpty()) { - return Collections.EMPTY_SET; - } - - DBObject query = new QueryBuilder() - .and("_id").in(role.getCompositeRoleIds()) - .get(); - List childRoles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext); - - Set set = new HashSet(); - for (MongoRoleEntity childRole : childRoles) { - set.add(new RoleAdapter(session, realm, childRole, invocationContext)); - } - return set; - } - - @Override - public boolean isClientRole() { - return role.getClientId() != null; - } - - - - @Override - public String getContainerId() { - if (isClientRole()) return role.getClientId(); - else return role.getRealmId(); - } - - - @Override - public RoleContainerModel getContainer() { - if (roleContainer == null) { - // Compute it - if (role.getRealmId() != null) { - MongoRealmEntity realm = getMongoStore().loadEntity(MongoRealmEntity.class, role.getRealmId(), invocationContext); - if (realm == null) { - throw new IllegalStateException("Realm with id: " + role.getRealmId() + " doesn't exists"); - } - roleContainer = new RealmAdapter(session, realm, invocationContext); - } else if (role.getClientId() != null) { - MongoClientEntity appEntity = getMongoStore().loadEntity(MongoClientEntity.class, role.getClientId(), invocationContext); - if (appEntity == null) { - throw new IllegalStateException("Application with id: " + role.getClientId() + " doesn't exists"); - } - roleContainer = new ClientAdapter(session, realm, appEntity, invocationContext); - } else { - throw new IllegalStateException("Both realmId and clientId are null for role: " + this); - } - } - return roleContainer; - } - - @Override - public boolean hasRole(RoleModel role) { - return this.equals(role) || KeycloakModelUtils.searchFor(role, this, new HashSet<>()); - } - - public MongoRoleEntity getRole() { - return role; - } - - @Override - public MongoRoleEntity getMongoEntity() { - return role; - } - - @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/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java deleted file mode 100755 index 9282df017bf..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.adapters; - -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -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.UserModel; -import org.keycloak.models.mongo.keycloak.entities.MongoUserEntity; -import org.keycloak.models.mongo.utils.MongoModelUtils; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.models.utils.RoleUtils; - -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; - -/** - * Wrapper around UserData object, which will persist wrapped object after each set operation (compatibility with picketlink based idm) - * - * @author Marek Posolda - */ -public class UserAdapter extends AbstractMongoAdapter implements UserModel { - - private final MongoUserEntity user; - private final RealmModel realm; - private final KeycloakSession session; - - public UserAdapter(KeycloakSession session, RealmModel realm, MongoUserEntity userEntity, MongoStoreInvocationContext invContext) { - super(invContext); - this.user = userEntity; - this.realm = realm; - this.session = session; - } - - @Override - public String getId() { - return user.getId(); - } - - @Override - public String getUsername() { - return user.getUsername(); - } - - @Override - public void setUsername(String username) { - username = KeycloakModelUtils.toLowerCaseSafe(username); - - user.setUsername(username); - updateUser(); - } - - @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); - updateUser(); - } - - @Override - public String getFirstName() { - return user.getFirstName(); - } - - @Override - public void setFirstName(String firstName) { - user.setFirstName(firstName); - updateUser(); - } - - @Override - public String getLastName() { - return user.getLastName(); - } - - @Override - public void setLastName(String lastName) { - user.setLastName(lastName); - updateUser(); - } - - @Override - public String getEmail() { - return user.getEmail(); - } - - @Override - public void setEmail(String email) { - email = KeycloakModelUtils.toLowerCaseSafe(email); - user.setEmail(email, realm.isDuplicateEmailsAllowed()); - updateUser(); - } - - @Override - public boolean isEmailVerified() { - return user.isEmailVerified(); - } - - @Override - public void setEmailVerified(boolean verified) { - user.setEmailVerified(verified); - updateUser(); - } - - @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); - updateUser(); - } - - @Override - public void setAttribute(String name, List values) { - if (user.getAttributes() == null) { - user.setAttributes(new HashMap>()); - } - - user.getAttributes().put(name, values); - updateUser(); - } - - @Override - public void removeAttribute(String name) { - if (user.getAttributes() == null) return; - - user.getAttributes().remove(name); - updateUser(); - } - - @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()); - } - - public MongoUserEntity getUser() { - return user; - } - - - @Override - public Set getRequiredActions() { - Set result = new HashSet(); - if (user.getRequiredActions() != null) { - result.addAll(user.getRequiredActions()); - } - return result; - } - - @Override - public void addRequiredAction(RequiredAction action) { - String actionName = action.name(); - addRequiredAction(actionName); - } - - @Override - public void addRequiredAction(String actionName) { - getMongoStore().pushItemToList(user, "requiredActions", actionName, true, invocationContext); - } - - @Override - public void removeRequiredAction(RequiredAction action) { - String actionName = action.name(); - removeRequiredAction(actionName); - } - - @Override - public void removeRequiredAction(String actionName) { - getMongoStore().pullItemFromList(user, "requiredActions", actionName, invocationContext); - } - - protected void updateUser() { - super.updateMongoEntity(); - } - - @Override - public MongoUserEntity getMongoEntity() { - return user; - } - - @Override - public Set getGroups() { - if (user.getGroupIds() == null || user.getGroupIds().size() == 0) return Collections.EMPTY_SET; - Set groups = new HashSet<>(); - for (String id : user.getGroupIds()) { - groups.add(realm.getGroupById(id)); - } - return groups; - } - - @Override - public void joinGroup(GroupModel group) { - getMongoStore().pushItemToList(getUser(), "groupIds", group.getId(), true, invocationContext); - - } - - @Override - public void leaveGroup(GroupModel group) { - if (user == null || group == null) return; - - getMongoStore().pullItemFromList(getUser(), "groupIds", group.getId(), invocationContext); - - } - - @Override - public boolean isMemberOf(GroupModel group) { - if (user.getGroupIds() == null) return false; - if (user.getGroupIds().contains(group.getId())) return true; - Set groups = getGroups(); - return RoleUtils.isMember(groups, group); - } - - @Override - public boolean hasRole(RoleModel role) { - Set roles = getRoleMappings(); - return RoleUtils.hasRole(roles, role) - || RoleUtils.hasRoleFromGroup(getGroups(), role, true); - } - - @Override - public void grantRole(RoleModel role) { - getMongoStore().pushItemToList(getUser(), "roleIds", role.getId(), true, invocationContext); - } - - @Override - public Set getRoleMappings() { - List roles = MongoModelUtils.getAllRolesOfUser(realm, this); - return new HashSet(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 (user == null || role == null) return; - - getMongoStore().pullItemFromList(getUser(), "roleIds", role.getId(), invocationContext); - } - - @Override - public Set getClientRoleMappings(ClientModel app) { - Set result = new HashSet(); - List roles = MongoModelUtils.getAllRolesOfUser(realm, this); - - for (RoleModel role : roles) { - if (app.equals(role.getContainer())) { - result.add(role); - } - } - return result; - } - - @Override - public String getFederationLink() { - return user.getFederationLink(); - } - - @Override - public void setFederationLink(String link) { - user.setFederationLink(link); - updateUser(); - } - - @Override - public String getServiceAccountClientLink() { - return user.getServiceAccountClientLink(); - } - - @Override - public void setServiceAccountClientLink(String clientInternalId) { - user.setServiceAccountClientLink(clientInternalId); - updateUser(); - } - - - @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(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AbstractIdentifiableEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AbstractIdentifiableEntity.java deleted file mode 100755 index a79dd753ccd..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AbstractIdentifiableEntity.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -/** - * Base for the identifiable entity - * - * @author Marek Posolda - */ -public class AbstractIdentifiableEntity { - - protected String id; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - - if (this.id == null) return false; - - if (o == null || getClass() != o.getClass()) return false; - - AbstractIdentifiableEntity that = (AbstractIdentifiableEntity) o; - - if (!getId().equals(that.getId())) return false; - - return true; - - } - - @Override - public int hashCode() { - return id!=null ? id.hashCode() : super.hashCode(); - } - - @Override - public String toString() { - return String.format("%s [ id=%s ]", getClass().getSimpleName(), getId()); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationExecutionEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationExecutionEntity.java deleted file mode 100755 index b8ed8d19f56..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationExecutionEntity.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.models.AuthenticationExecutionModel; - - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class AuthenticationExecutionEntity extends AbstractIdentifiableEntity { - protected String authenticator; - protected String authenticatorConfig; - protected String flowId; - protected AuthenticationExecutionModel.Requirement requirement; - protected int priority; - protected boolean userSetupAllowed; - protected boolean authenticatorFlow; - protected String parentFlow; - - public String getAuthenticator() { - return authenticator; - } - - public void setAuthenticator(String authenticator) { - this.authenticator = authenticator; - } - - public AuthenticationExecutionModel.Requirement getRequirement() { - return requirement; - } - - public void setRequirement(AuthenticationExecutionModel.Requirement requirement) { - this.requirement = requirement; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - public boolean isUserSetupAllowed() { - return userSetupAllowed; - } - - public void setUserSetupAllowed(boolean userSetupAllowed) { - this.userSetupAllowed = userSetupAllowed; - } - - public boolean isAuthenticatorFlow() { - return authenticatorFlow; - } - - public void setAuthenticatorFlow(boolean authenticatorFlow) { - this.authenticatorFlow = authenticatorFlow; - } - - public String getParentFlow() { - return parentFlow; - } - - public void setParentFlow(String parentFlow) { - this.parentFlow = parentFlow; - } - - public String getFlowId() { - return flowId; - } - - public void setFlowId(String flowId) { - this.flowId = flowId; - } - - public String getAuthenticatorConfig() { - return authenticatorConfig; - } - - public void setAuthenticatorConfig(String authenticatorConfig) { - this.authenticatorConfig = authenticatorConfig; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationFlowEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationFlowEntity.java deleted file mode 100755 index 440ba3a52f7..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticationFlowEntity.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class AuthenticationFlowEntity extends AbstractIdentifiableEntity { - protected String alias; - protected String description; - protected String providerId; - protected boolean topLevel; - protected boolean builtIn; - - List executions = new ArrayList(); - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public List getExecutions() { - return executions; - } - - public void setExecutions(List executions) { - this.executions = executions; - } - - public String getProviderId() { - return providerId; - } - - public void setProviderId(String providerId) { - this.providerId = providerId; - } - - public boolean isTopLevel() { - return topLevel; - } - - public void setTopLevel(boolean topLevel) { - this.topLevel = topLevel; - } - - public boolean isBuiltIn() { - return builtIn; - } - - public void setBuiltIn(boolean builtIn) { - this.builtIn = builtIn; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticatorConfigEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticatorConfigEntity.java deleted file mode 100755 index ba6359ab8d3..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/AuthenticatorConfigEntity.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class AuthenticatorConfigEntity extends AbstractIdentifiableEntity{ - protected String alias; - protected Map config; - - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public Map getConfig() { - return config; - } - - public void setConfig(Map config) { - this.config = config; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientEntity.java deleted file mode 100755 index dcefb7c6ddd..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientEntity.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class ClientEntity extends AbstractIdentifiableEntity { - - protected String clientId; - protected String name; - protected String description; - protected String realmId; - protected boolean enabled; - protected String clientAuthenticatorType; - protected String secret; - protected String registrationToken; - protected String protocol; - protected int notBefore; - protected boolean publicClient; - protected boolean fullScopeAllowed; - protected boolean frontchannelLogout; - - protected boolean surrogateAuthRequired; - protected String managementUrl; - protected String rootUrl; - protected String baseUrl; - protected boolean bearerOnly; - protected boolean consentRequired; - protected boolean standardFlowEnabled; - protected boolean implicitFlowEnabled; - protected boolean directAccessGrantsEnabled; - protected boolean serviceAccountsEnabled; - protected int nodeReRegistrationTimeout; - - // We are using names of defaultRoles (not ids) - protected List defaultRoles = new ArrayList(); - - protected Map registeredNodes; - - protected Map attributes = new HashMap(); - - protected List webOrigins = new ArrayList(); - protected List redirectUris = new ArrayList(); - protected List scopeIds = new ArrayList(); - protected List identityProviders = new ArrayList(); - protected List protocolMappers = new ArrayList(); - protected String clientTemplate; - protected boolean useTemplateConfig; - protected boolean useTemplateScope; - protected boolean useTemplateMappers; - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { return description; } - - public void setDescription(String description) { this.description = description; } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getClientAuthenticatorType() { - return clientAuthenticatorType; - } - - public void setClientAuthenticatorType(String clientAuthenticatorType) { - this.clientAuthenticatorType = clientAuthenticatorType; - } - - public String getSecret() { - return secret; - } - - public void setSecret(String secret) { - this.secret = secret; - } - - public String getRegistrationToken() { - return registrationToken; - } - - public void setRegistrationToken(String registrationToken) { - this.registrationToken = registrationToken; - } - - public int getNotBefore() { - return notBefore; - } - - public void setNotBefore(int notBefore) { - this.notBefore = notBefore; - } - - public boolean isPublicClient() { - return publicClient; - } - - public void setPublicClient(boolean publicClient) { - this.publicClient = publicClient; - } - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public List getWebOrigins() { - return webOrigins; - } - - public void setWebOrigins(List webOrigins) { - this.webOrigins = webOrigins; - } - - public List getRedirectUris() { - return redirectUris; - } - - public void setRedirectUris(List redirectUris) { - this.redirectUris = redirectUris; - } - - public List getScopeIds() { - return scopeIds; - } - - public void setScopeIds(List scopeIds) { - this.scopeIds = scopeIds; - } - - public boolean isFullScopeAllowed() { - return fullScopeAllowed; - } - - public void setFullScopeAllowed(boolean fullScopeAllowed) { - this.fullScopeAllowed = fullScopeAllowed; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - public boolean isFrontchannelLogout() { - return frontchannelLogout; - } - - public void setFrontchannelLogout(boolean frontchannelLogout) { - this.frontchannelLogout = frontchannelLogout; - } - - public List getIdentityProviders() { - return this.identityProviders; - } - - public void setIdentityProviders(List identityProviders) { - this.identityProviders = identityProviders; - } - - public List getProtocolMappers() { - return protocolMappers; - } - - public void setProtocolMappers(List protocolMappers) { - this.protocolMappers = protocolMappers; - } - - public boolean isSurrogateAuthRequired() { - return surrogateAuthRequired; - } - - public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { - this.surrogateAuthRequired = surrogateAuthRequired; - } - - public String getManagementUrl() { - return managementUrl; - } - - public void setManagementUrl(String managementUrl) { - this.managementUrl = managementUrl; - } - - public String getRootUrl() { - return rootUrl; - } - - public void setRootUrl(String rootUrl) { - this.rootUrl = rootUrl; - } - - public String getBaseUrl() { - return baseUrl; - } - - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - } - - public boolean isBearerOnly() { - return bearerOnly; - } - - public void setBearerOnly(boolean bearerOnly) { - this.bearerOnly = bearerOnly; - } - - public boolean isConsentRequired() { - return consentRequired; - } - - public void setConsentRequired(boolean consentRequired) { - this.consentRequired = consentRequired; - } - - public boolean isStandardFlowEnabled() { - return standardFlowEnabled; - } - - public void setStandardFlowEnabled(boolean standardFlowEnabled) { - this.standardFlowEnabled = standardFlowEnabled; - } - - public boolean isImplicitFlowEnabled() { - return implicitFlowEnabled; - } - - public void setImplicitFlowEnabled(boolean implicitFlowEnabled) { - this.implicitFlowEnabled = implicitFlowEnabled; - } - - public boolean isDirectAccessGrantsEnabled() { - return directAccessGrantsEnabled; - } - - public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) { - this.directAccessGrantsEnabled = directAccessGrantsEnabled; - } - - public boolean isServiceAccountsEnabled() { - return serviceAccountsEnabled; - } - - public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) { - this.serviceAccountsEnabled = serviceAccountsEnabled; - } - - public List getDefaultRoles() { - return defaultRoles; - } - - public void setDefaultRoles(List defaultRoles) { - this.defaultRoles = defaultRoles; - } - - public int getNodeReRegistrationTimeout() { - return nodeReRegistrationTimeout; - } - - public void setNodeReRegistrationTimeout(int nodeReRegistrationTimeout) { - this.nodeReRegistrationTimeout = nodeReRegistrationTimeout; - } - - public Map getRegisteredNodes() { - return registeredNodes; - } - - public void setRegisteredNodes(Map registeredNodes) { - this.registeredNodes = registeredNodes; - } - - public String getClientTemplate() { - return clientTemplate; - } - - public void setClientTemplate(String clientTemplate) { - this.clientTemplate = clientTemplate; - } - - public boolean isUseTemplateConfig() { - return useTemplateConfig; - } - - public void setUseTemplateConfig(boolean useTemplateConfig) { - this.useTemplateConfig = useTemplateConfig; - } - - public boolean isUseTemplateScope() { - return useTemplateScope; - } - - public void setUseTemplateScope(boolean useTemplateScope) { - this.useTemplateScope = useTemplateScope; - } - - public boolean isUseTemplateMappers() { - return useTemplateMappers; - } - - public void setUseTemplateMappers(boolean useTemplateMappers) { - this.useTemplateMappers = useTemplateMappers; - } -} - diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientIdentityProviderMappingEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientIdentityProviderMappingEntity.java deleted file mode 100755 index c064cb652e1..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientIdentityProviderMappingEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.models.mongo.keycloak.entities; - -/** - * @author pedroigor - */ -public class ClientIdentityProviderMappingEntity extends AbstractIdentifiableEntity { - - protected boolean retrieveToken; - - public boolean isRetrieveToken() { - return this.retrieveToken; - } - - public void setRetrieveToken(boolean retrieveToken) { - this.retrieveToken = retrieveToken; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientTemplateEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientTemplateEntity.java deleted file mode 100755 index 0f6336eb9b2..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ClientTemplateEntity.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class ClientTemplateEntity extends AbstractIdentifiableEntity { - - protected String name; - protected String description; - protected String realmId; - protected String protocol; - protected boolean fullScopeAllowed; - protected boolean bearerOnly; - protected boolean consentRequired; - protected boolean standardFlowEnabled; - protected boolean implicitFlowEnabled; - protected boolean directAccessGrantsEnabled; - protected boolean serviceAccountsEnabled; - protected boolean publicClient; - protected boolean frontchannelLogout; - protected List scopeIds = new ArrayList<>(); - protected List protocolMappers = new ArrayList<>(); - protected Map attributes = new HashMap<>(); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public List getProtocolMappers() { - return protocolMappers; - } - - public void setProtocolMappers(List protocolMappers) { - this.protocolMappers = protocolMappers; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public boolean isFullScopeAllowed() { - return fullScopeAllowed; - } - - public void setFullScopeAllowed(boolean fullScopeAllowed) { - this.fullScopeAllowed = fullScopeAllowed; - } - - public List getScopeIds() { - return scopeIds; - } - - public void setScopeIds(List scopeIds) { - this.scopeIds = scopeIds; - } - - public boolean isBearerOnly() { - return bearerOnly; - } - - public void setBearerOnly(boolean bearerOnly) { - this.bearerOnly = bearerOnly; - } - - public boolean isConsentRequired() { - return consentRequired; - } - - public void setConsentRequired(boolean consentRequired) { - this.consentRequired = consentRequired; - } - - public boolean isStandardFlowEnabled() { - return standardFlowEnabled; - } - - public void setStandardFlowEnabled(boolean standardFlowEnabled) { - this.standardFlowEnabled = standardFlowEnabled; - } - - public boolean isImplicitFlowEnabled() { - return implicitFlowEnabled; - } - - public void setImplicitFlowEnabled(boolean implicitFlowEnabled) { - this.implicitFlowEnabled = implicitFlowEnabled; - } - - public boolean isDirectAccessGrantsEnabled() { - return directAccessGrantsEnabled; - } - - public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) { - this.directAccessGrantsEnabled = directAccessGrantsEnabled; - } - - public boolean isServiceAccountsEnabled() { - return serviceAccountsEnabled; - } - - public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) { - this.serviceAccountsEnabled = serviceAccountsEnabled; - } - - public boolean isPublicClient() { - return publicClient; - } - - public void setPublicClient(boolean publicClient) { - this.publicClient = publicClient; - } - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - public boolean isFrontchannelLogout() { - return frontchannelLogout; - } - - public void setFrontchannelLogout(boolean frontchannelLogout) { - this.frontchannelLogout = frontchannelLogout; - } -} - diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ComponentEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ComponentEntity.java deleted file mode 100755 index 3ad6d6ee530..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ComponentEntity.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.common.util.MultivaluedHashMap; - -import java.util.List; -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class ComponentEntity extends AbstractIdentifiableEntity { - protected String name; - protected String providerType; - protected String providerId; - protected String parentId; - protected String subType; - protected Map> config = new MultivaluedHashMap<>(); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getProviderType() { - return providerType; - } - - public void setProviderType(String providerType) { - this.providerType = providerType; - } - - public String getProviderId() { - return providerId; - } - - public void setProviderId(String providerId) { - this.providerId = providerId; - } - - public String getParentId() { - return parentId; - } - - public void setParentId(String parentId) { - this.parentId = parentId; - } - - public String getSubType() { - return subType; - } - - public void setSubType(String subType) { - this.subType = subType; - } - - public Map> getConfig() { - return config; - } - - public void setConfig(Map> config) { - this.config = config; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/CredentialEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/CredentialEntity.java deleted file mode 100755 index f08964945d2..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/CredentialEntity.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.common.util.MultivaluedHashMap; - -import java.util.List; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class CredentialEntity extends AbstractIdentifiableEntity { - - protected String type; - protected String value; - protected String device; - protected byte[] salt; - protected int hashIterations; - protected Long createdDate; - protected UserEntity user; - protected int counter; - protected String algorithm; - protected int digits; - protected int period; - protected Map> config = new MultivaluedHashMap<>(); - - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getDevice() { - return device; - } - - public void setDevice(String device) { - this.device = device; - } - - public byte[] getSalt() { - return salt; - } - - public void setSalt(byte[] salt) { - this.salt = salt; - } - - public int getHashIterations() { - return hashIterations; - } - - public void setHashIterations(int hashIterations) { - this.hashIterations = hashIterations; - } - - public Long getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Long createdDate) { - this.createdDate = createdDate; - } - - public UserEntity getUser() { - return user; - } - - public void setUser(UserEntity user) { - this.user = user; - } - - public int getCounter() { - return counter; - } - - public void setCounter(int counter) { - this.counter = counter; - } - - public String getAlgorithm() { - return algorithm; - } - - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } - - public int getDigits() { - return digits; - } - - public void setDigits(int digits) { - this.digits = digits; - } - - public int getPeriod() { - return period; - } - - public void setPeriod(int period) { - this.period = period; - } - - public Map> getConfig() { - return config; - } - - public void setConfig(Map> config) { - this.config = config; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/FederatedIdentityEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/FederatedIdentityEntity.java deleted file mode 100644 index 6db210bc9ea..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/FederatedIdentityEntity.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -/** - * @author Marek Posolda - */ -public class FederatedIdentityEntity { - - private String userId; - private String userName; - private String identityProvider; - private String token; - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getIdentityProvider() { - return identityProvider; - } - - public void setIdentityProvider(String identityProvider) { - this.identityProvider = identityProvider; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - FederatedIdentityEntity that = (FederatedIdentityEntity) o; - - if (identityProvider != null && (that.identityProvider == null || !identityProvider.equals(that.identityProvider))) return false; - if (userId != null && (that.userId == null || !userId.equals(that.userId))) return false; - if (identityProvider == null && that.identityProvider != null)return false; - if (userId == null && that.userId != null) return false; - - return true; - } - - @Override - public int hashCode() { - int code = 1; - if (userId != null) { - code = code * userId.hashCode() * 13; - } - if (identityProvider != null) { - code = code * identityProvider.hashCode() * 17; - } - return code; - } - - public void setToken(String token) { - this.token = token; - } - - public String getToken() { - return token; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/GroupEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/GroupEntity.java deleted file mode 100755 index 0f40cd59024..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/GroupEntity.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.List; -import java.util.Map; - -/** - * @author Bill Burke/a> - */ -public class GroupEntity extends AbstractIdentifiableEntity { - - private String name; - private String realmId; - - private List roleIds; - private String parentId; - private Map> attributes; - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public List getRoleIds() { - return roleIds; - } - - public void setRoleIds(List roleIds) { - this.roleIds = roleIds; - } - - public Map> getAttributes() { - return attributes; - } - - public void setAttributes(Map> attributes) { - this.attributes = attributes; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getParentId() { - return parentId; - } - - public void setParentId(String parentId) { - this.parentId = parentId; - } -} - diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderEntity.java deleted file mode 100755 index e536fc8ef85..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderEntity.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Pedro Igor - */ -public class IdentityProviderEntity { - - private String internalId; - private String alias; - private String displayName; - private String providerId; - private String name; - private boolean enabled; - private boolean trustEmail; - private boolean storeToken; - protected boolean addReadTokenRoleOnCreate; - private boolean authenticateByDefault; - private String firstBrokerLoginFlowId; - private String postBrokerLoginFlowId; - - private Map config = new HashMap(); - - public String getInternalId() { - return this.internalId; - } - - public void setInternalId(String internalId) { - this.internalId = internalId; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isAuthenticateByDefault() { - return authenticateByDefault; - } - - public void setAuthenticateByDefault(boolean authenticateByDefault) { - this.authenticateByDefault = authenticateByDefault; - } - - public String getFirstBrokerLoginFlowId() { - return firstBrokerLoginFlowId; - } - - public void setFirstBrokerLoginFlowId(String firstBrokerLoginFlowId) { - this.firstBrokerLoginFlowId = firstBrokerLoginFlowId; - } - - public String getPostBrokerLoginFlowId() { - return postBrokerLoginFlowId; - } - - public void setPostBrokerLoginFlowId(String postBrokerLoginFlowId) { - this.postBrokerLoginFlowId = postBrokerLoginFlowId; - } - - public boolean isStoreToken() { - return this.storeToken; - } - - public void setStoreToken(boolean storeToken) { - this.storeToken = storeToken; - } - - public String getProviderId() { - return providerId; - } - - public void setProviderId(String providerId) { - this.providerId = providerId; - } - - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public Map getConfig() { - return this.config; - } - - public void setConfig(Map config) { - this.config = config; - } - - public boolean isAddReadTokenRoleOnCreate() { - return addReadTokenRoleOnCreate; - } - - public void setAddReadTokenRoleOnCreate(boolean addReadTokenRoleOnCreate) { - this.addReadTokenRoleOnCreate = addReadTokenRoleOnCreate; - } - - public boolean isTrustEmail() { - return trustEmail; - } - - public void setTrustEmail(boolean trustEmail) { - this.trustEmail = trustEmail; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IdentityProviderEntity)) return false; - - IdentityProviderEntity that = (IdentityProviderEntity) o; - - if (!internalId.equals(that.internalId)) return false; - - return true; - } - - @Override - public int hashCode() { - return internalId.hashCode(); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderMapperEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderMapperEntity.java deleted file mode 100755 index d5d750d95b1..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/IdentityProviderMapperEntity.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class IdentityProviderMapperEntity extends AbstractIdentifiableEntity { - protected String name; - protected String identityProviderAlias; - protected String identityProviderMapper; - protected Map config; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Map getConfig() { - return config; - } - - public void setConfig(Map config) { - this.config = config; - } - - public String getIdentityProviderAlias() { - return identityProviderAlias; - } - - public void setIdentityProviderAlias(String identityProviderAlias) { - this.identityProviderAlias = identityProviderAlias; - } - - public String getIdentityProviderMapper() { - return identityProviderMapper; - } - - public void setIdentityProviderMapper(String identityProviderMapper) { - this.identityProviderMapper = identityProviderMapper; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientEntity.java deleted file mode 100755 index 10411a188f8..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientEntity.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "clients") -public class MongoClientEntity extends ClientEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext context) { - // Remove all roles, which belongs to this application - DBObject query = new QueryBuilder() - .and("clientId").is(getId()) - .get(); - context.getMongoStore().removeEntities(MongoRoleEntity.class, query, true, context); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientTemplateEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientTemplateEntity.java deleted file mode 100755 index 7923e6efa91..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoClientTemplateEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Bill Burke - */ -@MongoCollection(collectionName = "clientTemplates") -public class MongoClientTemplateEntity extends ClientTemplateEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext context) { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java deleted file mode 100755 index c3f8e8a7883..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - */ -@MongoCollection(collectionName = "groups") -public class MongoGroupEntity extends GroupEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext invContext) { - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoMigrationModelEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoMigrationModelEntity.java deleted file mode 100755 index 8ea915bfe99..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoMigrationModelEntity.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -@MongoCollection(collectionName = "migrationModel") -public class MongoMigrationModelEntity implements MongoIdentifiableEntity { - public static final String MIGRATION_MODEL_ID = "VERSION"; - private String id = MIGRATION_MODEL_ID; - private String version; - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - - } - - @Override - public void afterRemove(MongoStoreInvocationContext invocationContext) { - - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOfflineUserSessionEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOfflineUserSessionEntity.java deleted file mode 100644 index d14210a4c32..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOfflineUserSessionEntity.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "offlineUserSessions") -public class MongoOfflineUserSessionEntity extends MongoUserSessionEntity { -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOnlineUserSessionEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOnlineUserSessionEntity.java deleted file mode 100644 index bbfb904ce26..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoOnlineUserSessionEntity.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "userSessions") -public class MongoOnlineUserSessionEntity extends MongoUserSessionEntity { -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRealmEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRealmEntity.java deleted file mode 100755 index e7b5bd82f3e..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRealmEntity.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "realms") -public class MongoRealmEntity extends RealmEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext context) { - DBObject query = new QueryBuilder() - .and("realmId").is(getId()) - .get(); - - // Remove all roles of this realm - context.getMongoStore().removeEntities(MongoGroupEntity.class, query, true, context); - - - // Remove all roles of this realm - context.getMongoStore().removeEntities(MongoRoleEntity.class, query, true, context); - - // Remove all client templates of this realm - context.getMongoStore().removeEntities(MongoClientTemplateEntity.class, query, true, context); - - // Remove all client templates of this realm - context.getMongoStore().removeEntities(MongoGroupEntity.class, query, true, context); - - // Remove all clients of this realm - context.getMongoStore().removeEntities(MongoClientEntity.class, query, true, context); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRoleEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRoleEntity.java deleted file mode 100755 index 660cca592d1..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoRoleEntity.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.jboss.logging.Logger; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoField; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -import java.util.List; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "roles") -public class MongoRoleEntity extends RoleEntity implements MongoIdentifiableEntity { - - private static final Logger logger = Logger.getLogger(MongoRoleEntity.class); - - @MongoField - // TODO This is required as Mongo doesn't support sparse indexes with compound keys (see https://jira.mongodb.org/browse/SERVER-2193) - public String getNameIndex() { - String realmId = getRealmId(); - String clientId = getClientId(); - String name = getName(); - - if (realmId != null) { - return realmId + "//" + name; - } else { - return clientId + "//" + name; - } - } - - public void setNameIndex(String ignored) { - } - - @Override - public void afterRemove(MongoStoreInvocationContext invContext) { - MongoStore mongoStore = invContext.getMongoStore(); - - // Remove from groups - DBObject query = new QueryBuilder() - .and("roleIds").is(getId()) - .get(); - - List groups = mongoStore.loadEntities(MongoGroupEntity.class, query, invContext); - for (MongoGroupEntity group : groups) { - mongoStore.pullItemFromList(group, "roleIds", getId(), invContext); - } - - - // Remove this scope from all clients, which has it - query = new QueryBuilder() - .and("scopeIds").is(getId()) - .get(); - - List clients = mongoStore.loadEntities(MongoClientEntity.class, query, invContext); - for (MongoClientEntity client : clients) { - //logger.info("Removing scope " + getName() + " from user " + user.getUsername()); - mongoStore.pullItemFromList(client, "scopeIds", getId(), invContext); - } - - // Remove this scope from all clientTemplates, which has it - List clientTemplates = mongoStore.loadEntities(MongoClientTemplateEntity.class, query, invContext); - for (MongoClientTemplateEntity clientTemplate : clientTemplates) { - //logger.info("Removing scope " + getName() + " from user " + user.getUsername()); - mongoStore.pullItemFromList(clientTemplate, "scopeIds", getId(), invContext); - } - - // Remove this role from others who has it as composite - query = new QueryBuilder() - .and("compositeRoleIds").is(getId()) - .get(); - List parentRoles = mongoStore.loadEntities(MongoRoleEntity.class, query, invContext); - for (MongoRoleEntity role : parentRoles) { - mongoStore.pullItemFromList(role, "compositeRoleIds", getId(), invContext); - } - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserConsentEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserConsentEntity.java deleted file mode 100644 index 61bf684403f..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserConsentEntity.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "userConsents") -public class MongoUserConsentEntity extends UserConsentEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext invocationContext) { - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserEntity.java deleted file mode 100755 index 909391b8115..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserEntity.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Marek Posolda - */ -@MongoCollection(collectionName = "users") -public class MongoUserEntity extends UserEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext context) { - // Remove all consents of this user - DBObject query = new QueryBuilder() - .and("userId").is(getId()) - .get(); - - context.getMongoStore().removeEntities(MongoUserConsentEntity.class, query, true, context); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserSessionEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserSessionEntity.java deleted file mode 100644 index 0e60c68fcc8..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoUserSessionEntity.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; - -/** - * @author Marek Posolda - */ -public abstract class MongoUserSessionEntity extends PersistentUserSessionEntity implements MongoIdentifiableEntity { - - @Override - public void afterRemove(MongoStoreInvocationContext invocationContext) { - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentClientSessionEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentClientSessionEntity.java deleted file mode 100644 index b4acfbf0c0d..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentClientSessionEntity.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -/** - * @author Marek Posolda - */ -public class PersistentClientSessionEntity { - - private String clientSessionId; - private String clientId; - private int timestamp; - private String data; - - public String getClientSessionId() { - return clientSessionId; - } - - public void setClientSessionId(String clientSessionId) { - this.clientSessionId = clientSessionId; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public int getTimestamp() { - return timestamp; - } - - public void setTimestamp(int timestamp) { - this.timestamp = timestamp; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentUserSessionEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentUserSessionEntity.java deleted file mode 100755 index 267ace4dc1d..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/PersistentUserSessionEntity.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.List; - -/** - * @author Marek Posolda - */ -public class PersistentUserSessionEntity extends AbstractIdentifiableEntity { - - private String realmId; - private String userId; - private int lastSessionRefresh; - private String data; - private List clientSessions; - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public int getLastSessionRefresh() { - return lastSessionRefresh; - } - - public void setLastSessionRefresh(int lastSessionRefresh) { - this.lastSessionRefresh = lastSessionRefresh; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public List getClientSessions() { - return clientSessions; - } - - public void setClientSessions(List clientSessions) { - this.clientSessions = clientSessions; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ProtocolMapperEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ProtocolMapperEntity.java deleted file mode 100755 index 312845452a1..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/ProtocolMapperEntity.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class ProtocolMapperEntity extends AbstractIdentifiableEntity { - protected String name; - protected String protocol; - protected String protocolMapper; - protected boolean consentRequired; - protected String consentText; - protected Map config; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getProtocolMapper() { - return protocolMapper; - } - - public void setProtocolMapper(String protocolMapper) { - this.protocolMapper = protocolMapper; - } - - public Map getConfig() { - return config; - } - - public void setConfig(Map config) { - this.config = config; - } - - public boolean isConsentRequired() { - return consentRequired; - } - - public void setConsentRequired(boolean consentRequired) { - this.consentRequired = consentRequired; - } - - public String getConsentText() { - return consentText; - } - - public void setConsentText(String consentText) { - this.consentText = consentText; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RealmEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RealmEntity.java deleted file mode 100755 index 07df0a833ad..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RealmEntity.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class RealmEntity extends AbstractIdentifiableEntity { - - private String name; - private String displayName; - private String displayNameHtml; - private boolean enabled; - private String sslRequired; - private boolean registrationAllowed; - protected boolean registrationEmailAsUsername; - private boolean rememberMe; - private boolean verifyEmail; - private boolean loginWithEmailAllowed; - private boolean duplicateEmailsAllowed; - private boolean resetPasswordAllowed; - private String passwordPolicy; - - protected String otpPolicyType; - protected String otpPolicyAlgorithm; - protected int otpPolicyInitialCounter; - protected int otpPolicyDigits; - protected int otpPolicyLookAheadWindow; - protected int otpPolicyPeriod; - - - private boolean editUsernameAllowed; - //--- brute force settings - private boolean bruteForceProtected; - private int maxFailureWaitSeconds; - private int minimumQuickLoginWaitSeconds; - private int waitIncrementSeconds; - private long quickLoginCheckMilliSeconds; - private int maxDeltaTimeSeconds; - private int failureFactor; - //--- end brute force settings - - private boolean revokeRefreshToken; - private int ssoSessionIdleTimeout; - private int ssoSessionMaxLifespan; - private int offlineSessionIdleTimeout; - private int accessTokenLifespan; - private int accessTokenLifespanForImplicitFlow; - private int accessCodeLifespan; - private int accessCodeLifespanUserAction; - private int accessCodeLifespanLogin; - private int notBefore; - - private String loginTheme; - private String accountTheme; - private String adminTheme; - private String emailTheme; - - // We are using names of defaultRoles (not ids) - private List defaultRoles = new LinkedList(); - private List defaultGroups = new LinkedList(); - - private List requiredCredentials = new LinkedList<>(); - private List componentEntities = new LinkedList<>(); - private List userFederationProviders = new LinkedList(); - private List userFederationMappers = new LinkedList(); - private List identityProviders = new LinkedList(); - - private Map browserSecurityHeaders = new HashMap(); - private Map smtpConfig = new HashMap(); - private Map socialConfig = new HashMap(); - - private Map attributes = new HashMap<>(); - - private boolean eventsEnabled; - private long eventsExpiration; - private List eventsListeners = new ArrayList(); - private List enabledEventTypes = new ArrayList(); - - protected boolean adminEventsEnabled; - protected boolean adminEventsDetailsEnabled; - - private String masterAdminClient; - - private boolean internationalizationEnabled; - private List supportedLocales = new ArrayList(); - private String defaultLocale; - private List identityProviderMappers = new ArrayList(); - private List authenticationFlows = new ArrayList<>(); - private List authenticatorConfigs = new ArrayList<>(); - private List requiredActionProviders = new ArrayList<>(); - private String browserFlow; - private String registrationFlow; - private String directGrantFlow; - private String resetCredentialsFlow; - private String clientAuthenticationFlow; - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public String getDisplayNameHtml() { - return displayNameHtml; - } - - public void setDisplayNameHtml(String displayNameHtml) { - this.displayNameHtml = displayNameHtml; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getSslRequired() { - return sslRequired; - } - - public void setSslRequired(String sslRequired) { - this.sslRequired = sslRequired; - } - - public boolean isRegistrationAllowed() { - return registrationAllowed; - } - - public void setRegistrationAllowed(boolean registrationAllowed) { - this.registrationAllowed = registrationAllowed; - } - - public boolean isRegistrationEmailAsUsername() { - return registrationEmailAsUsername; - } - - public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) { - this.registrationEmailAsUsername = registrationEmailAsUsername; - } - - public boolean isRememberMe() { - return rememberMe; - } - - public void setRememberMe(boolean rememberMe) { - this.rememberMe = rememberMe; - } - - public boolean isVerifyEmail() { - return verifyEmail; - } - - public void setVerifyEmail(boolean verifyEmail) { - this.verifyEmail = verifyEmail; - } - - public boolean isLoginWithEmailAllowed() { - return loginWithEmailAllowed; - } - - public void setLoginWithEmailAllowed(boolean loginWithEmailAllowed) { - this.loginWithEmailAllowed = loginWithEmailAllowed; - } - - public boolean isDuplicateEmailsAllowed() { - return duplicateEmailsAllowed; - } - - public void setDuplicateEmailsAllowed(boolean duplicateEmailsAllowed) { - this.duplicateEmailsAllowed = duplicateEmailsAllowed; - } - - public boolean isResetPasswordAllowed() { - return resetPasswordAllowed; - } - - public void setResetPasswordAllowed(boolean resetPasswordAllowed) { - this.resetPasswordAllowed = resetPasswordAllowed; - } - - public boolean isEditUsernameAllowed() { - return editUsernameAllowed; - } - - public void setEditUsernameAllowed(boolean editUsernameAllowed) { - this.editUsernameAllowed = editUsernameAllowed; - } - - public String getPasswordPolicy() { - return passwordPolicy; - } - - public void setPasswordPolicy(String passwordPolicy) { - this.passwordPolicy = passwordPolicy; - } - - public boolean isBruteForceProtected() { - return bruteForceProtected; - } - - public void setBruteForceProtected(boolean bruteForceProtected) { - this.bruteForceProtected = bruteForceProtected; - } - - public int getMaxFailureWaitSeconds() { - return maxFailureWaitSeconds; - } - - public void setMaxFailureWaitSeconds(int maxFailureWaitSeconds) { - this.maxFailureWaitSeconds = maxFailureWaitSeconds; - } - - public int getMinimumQuickLoginWaitSeconds() { - return minimumQuickLoginWaitSeconds; - } - - public void setMinimumQuickLoginWaitSeconds(int minimumQuickLoginWaitSeconds) { - this.minimumQuickLoginWaitSeconds = minimumQuickLoginWaitSeconds; - } - - public int getWaitIncrementSeconds() { - return waitIncrementSeconds; - } - - public void setWaitIncrementSeconds(int waitIncrementSeconds) { - this.waitIncrementSeconds = waitIncrementSeconds; - } - - public long getQuickLoginCheckMilliSeconds() { - return quickLoginCheckMilliSeconds; - } - - public void setQuickLoginCheckMilliSeconds(long quickLoginCheckMilliSeconds) { - this.quickLoginCheckMilliSeconds = quickLoginCheckMilliSeconds; - } - - public int getMaxDeltaTimeSeconds() { - return maxDeltaTimeSeconds; - } - - public void setMaxDeltaTimeSeconds(int maxDeltaTimeSeconds) { - this.maxDeltaTimeSeconds = maxDeltaTimeSeconds; - } - - public int getFailureFactor() { - return failureFactor; - } - - public void setFailureFactor(int failureFactor) { - this.failureFactor = failureFactor; - } - - public boolean isRevokeRefreshToken() { - return revokeRefreshToken; - } - - public void setRevokeRefreshToken(boolean revokeRefreshToken) { - this.revokeRefreshToken = revokeRefreshToken; - } - - public int getSsoSessionIdleTimeout() { - return ssoSessionIdleTimeout; - } - - public void setSsoSessionIdleTimeout(int ssoSessionIdleTimeout) { - this.ssoSessionIdleTimeout = ssoSessionIdleTimeout; - } - - public int getSsoSessionMaxLifespan() { - return ssoSessionMaxLifespan; - } - - public void setSsoSessionMaxLifespan(int ssoSessionMaxLifespan) { - this.ssoSessionMaxLifespan = ssoSessionMaxLifespan; - } - - public int getOfflineSessionIdleTimeout() { - return offlineSessionIdleTimeout; - } - - public void setOfflineSessionIdleTimeout(int offlineSessionIdleTimeout) { - this.offlineSessionIdleTimeout = offlineSessionIdleTimeout; - } - - public int getAccessTokenLifespan() { - return accessTokenLifespan; - } - - public void setAccessTokenLifespan(int accessTokenLifespan) { - this.accessTokenLifespan = accessTokenLifespan; - } - - public int getAccessTokenLifespanForImplicitFlow() { - return accessTokenLifespanForImplicitFlow; - } - - public void setAccessTokenLifespanForImplicitFlow(int accessTokenLifespanForImplicitFlow) { - this.accessTokenLifespanForImplicitFlow = accessTokenLifespanForImplicitFlow; - } - - public int getAccessCodeLifespan() { - return accessCodeLifespan; - } - - public void setAccessCodeLifespan(int accessCodeLifespan) { - this.accessCodeLifespan = accessCodeLifespan; - } - - public int getAccessCodeLifespanUserAction() { - return accessCodeLifespanUserAction; - } - - public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { - this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; - } - public int getAccessCodeLifespanLogin() { - return accessCodeLifespanLogin; - } - - public void setAccessCodeLifespanLogin(int accessCodeLifespanLogin) { - this.accessCodeLifespanLogin = accessCodeLifespanLogin; - } - - public int getNotBefore() { - return notBefore; - } - - public void setNotBefore(int notBefore) { - this.notBefore = notBefore; - } - - public String getLoginTheme() { - return loginTheme; - } - - public void setLoginTheme(String loginTheme) { - this.loginTheme = loginTheme; - } - - public String getAccountTheme() { - return accountTheme; - } - - public void setAccountTheme(String accountTheme) { - this.accountTheme = accountTheme; - } - - public String getAdminTheme() { - return adminTheme; - } - - public void setAdminTheme(String adminTheme) { - this.adminTheme = adminTheme; - } - - public String getEmailTheme() { - return emailTheme; - } - - public void setEmailTheme(String emailTheme) { - this.emailTheme = emailTheme; - } - - public List getDefaultRoles() { - return defaultRoles; - } - - public void setDefaultRoles(List defaultRoles) { - this.defaultRoles = defaultRoles; - } - - public List getRequiredCredentials() { - return requiredCredentials; - } - - public void setRequiredCredentials(List requiredCredentials) { - this.requiredCredentials = requiredCredentials; - } - - public Map getBrowserSecurityHeaders() { - return browserSecurityHeaders; - } - - public void setBrowserSecurityHeaders(Map browserSecurityHeaders) { - this.browserSecurityHeaders = browserSecurityHeaders; - } - - public Map getSmtpConfig() { - return smtpConfig; - } - - public void setSmtpConfig(Map smtpConfig) { - this.smtpConfig = smtpConfig; - } - - public Map getSocialConfig() { - return socialConfig; - } - - public void setSocialConfig(Map socialConfig) { - this.socialConfig = socialConfig; - } - - public boolean isEventsEnabled() { - return eventsEnabled; - } - - public void setEventsEnabled(boolean eventsEnabled) { - this.eventsEnabled = eventsEnabled; - } - - public long getEventsExpiration() { - return eventsExpiration; - } - - public void setEventsExpiration(long eventsExpiration) { - this.eventsExpiration = eventsExpiration; - } - - public List getEventsListeners() { - return eventsListeners; - } - - public void setEventsListeners(List eventsListeners) { - this.eventsListeners = eventsListeners; - } - - public List getEnabledEventTypes() { - return enabledEventTypes; - } - - public void setEnabledEventTypes(List enabledEventTypes) { - this.enabledEventTypes = enabledEventTypes; - } - - public boolean isAdminEventsEnabled() { - return adminEventsEnabled; - } - - public void setAdminEventsEnabled(boolean adminEventsEnabled) { - this.adminEventsEnabled = adminEventsEnabled; - } - - public boolean isAdminEventsDetailsEnabled() { - return adminEventsDetailsEnabled; - } - - public void setAdminEventsDetailsEnabled(boolean adminEventsDetailsEnabled) { - this.adminEventsDetailsEnabled = adminEventsDetailsEnabled; - } - - public String getMasterAdminClient() { - return masterAdminClient; - } - - public void setMasterAdminClient(String masterAdminClient) { - this.masterAdminClient = masterAdminClient; - } - - public List getUserFederationProviders() { - return userFederationProviders; - } - - public void setUserFederationProviders(List userFederationProviders) { - this.userFederationProviders = userFederationProviders; - } - - public List getUserFederationMappers() { - return userFederationMappers; - } - - public void setUserFederationMappers(List userFederationMappers) { - this.userFederationMappers = userFederationMappers; - } - - public List getIdentityProviders() { - return identityProviders; - } - - public void setIdentityProviders(List identityProviders) { - this.identityProviders = identityProviders; - } - - public boolean isInternationalizationEnabled() { - return internationalizationEnabled; - } - - public void setInternationalizationEnabled(boolean internationalizationEnabled) { - this.internationalizationEnabled = internationalizationEnabled; - } - - public List getSupportedLocales() { - return supportedLocales; - } - - public void setSupportedLocales(List supportedLocales) { - this.supportedLocales = supportedLocales; - } - - public String getDefaultLocale() { - return defaultLocale; - } - - public void setDefaultLocale(String defaultLocale) { - this.defaultLocale = defaultLocale; - } - - public List getIdentityProviderMappers() { - return identityProviderMappers; - } - - public void setIdentityProviderMappers(List identityProviderMappers) { - this.identityProviderMappers = identityProviderMappers; - } - - public List getAuthenticationFlows() { - return authenticationFlows; - } - - public void setAuthenticationFlows(List authenticationFlows) { - this.authenticationFlows = authenticationFlows; - } - - public List getAuthenticatorConfigs() { - return authenticatorConfigs; - } - - public void setAuthenticatorConfigs(List authenticators) { - this.authenticatorConfigs = authenticators; - } - - public List getRequiredActionProviders() { - return requiredActionProviders; - } - - public void setRequiredActionProviders(List requiredActionProviders) { - this.requiredActionProviders = requiredActionProviders; - } - - public String getOtpPolicyType() { - return otpPolicyType; - } - - public void setOtpPolicyType(String otpPolicyType) { - this.otpPolicyType = otpPolicyType; - } - - public String getOtpPolicyAlgorithm() { - return otpPolicyAlgorithm; - } - - public void setOtpPolicyAlgorithm(String otpPolicyAlgorithm) { - this.otpPolicyAlgorithm = otpPolicyAlgorithm; - } - - public int getOtpPolicyInitialCounter() { - return otpPolicyInitialCounter; - } - - public void setOtpPolicyInitialCounter(int otpPolicyInitialCounter) { - this.otpPolicyInitialCounter = otpPolicyInitialCounter; - } - - public int getOtpPolicyDigits() { - return otpPolicyDigits; - } - - public void setOtpPolicyDigits(int otpPolicyDigits) { - this.otpPolicyDigits = otpPolicyDigits; - } - - public int getOtpPolicyLookAheadWindow() { - return otpPolicyLookAheadWindow; - } - - public void setOtpPolicyLookAheadWindow(int otpPolicyLookAheadWindow) { - this.otpPolicyLookAheadWindow = otpPolicyLookAheadWindow; - } - - public int getOtpPolicyPeriod() { - return otpPolicyPeriod; - } - - public void setOtpPolicyPeriod(int otpPolicyPeriod) { - this.otpPolicyPeriod = otpPolicyPeriod; - } - - public String getBrowserFlow() { - return browserFlow; - } - - public void setBrowserFlow(String browserFlow) { - this.browserFlow = browserFlow; - } - - public String getRegistrationFlow() { - return registrationFlow; - } - - public void setRegistrationFlow(String registrationFlow) { - this.registrationFlow = registrationFlow; - } - - public String getDirectGrantFlow() { - return directGrantFlow; - } - - public void setDirectGrantFlow(String directGrantFlow) { - this.directGrantFlow = directGrantFlow; - } - - public String getResetCredentialsFlow() { - return resetCredentialsFlow; - } - - public void setResetCredentialsFlow(String resetCredentialsFlow) { - this.resetCredentialsFlow = resetCredentialsFlow; - } - - public String getClientAuthenticationFlow() { - return clientAuthenticationFlow; - } - - public void setClientAuthenticationFlow(String clientAuthenticationFlow) { - this.clientAuthenticationFlow = clientAuthenticationFlow; - } - - public List getDefaultGroups() { - return defaultGroups; - } - - public void setDefaultGroups(List defaultGroups) { - this.defaultGroups = defaultGroups; - } - - public List getComponentEntities() { - return componentEntities; - } - - public void setComponentEntities(List componentEntities) { - this.componentEntities = componentEntities; - } - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredActionProviderEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredActionProviderEntity.java deleted file mode 100755 index def4b14765f..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredActionProviderEntity.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RequiredActionProviderEntity extends AbstractIdentifiableEntity { - protected String alias; - protected String name; - protected String providerId; - protected boolean enabled; - protected boolean defaultAction; - private Map config; - - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isEnabled() { - return enabled; - } - - public boolean isDefaultAction() { - return defaultAction; - } - - public void setDefaultAction(boolean defaultAction) { - this.defaultAction = defaultAction; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getProviderId() { - return providerId; - } - - public void setProviderId(String providerId) { - this.providerId = providerId; - } - - public Map getConfig() { - return config; - } - - public void setConfig(Map config) { - this.config = config; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredCredentialEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredCredentialEntity.java deleted file mode 100644 index 566041ef196..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RequiredCredentialEntity.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -/** - * @author Marek Posolda - */ -public class RequiredCredentialEntity { - - private String type; - private boolean input; - private boolean secret; - private String formLabel; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public boolean isInput() { - return input; - } - - public void setInput(boolean input) { - this.input = input; - } - - public boolean isSecret() { - return secret; - } - - public void setSecret(boolean secret) { - this.secret = secret; - } - - public String getFormLabel() { - return formLabel; - } - - public void setFormLabel(String formLabel) { - this.formLabel = formLabel; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RoleEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RoleEntity.java deleted file mode 100644 index 4a730a97ee3..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/RoleEntity.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.List; - -/** - * @author Marek Posolda - */ -public class RoleEntity extends AbstractIdentifiableEntity { - - private String name; - private String description; - private boolean scopeParamRequired; - - private List compositeRoleIds; - - private String realmId; - private String clientId; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public boolean isScopeParamRequired() { - return scopeParamRequired; - } - - public void setScopeParamRequired(boolean scopeParamRequired) { - this.scopeParamRequired = scopeParamRequired; - } - - public List getCompositeRoleIds() { - return compositeRoleIds; - } - - public void setCompositeRoleIds(List compositeRoleIds) { - this.compositeRoleIds = compositeRoleIds; - } - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserConsentEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserConsentEntity.java deleted file mode 100644 index 1ca9e64f525..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserConsentEntity.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Marek Posolda - */ -public class UserConsentEntity extends AbstractIdentifiableEntity { - - private String userId; - private String clientId; - private List grantedRoles = new ArrayList(); - private List grantedProtocolMappers = new ArrayList(); - private Long createdDate; - private Long lastUpdatedDate; - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public List getGrantedRoles() { - return grantedRoles; - } - - public void setGrantedRoles(List grantedRoles) { - this.grantedRoles = grantedRoles; - } - - public List getGrantedProtocolMappers() { - return grantedProtocolMappers; - } - - public void setGrantedProtocolMappers(List grantedProtocolMappers) { - this.grantedProtocolMappers = grantedProtocolMappers; - } - - public Long getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Long createdDate) { - this.createdDate = createdDate; - } - - public Long getLastUpdatedDate() { - return lastUpdatedDate; - } - - public void setLastUpdatedDate(Long lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserEntity.java deleted file mode 100755 index 2dd5395338e..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserEntity.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class UserEntity extends AbstractIdentifiableEntity { - - private String username; - private Long createdTimestamp; - private String firstName; - private String lastName; - private String email; - private String emailIndex; - private boolean emailVerified; - private boolean enabled; - - private String realmId; - - private List roleIds; - private List groupIds; - - private Map> attributes; - private List requiredActions; - private List credentials = new ArrayList(); - private List federatedIdentities; - private String federationLink; - private String serviceAccountClientLink; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Long getCreatedTimestamp() { - return createdTimestamp; - } - - public void setCreatedTimestamp(Long timestamp) { - this.createdTimestamp = timestamp; - } - - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - @Deprecated // called upon deserialization only - public void setEmail(String email) { - this.email = email; - } - - public void setEmail(String email, boolean allowDuplicate) { - this.email = email; - this.emailIndex = email == null || allowDuplicate ? null : getRealmId() + "//" + email; - } - - public void setEmailIndex(String index) { - this.emailIndex = index; - } - - public String getEmailIndex() { - return emailIndex; - } - - public boolean isEmailVerified() { - return emailVerified; - } - - public void setEmailVerified(boolean emailVerified) { - this.emailVerified = emailVerified; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public List getRoleIds() { - return roleIds; - } - - public void setRoleIds(List roleIds) { - this.roleIds = roleIds; - } - - public Map> getAttributes() { - return attributes; - } - - public void setAttributes(Map> attributes) { - this.attributes = attributes; - } - - public List getRequiredActions() { - return requiredActions; - } - - public void setRequiredActions(List requiredActions) { - this.requiredActions = requiredActions; - } - - public List getCredentials() { - return credentials; - } - - public void setCredentials(List credentials) { - this.credentials = credentials; - } - - public List getFederatedIdentities() { - return federatedIdentities; - } - - public void setFederatedIdentities(List federatedIdentities) { - this.federatedIdentities = federatedIdentities; - } - - public String getFederationLink() { - return federationLink; - } - - public void setFederationLink(String federationLink) { - this.federationLink = federationLink; - } - - public String getServiceAccountClientLink() { - return serviceAccountClientLink; - } - - public void setServiceAccountClientLink(String serviceAccountClientLink) { - this.serviceAccountClientLink = serviceAccountClientLink; - } - - public List getGroupIds() { - return groupIds; - } - - public void setGroupIds(List groupIds) { - this.groupIds = groupIds; - } -} - diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationMapperEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationMapperEntity.java deleted file mode 100755 index a02e573f784..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationMapperEntity.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.Map; - -/** - * @author Marek Posolda - */ -public class UserFederationMapperEntity extends AbstractIdentifiableEntity { - - protected String name; - protected String federationProviderId; - protected String federationMapperType; - protected Map config; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getFederationProviderId() { - return federationProviderId; - } - - public void setFederationProviderId(String federationProviderId) { - this.federationProviderId = federationProviderId; - } - - public String getFederationMapperType() { - return federationMapperType; - } - - public void setFederationMapperType(String federationMapperType) { - this.federationMapperType = federationMapperType; - } - - public Map getConfig() { - return config; - } - - public void setConfig(Map config) { - this.config = config; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationProviderEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationProviderEntity.java deleted file mode 100755 index 637e905b9ae..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/UserFederationProviderEntity.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.keycloak.entities; - -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class UserFederationProviderEntity extends AbstractIdentifiableEntity { - protected String providerName; - protected Map config; - protected int priority; - protected String displayName; - private int fullSyncPeriod; - private int changedSyncPeriod; - private int lastSync; - - - public String getProviderName() { - return providerName; - } - - public void setProviderName(String providerName) { - this.providerName = providerName; - } - - public Map getConfig() { - return config; - } - - public void setConfig(Map config) { - this.config = config; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public int getFullSyncPeriod() { - return fullSyncPeriod; - } - - public void setFullSyncPeriod(int fullSyncPeriod) { - this.fullSyncPeriod = fullSyncPeriod; - } - - public int getChangedSyncPeriod() { - return changedSyncPeriod; - } - - public void setChangedSyncPeriod(int changedSyncPeriod) { - this.changedSyncPeriod = changedSyncPeriod; - } - - public int getLastSync() { - return lastSync; - } - - public void setLastSync(int lastSync) { - this.lastSync = lastSync; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java b/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java deleted file mode 100755 index 1555a5b02c0..00000000000 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.keycloak.models.mongo.utils; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.ClientModel; -import org.keycloak.models.ClientTemplateModel; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.mongo.keycloak.adapters.ClientAdapter; -import org.keycloak.models.mongo.keycloak.adapters.ClientTemplateAdapter; -import org.keycloak.models.mongo.keycloak.adapters.UserAdapter; -import org.keycloak.models.mongo.keycloak.entities.ClientEntity; -import org.keycloak.models.mongo.keycloak.entities.ClientTemplateEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoUserEntity; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * @author Marek Posolda - */ -public class MongoModelUtils { - - // Get everything including both application and realm roles - public static List getAllRolesOfUser(RealmModel realm, UserModel user) { - MongoUserEntity userEntity = ((UserAdapter)user).getUser(); - List roleIds = userEntity.getRoleIds(); - - if (roleIds == null || roleIds.isEmpty()) { - return Collections.emptyList(); - } - - List roles = new LinkedList(); - for (String roleId : roleIds) { - RoleModel role = realm.getRoleById(roleId); - if (role != null) { - roles.add(role); - } - } - return roles; - } - - // Get everything including both application and realm scopes - public static List getAllScopesOfClient(ClientModel client, MongoStoreInvocationContext invContext) { - ClientEntity scopedEntity = ((ClientAdapter)client).getMongoEntity(); - List scopeIds = scopedEntity.getScopeIds(); - - if (scopeIds == null || scopeIds.isEmpty()) { - return Collections.emptyList(); - } - - DBObject query = new QueryBuilder() - .and("_id").in(scopeIds) - .get(); - return invContext.getMongoStore().loadEntities(MongoRoleEntity.class, query, invContext); - } - public static List getAllScopesOfTemplate(ClientTemplateModel template, MongoStoreInvocationContext invContext) { - ClientTemplateEntity scopedEntity = ((ClientTemplateAdapter)template).getMongoEntity(); - List scopeIds = scopedEntity.getScopeIds(); - - if (scopeIds == null || scopeIds.isEmpty()) { - return Collections.emptyList(); - } - - DBObject query = new QueryBuilder() - .and("_id").in(scopeIds) - .get(); - return invContext.getMongoStore().loadEntities(MongoRoleEntity.class, query, invContext); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProvider.java b/model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProvider.java deleted file mode 100644 index a5f66ef577e..00000000000 --- a/model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProvider.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.storage.mongo; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.common.util.MultivaluedHashMap; -import org.keycloak.component.ComponentModel; -import org.keycloak.connections.mongo.api.MongoStore; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.credential.CredentialModel; -import org.keycloak.credential.UserCredentialStore; -import org.keycloak.models.ClientModel; -import org.keycloak.models.FederatedIdentityModel; -import org.keycloak.models.GroupModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.ProtocolMapperModel; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserConsentModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.mongo.keycloak.entities.CredentialEntity; -import org.keycloak.models.mongo.keycloak.entities.FederatedIdentityEntity; -import org.keycloak.models.utils.KeycloakModelUtils; -import org.keycloak.storage.StorageId; -import org.keycloak.storage.UserStorageProvider; -import org.keycloak.storage.federated.UserFederatedStorageProvider; -import org.keycloak.storage.mongo.entity.FederatedUser; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class MongoUserFederatedStorageProvider implements - UserFederatedStorageProvider, - UserCredentialStore { - - private final MongoStoreInvocationContext invocationContext; - private final KeycloakSession session; - - public MongoUserFederatedStorageProvider(KeycloakSession session, MongoStoreInvocationContext invocationContext) { - this.session = session; - this.invocationContext = invocationContext; - } - - protected MongoStore getMongoStore() { - return invocationContext.getMongoStore(); - } - - - protected FederatedUser addUserEntity(RealmModel realm, String id) { - FederatedUser userEntity = new FederatedUser(); - userEntity.setId(id); - userEntity.setStorageId(StorageId.providerId(id)); - userEntity.setRealmId(realm.getId()); - - getMongoStore().insertEntity(userEntity, invocationContext); - return userEntity; - } - - protected FederatedUser getUserById(String id) { - return getMongoStore().loadEntity(FederatedUser.class, id, invocationContext); - } - - protected FederatedUser findOrCreate(RealmModel realm, String id) { - FederatedUser user = getUserById(id); - if (user != null) return user; - return addUserEntity(realm, id); - } - - - - @Override - public boolean removeStoredCredential(RealmModel realm, String userId, String id) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null) return false; - CredentialEntity ce = getCredentialEntity(id, userEntity); - if (ce != null) return getMongoStore().pullItemFromList(userEntity, "credentials", ce, invocationContext); - return false; - } - - private CredentialEntity getCredentialEntity(String id, FederatedUser userEntity) { - CredentialEntity ce = null; - if (userEntity.getCredentials() != null) { - for (CredentialEntity credentialEntity : userEntity.getCredentials()) { - if (credentialEntity.getId().equals(id)) { - ce = credentialEntity; - break; - - } - } - } - return ce; - } - - protected CredentialModel toModel(CredentialEntity entity) { - CredentialModel model = new CredentialModel(); - model.setId(entity.getId()); - model.setHashIterations(entity.getHashIterations()); - model.setType(entity.getType()); - model.setValue(entity.getValue()); - model.setAlgorithm(entity.getAlgorithm()); - model.setSalt(entity.getSalt()); - model.setPeriod(entity.getPeriod()); - model.setCounter(entity.getCounter()); - model.setCreatedDate(entity.getCreatedDate()); - model.setDevice(entity.getDevice()); - model.setDigits(entity.getDigits()); - MultivaluedHashMap config = new MultivaluedHashMap<>(); - model.setConfig(config); - if (entity.getConfig() != null) { - config.putAll(entity.getConfig()); - } - - return model; - } - - @Override - public CredentialModel getStoredCredentialById(RealmModel realm, String userId, String id) { - FederatedUser userEntity = getUserById(id); - if (userEntity != null && userEntity.getCredentials() != null) { - for (CredentialEntity credentialEntity : userEntity.getCredentials()) { - if (credentialEntity.getId().equals(id)) { - return toModel(credentialEntity); - - } - } - } - return null; - } - - @Override - public List getStoredCredentials(RealmModel realm, String userId) { - FederatedUser userEntity = getUserById(userId); - if (userEntity != null && userEntity.getCredentials() != null) { - List list = new LinkedList<>(); - for (CredentialEntity credentialEntity : userEntity.getCredentials()) { - list.add(toModel(credentialEntity)); - } - return list; - } - return Collections.EMPTY_LIST; - } - - @Override - public List getStoredCredentialsByType(RealmModel realm, String userId, String type) { - FederatedUser userEntity = getUserById(userId); - if (userEntity != null && userEntity.getCredentials() != null) { - List list = new LinkedList<>(); - for (CredentialEntity credentialEntity : userEntity.getCredentials()) { - if (type.equals(credentialEntity.getType())) list.add(toModel(credentialEntity)); - } - return list; - } - return Collections.EMPTY_LIST; - } - - @Override - public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, String userId, String name, String type) { - FederatedUser userEntity = getUserById(userId); - if (userEntity != null && userEntity.getCredentials() != null) { - for (CredentialEntity credentialEntity : userEntity.getCredentials()) { - if (credentialEntity.getDevice().equals(name) && type.equals(credentialEntity.getType())) { - return toModel(credentialEntity); - - } - } - } - return null; - } - - @Override - public List getStoredUsers(RealmModel realm, int first, int max) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - - DBObject query = queryBuilder.get(); - List users = getMongoStore().loadEntities(FederatedUser.class, query, null, first, max, invocationContext); - List ids = new LinkedList<>(); - for (FederatedUser user : users) ids.add(user.getId()); - return ids; - } - - @Override - public void preRemove(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - getMongoStore().removeEntities(FederatedUser.class, query, true, invocationContext); - } - - @Override - public void preRemove(RealmModel realm, GroupModel group) { - DBObject query = new QueryBuilder() - .and("groupIds").is(group.getId()) - .get(); - - DBObject pull = new BasicDBObject("$pull", query); - getMongoStore().updateEntities(FederatedUser.class, query, pull, invocationContext); - - } - - @Override - public void preRemove(RealmModel realm, RoleModel role) { - DBObject query = new QueryBuilder() - .and("roleIds").is(role.getId()) - .get(); - - DBObject pull = new BasicDBObject("$pull", query); - getMongoStore().updateEntities(FederatedUser.class, query, pull, invocationContext); - - } - - @Override - public void preRemove(RealmModel realm, ClientModel client) { - - } - - @Override - public void preRemove(ProtocolMapperModel protocolMapper) { - - } - - @Override - public void preRemove(RealmModel realm, UserModel user) { - getMongoStore().removeEntity(FederatedUser.class, user.getId(), invocationContext); - - } - - @Override - public void preRemove(RealmModel realm, ComponentModel model) { - if (!model.getProviderType().equals(UserStorageProvider.class.getName())) return; - DBObject query = new QueryBuilder() - .and("storageId").is(model.getId()) - .get(); - getMongoStore().removeEntities(FederatedUser.class, query, true, invocationContext); - - } - - @Override - public void close() { - - } - - @Override - public void setSingleAttribute(RealmModel realm, String userId, String name, String value) { - FederatedUser userEntity = findOrCreate(realm, userId); - if (userEntity.getAttributes() == null) { - userEntity.setAttributes(new HashMap<>()); - } - - List attrValues = new LinkedList<>(); - attrValues.add(value); - userEntity.getAttributes().put(name, attrValues); - getMongoStore().updateEntity(userEntity, invocationContext); - } - - @Override - public void setAttribute(RealmModel realm, String userId, String name, List values) { - FederatedUser userEntity = findOrCreate(realm, userId); - if (userEntity.getAttributes() == null) { - userEntity.setAttributes(new HashMap<>()); - } - - userEntity.getAttributes().put(name, values); - getMongoStore().updateEntity(userEntity, invocationContext); - - } - - @Override - public void removeAttribute(RealmModel realm, String userId, String name) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getAttributes() == null) return; - - userEntity.getAttributes().remove(name); - getMongoStore().updateEntity(userEntity, invocationContext); - } - - @Override - public MultivaluedHashMap getAttributes(RealmModel realm, String userId) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getAttributes() == null) return new MultivaluedHashMap<>(); - MultivaluedHashMap result = new MultivaluedHashMap<>(); - result.putAll(userEntity.getAttributes()); - return result; - } - - @Override - public List getUsersByUserAttribute(RealmModel realm, String name, String value) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - queryBuilder.and("attributes." + name).is(value); - - List users = getMongoStore().loadEntities(FederatedUser.class, queryBuilder.get(), invocationContext); - List ids = new LinkedList<>(); - for (FederatedUser user : users) ids.add(user.getId()); - return ids; - } - - @Override - public String getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) { - DBObject query = new QueryBuilder() - .and("federatedIdentities.identityProvider").is(socialLink.getIdentityProvider()) - .and("federatedIdentities.userId").is(socialLink.getUserId()) - .and("realmId").is(realm.getId()) - .get(); - FederatedUser userEntity = getMongoStore().loadSingleEntity(FederatedUser.class, query, invocationContext); - return userEntity != null ? userEntity.getId() : null; - } - - @Override - public void addFederatedIdentity(RealmModel realm, String userId, FederatedIdentityModel socialLink) { - FederatedUser userEntity = findOrCreate(realm, userId); - FederatedIdentityEntity federatedIdentityEntity = new FederatedIdentityEntity(); - federatedIdentityEntity.setIdentityProvider(socialLink.getIdentityProvider()); - federatedIdentityEntity.setUserId(socialLink.getUserId()); - federatedIdentityEntity.setUserName(socialLink.getUserName().toLowerCase()); - federatedIdentityEntity.setToken(socialLink.getToken()); - - getMongoStore().pushItemToList(userEntity, "federatedIdentities", federatedIdentityEntity, true, invocationContext); - } - - @Override - public boolean removeFederatedIdentity(RealmModel realm, String userId, String socialProvider) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null) return false; - - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, socialProvider); - if (federatedIdentityEntity == null) { - return false; - } - return getMongoStore().pullItemFromList(userEntity, "federatedIdentities", federatedIdentityEntity, invocationContext); } - - private FederatedIdentityEntity findFederatedIdentityLink(FederatedUser 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 void updateFederatedIdentity(RealmModel realm, String userId, FederatedIdentityModel federatedIdentityModel) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null) return; - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, federatedIdentityModel.getIdentityProvider()); - if (federatedIdentityEntity == null) return; - //pushItemToList updates the whole federatedIdentities array in Mongo so we just need to remove this object from the Java - //List and pushItemToList will handle the DB update. - userEntity.getFederatedIdentities().remove(federatedIdentityEntity); - federatedIdentityEntity.setToken(federatedIdentityModel.getToken()); - getMongoStore().pushItemToList(userEntity, "federatedIdentities", federatedIdentityEntity, true, invocationContext); - } - - @Override - public Set getFederatedIdentities(String userId, RealmModel realm) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null) return Collections.EMPTY_SET; - 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(), federatedIdentityEntity.getToken()); - result.add(model); - } - return result; - } - - @Override - public FederatedIdentityModel getFederatedIdentity(String userId, String socialProvider, RealmModel realm) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null) return null; - FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, socialProvider); - - return federatedIdentityEntity != null ? new FederatedIdentityModel(federatedIdentityEntity.getIdentityProvider(), federatedIdentityEntity.getUserId(), - federatedIdentityEntity.getUserName(), federatedIdentityEntity.getToken()) : null; - } - - @Override - public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { - session.userLocalStorage().addConsent(realm, userId, consent); - - } - - @Override - public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientInternalId) { - return session.userLocalStorage().getConsentByClient(realm, userId, clientInternalId); - } - - @Override - public List getConsents(RealmModel realm, String userId) { - return session.userLocalStorage().getConsents(realm, userId); - } - - @Override - public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) { - session.userLocalStorage().updateConsent(realm, userId, consent); - - } - - @Override - public boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId) { - return session.userLocalStorage().revokeConsentForClient(realm, userId, clientInternalId); - } - - @Override - public void updateCredential(RealmModel realm, String userId, CredentialModel cred) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null) return; - CredentialEntity entity = getCredentialEntity(cred.getId(), userEntity); - if (entity == null) return; - toEntity(cred, entity); - userEntity.getCredentials().remove(entity); - - getMongoStore().pushItemToList(userEntity, "credentials", entity, true, invocationContext); - } - - private void toEntity(CredentialModel cred, CredentialEntity entity) { - entity.setAlgorithm(cred.getAlgorithm()); - entity.setCounter(cred.getCounter()); - entity.setCreatedDate(cred.getCreatedDate()); - entity.setDevice(cred.getDevice()); - entity.setDigits(cred.getDigits()); - entity.setHashIterations(cred.getHashIterations()); - entity.setPeriod(cred.getPeriod()); - entity.setSalt(cred.getSalt()); - entity.setType(cred.getType()); - entity.setValue(cred.getValue()); - - if (cred.getConfig() == null) entity.setConfig(null); - else { - MultivaluedHashMap newConfig = new MultivaluedHashMap<>(); - newConfig.putAll(cred.getConfig()); - entity.setConfig(newConfig); - } - } - - @Override - public CredentialModel createCredential(RealmModel realm, String userId, CredentialModel cred) { - FederatedUser userEntity = findOrCreate(realm, userId); - CredentialEntity entity = new CredentialEntity(); - entity.setId(KeycloakModelUtils.generateId()); - toEntity(cred, entity); - getMongoStore().pushItemToList(userEntity, "credentials", entity, true, invocationContext); - cred.setId(entity.getId()); - return cred; - } - - @Override - public Set getGroups(RealmModel realm, String userId) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getGroupIds() == null || userEntity.getGroupIds().isEmpty()) return Collections.EMPTY_SET; - Set groups = new HashSet<>(); - for (String groupId : userEntity.getGroupIds()) { - GroupModel group = session.realms().getGroupById(groupId, realm); - if (group != null) groups.add(group); - } - - return groups; - } - - @Override - public void joinGroup(RealmModel realm, String userId, GroupModel group) { - FederatedUser userEntity = findOrCreate(realm, userId); - getMongoStore().pushItemToList(userEntity, "groupIds", group.getId(), true, invocationContext); - - - } - - @Override - public void leaveGroup(RealmModel realm, String userId, GroupModel group) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || group == null) return; - getMongoStore().pullItemFromList(userEntity, "groupIds", group.getId(), invocationContext); - - - } - - @Override - public List getMembership(RealmModel realm, GroupModel group, int firstResult, int max) { - QueryBuilder queryBuilder = new QueryBuilder() - .and("realmId").is(realm.getId()); - queryBuilder.and("groupIds").is(group.getId()); - - List users = getMongoStore().loadEntities(FederatedUser.class, queryBuilder.get(), null, firstResult, max, invocationContext); - List ids = new LinkedList<>(); - for (FederatedUser user : users) ids.add(user.getId()); - return ids; - } - - @Override - public Set getRequiredActions(RealmModel realm, String userId) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getRequiredActions() == null || userEntity.getRequiredActions().isEmpty()) return Collections.EMPTY_SET; - Set set = new HashSet<>(); - set.addAll(userEntity.getRequiredActions()); - return set; - } - - @Override - public void addRequiredAction(RealmModel realm, String userId, String action) { - FederatedUser userEntity = findOrCreate(realm, userId); - getMongoStore().pushItemToList(userEntity, "requiredActions", action, true, invocationContext); - - } - - @Override - public void removeRequiredAction(RealmModel realm, String userId, String action) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getRequiredActions() == null || userEntity.getRequiredActions().isEmpty()) return; - getMongoStore().pullItemFromList(userEntity, "requiredActions", action, invocationContext); - - } - - @Override - public void grantRole(RealmModel realm, String userId, RoleModel role) { - FederatedUser userEntity = findOrCreate(realm, userId); - getMongoStore().pushItemToList(userEntity, "roleIds", role.getId(), true, invocationContext); - - } - - @Override - public Set getRoleMappings(RealmModel realm, String userId) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getRoleIds() == null || userEntity.getRoleIds().isEmpty()) return Collections.EMPTY_SET; - Set roles = new HashSet<>(); - for (String roleId : userEntity.getRoleIds()) { - RoleModel role = realm.getRoleById(roleId); - if (role != null) roles.add(role); - } - return roles; - } - - @Override - public void deleteRoleMapping(RealmModel realm, String userId, RoleModel role) { - FederatedUser userEntity = getUserById(userId); - if (userEntity == null || userEntity.getRoleIds() == null || userEntity.getRoleIds().isEmpty()) return; - getMongoStore().pullItemFromList(userEntity, "roleIds", role.getId(), invocationContext); - - } - - @Override - public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) { - updateCredential(realm, user.getId(), cred); - } - - @Override - public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) { - return createCredential(realm, user.getId(), cred); - } - - @Override - public boolean removeStoredCredential(RealmModel realm, UserModel user, String id) { - return removeStoredCredential(realm, user.getId(), id); - } - - @Override - public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) { - return getStoredCredentialById(realm, user.getId(), id); - } - - @Override - public List getStoredCredentials(RealmModel realm, UserModel user) { - return getStoredCredentials(realm, user.getId()); - } - - @Override - public List getStoredCredentialsByType(RealmModel realm, UserModel user, String type) { - return getStoredCredentialsByType(realm, user.getId(), type); - } - - @Override - public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, UserModel user, String name, String type) { - return getStoredCredentialByNameAndType(realm, user.getId(), name, type); - } - - @Override - public int getStoredUsersCount(RealmModel realm) { - DBObject query = new QueryBuilder() - .and("realmId").is(realm.getId()) - .get(); - return getMongoStore().countEntities(FederatedUser.class, query, invocationContext); - } -} diff --git a/model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProviderFactory.java b/model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProviderFactory.java deleted file mode 100644 index d07e872cf70..00000000000 --- a/model/mongo/src/main/java/org/keycloak/storage/mongo/MongoUserFederatedStorageProviderFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.storage.mongo; - -import org.keycloak.Config; -import org.keycloak.connections.mongo.MongoConnectionProvider; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.provider.ProviderFactory; -import org.keycloak.storage.federated.UserFederatedStorageProvider; -import org.keycloak.storage.federated.UserFederatedStorageProviderFactory; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class MongoUserFederatedStorageProviderFactory implements UserFederatedStorageProviderFactory { - @Override - public UserFederatedStorageProvider create(KeycloakSession session) { - MongoConnectionProvider connection = session.getProvider(MongoConnectionProvider.class); - return new MongoUserFederatedStorageProvider(session, connection.getInvocationContext()); - } - - @Override - public void init(Config.Scope config) { - - } - - @Override - public void postInit(KeycloakSessionFactory factory) { - - } - - @Override - public void close() { - - } - - @Override - public String getId() { - return "mongo"; - } -} diff --git a/model/mongo/src/main/java/org/keycloak/storage/mongo/entity/FederatedUser.java b/model/mongo/src/main/java/org/keycloak/storage/mongo/entity/FederatedUser.java deleted file mode 100644 index c81064956a5..00000000000 --- a/model/mongo/src/main/java/org/keycloak/storage/mongo/entity/FederatedUser.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2016 Red Hat, Inc. and/or its affiliates - * and other contributors as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.keycloak.storage.mongo.entity; - -import com.mongodb.DBObject; -import com.mongodb.QueryBuilder; -import org.keycloak.connections.mongo.api.MongoCollection; -import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; -import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; -import org.keycloak.models.mongo.keycloak.entities.AbstractIdentifiableEntity; -import org.keycloak.models.mongo.keycloak.entities.CredentialEntity; -import org.keycloak.models.mongo.keycloak.entities.FederatedIdentityEntity; -import org.keycloak.models.mongo.keycloak.entities.MongoUserConsentEntity; -import org.keycloak.models.mongo.keycloak.entities.UserConsentEntity; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -@MongoCollection(collectionName = "federatedusers") -public class FederatedUser extends AbstractIdentifiableEntity implements MongoIdentifiableEntity { - protected String realmId; - protected String storageId; - - private Map> attributes; - private List roleIds; - private List groupIds; - private List requiredActions; - private List credentials; - private List federatedIdentities; - - public String getRealmId() { - return realmId; - } - - public void setRealmId(String realmId) { - this.realmId = realmId; - } - - public String getStorageId() { - return storageId; - } - - public void setStorageId(String storageId) { - this.storageId = storageId; - } - - public Map> getAttributes() { - return attributes; - } - - public void setAttributes(Map> attributes) { - this.attributes = attributes; - } - - public List getRoleIds() { - return roleIds; - } - - public void setRoleIds(List roleIds) { - this.roleIds = roleIds; - } - - public List getGroupIds() { - return groupIds; - } - - public void setGroupIds(List groupIds) { - this.groupIds = groupIds; - } - - public List getRequiredActions() { - return requiredActions; - } - - public void setRequiredActions(List requiredActions) { - this.requiredActions = requiredActions; - } - - public List getCredentials() { - return credentials; - } - - public void setCredentials(List credentials) { - this.credentials = credentials; - } - - public List getFederatedIdentities() { - return federatedIdentities; - } - - public void setFederatedIdentities(List federatedIdentities) { - this.federatedIdentities = federatedIdentities; - } - - @Override - public void afterRemove(MongoStoreInvocationContext context) { - // Remove all consents of this user - DBObject query = new QueryBuilder() - .and("userId").is(getId()) - .get(); - - context.getMongoStore().removeEntities(MongoUserConsentEntity.class, query, true, context); - } - -} diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.authorization.store.AuthorizationStoreFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.authorization.store.AuthorizationStoreFactory deleted file mode 100644 index e1d801cc483..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.authorization.store.AuthorizationStoreFactory +++ /dev/null @@ -1,37 +0,0 @@ -# -# JBoss, Home of Professional Open Source. -# Copyright 2016 Red Hat, Inc., and individual contributors -# as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# -# JBoss, Home of Professional Open Source. -# Copyright 2016 Red Hat, Inc., and individual contributors -# as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.authorization.mongo.store.MongoAuthorizationStoreFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.MongoConnectionProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.MongoConnectionProviderFactory deleted file mode 100644 index 4c312ab2d25..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.MongoConnectionProviderFactory +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.connections.mongo.DefaultMongoConnectionFactoryProvider \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.updater.MongoUpdaterProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.updater.MongoUpdaterProviderFactory deleted file mode 100644 index 8658db66320..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.connections.mongo.updater.MongoUpdaterProviderFactory +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.connections.mongo.updater.impl.DefaultMongoUpdaterProviderFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.events.EventStoreProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.events.EventStoreProviderFactory deleted file mode 100644 index 95c50d7474e..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.events.EventStoreProviderFactory +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.events.mongo.MongoEventStoreProviderFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory deleted file mode 100755 index c49fe04eec6..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.RealmProviderFactory +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.models.mongo.keycloak.adapters.MongoRealmProviderFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory deleted file mode 100755 index be93efd263f..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.UserProviderFactory +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.models.mongo.keycloak.adapters.MongoUserProviderFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.dblock.DBLockProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.dblock.DBLockProviderFactory deleted file mode 100644 index 4c6c4aa4c88..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.dblock.DBLockProviderFactory +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.connections.mongo.lock.MongoDBLockProviderFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.session.UserSessionPersisterProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.session.UserSessionPersisterProviderFactory deleted file mode 100644 index ca6ef8e48ac..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.models.session.UserSessionPersisterProviderFactory +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.models.mongo.keycloak.adapters.MongoUserSessionPersisterProviderFactory \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.provider.Spi b/model/mongo/src/main/resources/META-INF/services/org.keycloak.provider.Spi deleted file mode 100644 index 0f37157b55c..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.provider.Spi +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright 2016 Red Hat, Inc. and/or its affiliates -# and other contributors as indicated by the @author tags. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -org.keycloak.connections.mongo.MongoConnectionSpi -org.keycloak.connections.mongo.updater.MongoUpdaterSpi \ No newline at end of file diff --git a/model/mongo/src/main/resources/META-INF/services/org.keycloak.storage.federated.UserFederatedStorageProviderFactory b/model/mongo/src/main/resources/META-INF/services/org.keycloak.storage.federated.UserFederatedStorageProviderFactory deleted file mode 100644 index c6afa25d35a..00000000000 --- a/model/mongo/src/main/resources/META-INF/services/org.keycloak.storage.federated.UserFederatedStorageProviderFactory +++ /dev/null @@ -1 +0,0 @@ -org.keycloak.storage.mongo.MongoUserFederatedStorageProviderFactory \ No newline at end of file diff --git a/model/pom.xml b/model/pom.xml index 3c611c349bc..cb0186a4095 100755 --- a/model/pom.xml +++ b/model/pom.xml @@ -43,7 +43,6 @@ jpa - mongo infinispan diff --git a/pom.xml b/pom.xml index 6cc7aac897a..5e3d305dae7 100755 --- a/pom.xml +++ b/pom.xml @@ -90,7 +90,6 @@ 2.3.23 9.1.0.v20131115 3.4.1 - 3.2.0 5.1.29 4.2.0 4.2.4 @@ -111,7 +110,6 @@ 3.1.7 - 0.1.12 1.4 1.3.5 7.5.Final @@ -486,11 +484,6 @@ ${selenium.version} test - - org.mongodb - mongo-java-driver - ${mongo.driver.version} - org.apache.jmeter ApacheJMeter_java @@ -948,11 +941,6 @@ keycloak-model-jpa ${project.version} - - org.keycloak - keycloak-model-mongo - ${project.version} - org.keycloak keycloak-model-infinispan @@ -1395,11 +1383,6 @@ jmeter-analysis-maven-plugin ${jmeter.analysis.plugin.version} - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - ${embedmongo.plugin.version} - org.jboss.as.plugins jboss-as-maven-plugin diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json b/testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json index deb5b64deef..a29ce6e2c16 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/META-INF/keycloak-server.json @@ -98,16 +98,6 @@ } }, - "connectionsMongo": { - "default": { - "host": "${keycloak.connectionsMongo.host:127.0.0.1}", - "port": "${keycloak.connectionsMongo.port:27017}", - "db": "${keycloak.connectionsMongo.db:keycloak}", - "databaseSchema": "${keycloak.connectionsMongo.databaseSchema:update}", - "connectionsPerHost": "${keycloak.connectionsMongo.connectionsPerHost:100}" - } - }, - "realmCache": { "provider": "${keycloak.realm.cache.provider:default}", "default" : { diff --git a/testsuite/integration-arquillian/tests/base/src/test/resources/log4j.properties b/testsuite/integration-arquillian/tests/base/src/test/resources/log4j.properties index d661c6ac7e0..74eefa0b876 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/resources/log4j.properties +++ b/testsuite/integration-arquillian/tests/base/src/test/resources/log4j.properties @@ -49,7 +49,6 @@ log4j.logger.org.keycloak.connections.jpa.updater.liquibase=${keycloak.liquibase log4j.logger.org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory=debug # Enable to view database updates -# log4j.logger.org.keycloak.connections.mongo.updater.DefaultMongoUpdaterProvider=debug # log4j.logger.org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory=debug # log4j.logger.org.keycloak.migration.MigrationModelManager=debug diff --git a/testsuite/integration-arquillian/tests/other/jpa-performance/src/test/resources/log4j.properties b/testsuite/integration-arquillian/tests/other/jpa-performance/src/test/resources/log4j.properties index 979584600b6..e6e934c76d8 100644 --- a/testsuite/integration-arquillian/tests/other/jpa-performance/src/test/resources/log4j.properties +++ b/testsuite/integration-arquillian/tests/other/jpa-performance/src/test/resources/log4j.properties @@ -44,7 +44,6 @@ log4j.logger.org.keycloak.connections.jpa.updater.liquibase=${keycloak.liquibase log4j.logger.org.keycloak.connections.jpa=debug # Enable to view database updates -# log4j.logger.org.keycloak.connections.mongo.updater.DefaultMongoUpdaterProvider=debug # log4j.logger.org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory=debug # log4j.logger.org.keycloak.migration.MigrationModelManager=debug diff --git a/testsuite/integration/pom.xml b/testsuite/integration/pom.xml index 8ed47d47cac..04faa7c244c 100755 --- a/testsuite/integration/pom.xml +++ b/testsuite/integration/pom.xml @@ -434,131 +434,6 @@ - - mongo - - - localhost - 27018 - keycloak - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - - - mongodb-server - - - localhost - 27018 - keycloak - 127.0.0.1 - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - clean-jpa diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/ldap/LDAPBinaryAttributesTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/ldap/LDAPBinaryAttributesTest.java index fb93cc04feb..66924d173c7 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/ldap/LDAPBinaryAttributesTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/ldap/LDAPBinaryAttributesTest.java @@ -203,14 +203,10 @@ public class LDAPBinaryAttributesTest { joe.getAttributes().put("someOtherPhoto", Arrays.asList(JPEG_PHOTO_BASE64)); adminClient.realm("test").users().get(joe.getId()).update(joe); - // TODO: Workaround as on Mongo it is not limit for length of attribute. Should be removed/improved... KeycloakSession session = keycloakRule.startSession(); String realmProviderId = session.getKeycloakSessionFactory().getProviderFactory(RealmProvider.class).getId(); keycloakRule.stopSession(session, false); - if (!realmProviderId.equals("mongo")) { - Assert.fail("Not expected to successfully update user"); - } - + Assert.fail("Not expected to successfully update user"); } catch (ClientErrorException cee) { // Expected } diff --git a/testsuite/integration/src/test/resources/META-INF/keycloak-server.json b/testsuite/integration/src/test/resources/META-INF/keycloak-server.json index 40a15e98e6d..c463347de93 100755 --- a/testsuite/integration/src/test/resources/META-INF/keycloak-server.json +++ b/testsuite/integration/src/test/resources/META-INF/keycloak-server.json @@ -77,16 +77,6 @@ } }, - "connectionsMongo": { - "default": { - "host": "${keycloak.connectionsMongo.host:127.0.0.1}", - "port": "${keycloak.connectionsMongo.port:27017}", - "db": "${keycloak.connectionsMongo.db:keycloak}", - "databaseSchema": "${keycloak.connectionsMongo.databaseSchema:update}", - "connectionsPerHost": "${keycloak.connectionsMongo.connectionsPerHost:100}" - } - }, - "realmCache": { "default" : { "enabled": true diff --git a/testsuite/integration/src/test/resources/log4j.properties b/testsuite/integration/src/test/resources/log4j.properties index 4cc1f91c420..cac26aebae9 100755 --- a/testsuite/integration/src/test/resources/log4j.properties +++ b/testsuite/integration/src/test/resources/log4j.properties @@ -50,7 +50,6 @@ log4j.logger.org.keycloak.connections.jpa.updater.liquibase=${keycloak.liquibase #log4j.logger.org.keycloak.models.cache.infinispan=debug # Enable to view database updates -# log4j.logger.org.keycloak.connections.mongo.updater.DefaultMongoUpdaterProvider=debug log4j.logger.org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory=${keycloak.liquibase.logging.level} # log4j.logger.org.keycloak.migration.MigrationModelManager=debug diff --git a/testsuite/jetty/jetty81/pom.xml b/testsuite/jetty/jetty81/pom.xml index 81a43595875..edd788b331b 100755 --- a/testsuite/jetty/jetty81/pom.xml +++ b/testsuite/jetty/jetty81/pom.xml @@ -350,85 +350,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/jetty/jetty91/pom.xml b/testsuite/jetty/jetty91/pom.xml index 0bbaa29b6e7..4e0c49b3aea 100755 --- a/testsuite/jetty/jetty91/pom.xml +++ b/testsuite/jetty/jetty91/pom.xml @@ -350,85 +350,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/jetty/jetty92/pom.xml b/testsuite/jetty/jetty92/pom.xml index da7f50c5e2d..040661b8406 100755 --- a/testsuite/jetty/jetty92/pom.xml +++ b/testsuite/jetty/jetty92/pom.xml @@ -357,85 +357,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/jetty/jetty93/pom.xml b/testsuite/jetty/jetty93/pom.xml index 154094b0cd8..49e306eb72d 100644 --- a/testsuite/jetty/jetty93/pom.xml +++ b/testsuite/jetty/jetty93/pom.xml @@ -357,85 +357,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/proxy/pom.xml b/testsuite/proxy/pom.xml index 15fd6c969dc..3c796c258b4 100755 --- a/testsuite/proxy/pom.xml +++ b/testsuite/proxy/pom.xml @@ -330,85 +330,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/tomcat6/pom.xml b/testsuite/tomcat6/pom.xml index c61e82f1a76..c73a8412077 100755 --- a/testsuite/tomcat6/pom.xml +++ b/testsuite/tomcat6/pom.xml @@ -336,85 +336,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/tomcat7/pom.xml b/testsuite/tomcat7/pom.xml index e3d9dd4ca0f..8ef09e15c60 100755 --- a/testsuite/tomcat7/pom.xml +++ b/testsuite/tomcat7/pom.xml @@ -350,85 +350,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/testsuite/tomcat8/pom.xml b/testsuite/tomcat8/pom.xml index 7507e2d3e24..66799a858c0 100755 --- a/testsuite/tomcat8/pom.xml +++ b/testsuite/tomcat8/pom.xml @@ -343,85 +343,6 @@ - - mongo - - - localhost - 27018 - keycloak - true - 127.0.0.1 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - test - integration-test - - test - - - - mongo - mongo - mongo - ${keycloak.connectionsMongo.host} - ${keycloak.connectionsMongo.port} - ${keycloak.connectionsMongo.db} - ${keycloak.connectionsMongo.clearOnStartup} - ${keycloak.connectionsMongo.bindIp} - - - - - default-test - - true - - - - - - - - com.github.joelittlejohn.embedmongo - embedmongo-maven-plugin - - - start-mongodb - pre-integration-test - - start - - - ${keycloak.connectionsMongo.port} - file - ${project.build.directory}/mongodb.log - ${keycloak.connectionsMongo.bindIp} - - - - stop-mongodb - post-integration-test - - stop - - - - - - - - - diff --git a/wildfly/server-subsystem/src/main/config/default-server-subsys-config.properties b/wildfly/server-subsystem/src/main/config/default-server-subsys-config.properties index fab6bdb8217..51e6db9d946 100644 --- a/wildfly/server-subsystem/src/main/config/default-server-subsys-config.properties +++ b/wildfly/server-subsystem/src/main/config/default-server-subsys-config.properties @@ -17,31 +17,15 @@ keycloak.server.subsys.default.config=\ ${jboss.home.dir}/themes\ \ \ - jpa\ \ \ \ \ \ \ - \ - jpa\ - \ - \ - jpa\ - \ - \ - jpa\ - \ \ \ \ - \ - jpa\ - \ - \ - jpa\ - \ \ basic\ \ diff --git a/wildfly/server-subsystem/src/main/resources/cli/default-keycloak-subsys-config.cli b/wildfly/server-subsystem/src/main/resources/cli/default-keycloak-subsys-config.cli index 41473988903..8332bb9d7ce 100644 --- a/wildfly/server-subsystem/src/main/resources/cli/default-keycloak-subsys-config.cli +++ b/wildfly/server-subsystem/src/main/resources/cli/default-keycloak-subsys-config.cli @@ -1,13 +1,9 @@ /subsystem=keycloak-server:add(web-context=auth,master-realm-name=master,scheduled-task-interval=900,providers=[classpath:${jboss.home.dir}/providers/*]) /subsystem=keycloak-server/theme=defaults/:add(dir=${jboss.home.dir}/themes,staticMaxAge=2592000,cacheTemplates=true,cacheThemes=true) -/subsystem=keycloak-server/spi=eventsStore/:add(default-provider=jpa) +/subsystem=keycloak-server/spi=eventsStore/:add /subsystem=keycloak-server/spi=eventsStore/provider=jpa/:add(properties={exclude-events => "[\"REFRESH_TOKEN\"]"},enabled=true) -/subsystem=keycloak-server/spi=realm/:add(default-provider=jpa) -/subsystem=keycloak-server/spi=user/:add(default-provider=jpa) /subsystem=keycloak-server/spi=userCache/:add /subsystem=keycloak-server/spi=userCache/provider=default/:add(enabled=true) -/subsystem=keycloak-server/spi=userSessionPersister/:add(default-provider=jpa) -/subsystem=keycloak-server/spi=authorizationPersister/:add(default-provider=jpa) /subsystem=keycloak-server/spi=timer/:add(default-provider=basic) /subsystem=keycloak-server/spi=connectionsHttpClient/:add /subsystem=keycloak-server/spi=connectionsHttpClient/provider=default/:add(enabled=true)