From 8ea0d19d2f144752dd3a33f0e3d1d7fb1b5c3d98 Mon Sep 17 00:00:00 2001 From: Bill Burke Date: Wed, 30 Jul 2014 16:01:54 -0400 Subject: [PATCH] federation refactor --- .../main/resources/META-INF/persistence.xml | 2 +- .../UserFederationProviderRepresentation.java | 9 + .../java/org/keycloak/models/RealmModel.java | 2 + .../models/UserFederationProviderModel.java | 11 +- .../keycloak/models/entities/RealmEntity.java | 10 +- ...java => UserFederationProviderEntity.java} | 14 +- .../models/utils/RepresentationToModel.java | 1404 ++++++++--------- .../keycloak/models/cache/RealmAdapter.java | 15 +- .../models/cache/entities/CachedRealm.java | 8 +- .../org/keycloak/models/jpa/RealmAdapter.java | 119 +- .../models/jpa/entities/RealmEntity.java | 10 +- ...java => UserFederationProviderEntity.java} | 6 +- .../mongo/keycloak/adapters/RealmAdapter.java | 62 +- model/picketlink/pom.xml | 82 - .../models/picketlink/ApplicationAdapter.java | 313 ---- .../models/picketlink/OAuthClientAdapter.java | 34 - .../picketlink/PicketlinkKeycloakSession.java | 119 -- .../PicketlinkKeycloakSessionFactory.java | 31 - .../PicketlinkKeycloakTransaction.java | 41 - .../picketlink/PicketlinkModelProvider.java | 82 - .../models/picketlink/RealmAdapter.java | 1046 ------------ .../models/picketlink/RoleAdapter.java | 60 - .../models/picketlink/UserAdapter.java | 249 --- .../picketlink/mappings/ApplicationData.java | 89 -- .../mappings/ApplicationEntity.java | 101 -- .../models/picketlink/mappings/RealmData.java | 208 --- .../picketlink/mappings/RealmEntity.java | 204 --- .../ApplicationRelationship.java | 41 - .../OAuthClientRelationship.java | 57 - ...hClientRequiredCredentialRelationship.java | 8 - .../relationships/RealmAdminRelationship.java | 45 - .../RealmListingRelationship.java | 26 - ...iredApplicationCredentialRelationship.java | 8 - .../RequiredCredentialRelationship.java | 81 - .../relationships/ScopeRelationship.java | 51 - .../relationships/SocialLinkRelationship.java | 73 - .../org.keycloak.models.ModelProvider | 1 - .../FederationProvidersIntegrationTest.java | 3 +- 38 files changed, 903 insertions(+), 3822 deletions(-) rename model/api/src/main/java/org/keycloak/models/entities/{FederationProviderEntity.java => UserFederationProviderEntity.java} (68%) rename model/jpa/src/main/java/org/keycloak/models/jpa/entities/{FederationProviderEntity.java => UserFederationProviderEntity.java} (93%) delete mode 100755 model/picketlink/pom.xml delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/ApplicationAdapter.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/OAuthClientAdapter.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSession.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSessionFactory.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakTransaction.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkModelProvider.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/RealmAdapter.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/RoleAdapter.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/UserAdapter.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationData.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationEntity.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmData.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmEntity.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ApplicationRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRequiredCredentialRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmAdminRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmListingRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredApplicationCredentialRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredCredentialRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ScopeRelationship.java delete mode 100755 model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/SocialLinkRelationship.java delete mode 100644 model/picketlink/src/main/resources/META-INF/services/org.keycloak.models.ModelProvider diff --git a/connections/jpa/src/main/resources/META-INF/persistence.xml b/connections/jpa/src/main/resources/META-INF/persistence.xml index 2463c4ca36..e2c80de350 100755 --- a/connections/jpa/src/main/resources/META-INF/persistence.xml +++ b/connections/jpa/src/main/resources/META-INF/persistence.xml @@ -9,7 +9,7 @@ org.keycloak.models.jpa.entities.RealmEntity org.keycloak.models.jpa.entities.RequiredCredentialEntity org.keycloak.models.jpa.entities.AuthenticationProviderEntity - org.keycloak.models.jpa.entities.FederationProviderEntity + org.keycloak.models.jpa.entities.UserFederationProviderEntity org.keycloak.models.jpa.entities.RoleEntity org.keycloak.models.jpa.entities.SocialLinkEntity org.keycloak.models.jpa.entities.AuthenticationLinkEntity diff --git a/core/src/main/java/org/keycloak/representations/idm/UserFederationProviderRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/UserFederationProviderRepresentation.java index 90efd175ce..76541f9810 100755 --- a/core/src/main/java/org/keycloak/representations/idm/UserFederationProviderRepresentation.java +++ b/core/src/main/java/org/keycloak/representations/idm/UserFederationProviderRepresentation.java @@ -10,6 +10,7 @@ public class UserFederationProviderRepresentation { private String id; private String providerName; private Map config; + private int priority; public String getId() { return id; @@ -36,6 +37,14 @@ public class UserFederationProviderRepresentation { this.config = config; } + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/model/api/src/main/java/org/keycloak/models/RealmModel.java b/model/api/src/main/java/org/keycloak/models/RealmModel.java index 1884dec9f2..cc3a9b6f5c 100755 --- a/model/api/src/main/java/org/keycloak/models/RealmModel.java +++ b/model/api/src/main/java/org/keycloak/models/RealmModel.java @@ -167,6 +167,8 @@ public interface RealmModel extends RoleContainerModel { List getUserFederationProviders(); + UserFederationProviderModel addUserFederationProvider(String providerName, Map config, int priority); + void removeUserFederationProvider(UserFederationProviderModel provider); void setUserFederationProviders(List providers); String getLoginTheme(); diff --git a/model/api/src/main/java/org/keycloak/models/UserFederationProviderModel.java b/model/api/src/main/java/org/keycloak/models/UserFederationProviderModel.java index 35fd727aa6..a682c5499d 100755 --- a/model/api/src/main/java/org/keycloak/models/UserFederationProviderModel.java +++ b/model/api/src/main/java/org/keycloak/models/UserFederationProviderModel.java @@ -12,10 +12,11 @@ public class UserFederationProviderModel { private String id; private String providerName; private Map config = new HashMap(); + private int priority; public UserFederationProviderModel() {}; - public UserFederationProviderModel(String id, String providerName, Map config) { + public UserFederationProviderModel(String id, String providerName, Map config, int priority) { this.id = id; this.providerName = providerName; if (config != null) { @@ -42,4 +43,12 @@ public class UserFederationProviderModel { public void setConfig(Map config) { this.config = config; } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } } diff --git a/model/api/src/main/java/org/keycloak/models/entities/RealmEntity.java b/model/api/src/main/java/org/keycloak/models/entities/RealmEntity.java index 061cfe42a0..16907575d7 100755 --- a/model/api/src/main/java/org/keycloak/models/entities/RealmEntity.java +++ b/model/api/src/main/java/org/keycloak/models/entities/RealmEntity.java @@ -51,7 +51,7 @@ public class RealmEntity extends AbstractIdentifiableEntity { private List requiredCredentials = new ArrayList(); private List authenticationProviders = new ArrayList(); - private List federationProviders = new ArrayList(); + private List userFederationProviders = new ArrayList(); private Map smtpConfig = new HashMap(); private Map socialConfig = new HashMap(); @@ -383,11 +383,11 @@ public class RealmEntity extends AbstractIdentifiableEntity { this.adminAppId = adminAppId; } - public List getFederationProviders() { - return federationProviders; + public List getUserFederationProviders() { + return userFederationProviders; } - public void setFederationProviders(List federationProviders) { - this.federationProviders = federationProviders; + public void setUserFederationProviders(List userFederationProviders) { + this.userFederationProviders = userFederationProviders; } } diff --git a/model/api/src/main/java/org/keycloak/models/entities/FederationProviderEntity.java b/model/api/src/main/java/org/keycloak/models/entities/UserFederationProviderEntity.java similarity index 68% rename from model/api/src/main/java/org/keycloak/models/entities/FederationProviderEntity.java rename to model/api/src/main/java/org/keycloak/models/entities/UserFederationProviderEntity.java index 0330acc9e8..5e39d9dbb6 100755 --- a/model/api/src/main/java/org/keycloak/models/entities/FederationProviderEntity.java +++ b/model/api/src/main/java/org/keycloak/models/entities/UserFederationProviderEntity.java @@ -6,10 +6,12 @@ import java.util.Map; * @author Bill Burke * @version $Revision: 1 $ */ -public class FederationProviderEntity { +public class UserFederationProviderEntity { protected String id; protected String providerName; - private Map config; + protected Map config; + protected int priority; + public String getId() { return id; @@ -34,4 +36,12 @@ public class FederationProviderEntity { public void setConfig(Map config) { this.config = config; } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } } diff --git a/model/api/src/main/java/org/keycloak/models/utils/RepresentationToModel.java b/model/api/src/main/java/org/keycloak/models/utils/RepresentationToModel.java index 6b3ec2dca1..06c66307bd 100755 --- a/model/api/src/main/java/org/keycloak/models/utils/RepresentationToModel.java +++ b/model/api/src/main/java/org/keycloak/models/utils/RepresentationToModel.java @@ -1,702 +1,702 @@ -package org.keycloak.models.utils; - -import net.iharder.Base64; -import org.jboss.logging.Logger; -import org.keycloak.models.ApplicationModel; -import org.keycloak.models.AuthenticationLinkModel; -import org.keycloak.models.AuthenticationProviderModel; -import org.keycloak.models.ClaimMask; -import org.keycloak.models.ClientModel; -import org.keycloak.models.UserFederationProviderModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.OAuthClientModel; -import org.keycloak.models.PasswordPolicy; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.SocialLinkModel; -import org.keycloak.models.UserCredentialModel; -import org.keycloak.models.UserCredentialValueModel; -import org.keycloak.models.UserModel; -import org.keycloak.representations.idm.UserFederationProviderRepresentation; -import org.keycloak.representations.idm.ApplicationRepresentation; -import org.keycloak.representations.idm.AuthenticationLinkRepresentation; -import org.keycloak.representations.idm.AuthenticationProviderRepresentation; -import org.keycloak.representations.idm.ClaimRepresentation; -import org.keycloak.representations.idm.CredentialRepresentation; -import org.keycloak.representations.idm.OAuthClientRepresentation; -import org.keycloak.representations.idm.RealmRepresentation; -import org.keycloak.representations.idm.RoleRepresentation; -import org.keycloak.representations.idm.ScopeMappingRepresentation; -import org.keycloak.representations.idm.SocialLinkRepresentation; -import org.keycloak.representations.idm.UserRepresentation; - -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class RepresentationToModel { - - private static Logger logger = Logger.getLogger(RepresentationToModel.class); - - public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) { - newRealm.setName(rep.getRealm()); - if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled()); - if (rep.isSocial() != null) newRealm.setSocial(rep.isSocial()); - if (rep.isBruteForceProtected() != null) newRealm.setBruteForceProtected(rep.isBruteForceProtected()); - if (rep.getMaxFailureWaitSeconds() != null) newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); - if (rep.getMinimumQuickLoginWaitSeconds() != null) newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); - if (rep.getWaitIncrementSeconds() != null) newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); - if (rep.getQuickLoginCheckMilliSeconds() != null) newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); - if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); - if (rep.getFailureFactor() != null) newRealm.setFailureFactor(rep.getFailureFactor()); - - if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore()); - - if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); - else newRealm.setAccessTokenLifespan(300); - - if (rep.getSsoSessionIdleTimeout() != null) newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); - else newRealm.setSsoSessionIdleTimeout(600); - if (rep.getSsoSessionMaxLifespan() != null) newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan()); - else newRealm.setSsoSessionMaxLifespan(36000); - - if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); - else newRealm.setAccessCodeLifespan(60); - - if (rep.getAccessCodeLifespanUserAction() != null) - newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); - else newRealm.setAccessCodeLifespanUserAction(300); - - if (rep.isSslNotRequired() != null) newRealm.setSslNotRequired(rep.isSslNotRequired()); - if (rep.isPasswordCredentialGrantAllowed() != null) newRealm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); - if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); - if (rep.isRememberMe() != null) newRealm.setRememberMe(rep.isRememberMe()); - if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail()); - if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); - if (rep.isUpdateProfileOnInitialSocialLogin() != null) - newRealm.setUpdateProfileOnInitialSocialLogin(rep.isUpdateProfileOnInitialSocialLogin()); - if (rep.getPrivateKey() == null || rep.getPublicKey() == null) { - KeycloakModelUtils.generateRealmKeys(newRealm); - } else { - newRealm.setPrivateKeyPem(rep.getPrivateKey()); - newRealm.setPublicKeyPem(rep.getPublicKey()); - } - if (rep.getLoginTheme() != null) newRealm.setLoginTheme(rep.getLoginTheme()); - if (rep.getAccountTheme() != null) newRealm.setAccountTheme(rep.getAccountTheme()); - if (rep.getAdminTheme() != null) newRealm.setAdminTheme(rep.getAdminTheme()); - if (rep.getEmailTheme() != null) newRealm.setEmailTheme(rep.getEmailTheme()); - - if (rep.getRequiredCredentials() != null) { - for (String requiredCred : rep.getRequiredCredentials()) { - addRequiredCredential(newRealm, requiredCred); - } - } else { - addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); - } - - if (rep.getPasswordPolicy() != null) newRealm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy())); - - if (rep.getApplications() != null) { - Map appMap = createApplications(rep, newRealm); - } - - if (rep.getRoles() != null) { - if (rep.getRoles().getRealm() != null) { // realm roles - for (RoleRepresentation roleRep : rep.getRoles().getRealm()) { - createRole(newRealm, roleRep); - } - } - if (rep.getRoles().getApplication() != null) { - for (Map.Entry> entry : rep.getRoles().getApplication().entrySet()) { - ApplicationModel app = newRealm.getApplicationByName(entry.getKey()); - if (app == null) { - throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey()); - } - for (RoleRepresentation roleRep : entry.getValue()) { - // Application role may already exists (for example if it is defaultRole) - RoleModel role = roleRep.getId()!=null ? app.addRole(roleRep.getId(), roleRep.getName()) : app.addRole(roleRep.getName()); - role.setDescription(roleRep.getDescription()); - } - } - } - // now that all roles are created, re-iterate and set up composites - if (rep.getRoles().getRealm() != null) { // realm roles - for (RoleRepresentation roleRep : rep.getRoles().getRealm()) { - RoleModel role = newRealm.getRole(roleRep.getName()); - addComposites(role, roleRep, newRealm); - } - } - if (rep.getRoles().getApplication() != null) { - for (Map.Entry> entry : rep.getRoles().getApplication().entrySet()) { - ApplicationModel app = newRealm.getApplicationByName(entry.getKey()); - if (app == null) { - throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey()); - } - for (RoleRepresentation roleRep : entry.getValue()) { - RoleModel role = app.getRole(roleRep.getName()); - addComposites(role, roleRep, newRealm); - } - } - } - } - - // Setup realm default roles - if (rep.getDefaultRoles() != null) { - for (String roleString : rep.getDefaultRoles()) { - newRealm.addDefaultRole(roleString.trim()); - } - } - // Setup application default roles - if (rep.getApplications() != null) { - for (ApplicationRepresentation resourceRep : rep.getApplications()) { - if (resourceRep.getDefaultRoles() != null) { - ApplicationModel appModel = newRealm.getApplicationByName(resourceRep.getName()); - appModel.updateDefaultRoles(resourceRep.getDefaultRoles()); - } - } - } - - if (rep.getOauthClients() != null) { - createOAuthClients(rep, newRealm); - } - - - // Now that all possible roles and applications are created, create scope mappings - - Map appMap = newRealm.getApplicationNameMap(); - - if (rep.getApplicationScopeMappings() != null) { - - for (Map.Entry> entry : rep.getApplicationScopeMappings().entrySet()) { - ApplicationModel app = appMap.get(entry.getKey()); - if (app == null) { - throw new RuntimeException("Unable to find application role mappings for app: " + entry.getKey()); - } - createApplicationScopeMappings(newRealm, app, entry.getValue()); - } - } - - if (rep.getScopeMappings() != null) { - for (ScopeMappingRepresentation scope : rep.getScopeMappings()) { - ClientModel client = newRealm.findClient(scope.getClient()); - for (String roleString : scope.getRoles()) { - RoleModel role = newRealm.getRole(roleString.trim()); - if (role == null) { - role = newRealm.addRole(roleString.trim()); - } - client.addScopeMapping(role); - } - - } - } - - if (rep.getSmtpServer() != null) { - newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer())); - } - - if (rep.getSocialProviders() != null) { - newRealm.setSocialConfig(new HashMap(rep.getSocialProviders())); - } - if (rep.getLdapServer() != null) { - newRealm.setLdapServerConfig(new HashMap(rep.getLdapServer())); - } - - if (rep.getAuthenticationProviders() != null) { - List authProviderModels = convertAuthenticationProviders(rep.getAuthenticationProviders()); - newRealm.setAuthenticationProviders(authProviderModels); - } else { - List authProviderModels = Arrays.asList(AuthenticationProviderModel.DEFAULT_PROVIDER); - newRealm.setAuthenticationProviders(authProviderModels); - } - - if (rep.getUserFederationProviders() != null) { - List providerModels = convertFederationProviders(rep.getUserFederationProviders()); - newRealm.setUserFederationProviders(providerModels); - } - - // create users and their role mappings and social mappings - - if (rep.getUsers() != null) { - for (UserRepresentation userRep : rep.getUsers()) { - UserModel user = createUser(session, newRealm, userRep, appMap); - } - } - } - - public static void updateRealm(RealmRepresentation rep, RealmModel realm) { - if (rep.getRealm() != null) { - realm.setName(rep.getRealm()); - } - if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled()); - if (rep.isSocial() != null) realm.setSocial(rep.isSocial()); - if (rep.isBruteForceProtected() != null) realm.setBruteForceProtected(rep.isBruteForceProtected()); - if (rep.getMaxFailureWaitSeconds() != null) realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); - if (rep.getMinimumQuickLoginWaitSeconds() != null) realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); - if (rep.getWaitIncrementSeconds() != null) realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); - if (rep.getQuickLoginCheckMilliSeconds() != null) realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); - if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); - if (rep.getFailureFactor() != null) realm.setFailureFactor(rep.getFailureFactor()); - if (rep.isPasswordCredentialGrantAllowed() != null) realm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); - if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed()); - if (rep.isRememberMe() != null) realm.setRememberMe(rep.isRememberMe()); - if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail()); - if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); - if (rep.isUpdateProfileOnInitialSocialLogin() != null) - realm.setUpdateProfileOnInitialSocialLogin(rep.isUpdateProfileOnInitialSocialLogin()); - if (rep.isSslNotRequired() != null) realm.setSslNotRequired((rep.isSslNotRequired())); - if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); - if (rep.getAccessCodeLifespanUserAction() != null) - realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); - if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore()); - if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); - if (rep.getSsoSessionIdleTimeout() != null) realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); - if (rep.getSsoSessionMaxLifespan() != null) realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan()); - if (rep.getRequiredCredentials() != null) { - realm.updateRequiredCredentials(rep.getRequiredCredentials()); - } - if (rep.getLoginTheme() != null) realm.setLoginTheme(rep.getLoginTheme()); - if (rep.getAccountTheme() != null) realm.setAccountTheme(rep.getAccountTheme()); - if (rep.getAdminTheme() != null) realm.setAdminTheme(rep.getAdminTheme()); - if (rep.getEmailTheme() != null) realm.setEmailTheme(rep.getEmailTheme()); - - if (rep.getPasswordPolicy() != null) realm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy())); - - if (rep.getDefaultRoles() != null) { - realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()])); - } - - if (rep.getSmtpServer() != null) { - realm.setSmtpConfig(new HashMap(rep.getSmtpServer())); - } - - if (rep.getSocialProviders() != null) { - realm.setSocialConfig(new HashMap(rep.getSocialProviders())); - } - - if (rep.getLdapServer() != null) { - realm.setLdapServerConfig(new HashMap(rep.getLdapServer())); - } - if (rep.getAuthenticationProviders() != null) { - List authProviderModels = convertAuthenticationProviders(rep.getAuthenticationProviders()); - realm.setAuthenticationProviders(authProviderModels); - } - - if (rep.getUserFederationProviders() != null) { - List providerModels = convertFederationProviders(rep.getUserFederationProviders()); - realm.setUserFederationProviders(providerModels); - } - - if ("GENERATE".equals(rep.getPublicKey())) { - KeycloakModelUtils.generateRealmKeys(realm); - } - } - - // Basic realm stuff - - public static void addRequiredCredential(RealmModel newRealm, String requiredCred) { - newRealm.addRequiredCredential(requiredCred); - } - - - private static List convertAuthenticationProviders(List authenticationProviders) { - List result = new ArrayList(); - - for (AuthenticationProviderRepresentation representation : authenticationProviders) { - AuthenticationProviderModel model = new AuthenticationProviderModel(representation.getProviderName(), - representation.isPasswordUpdateSupported(), representation.getConfig()); - result.add(model); - } - return result; - } - - private static List convertFederationProviders(List providers) { - List result = new ArrayList(); - - for (UserFederationProviderRepresentation representation : providers) { - UserFederationProviderModel model = new UserFederationProviderModel(representation.getId(), representation.getProviderName(), - representation.getConfig()); - result.add(model); - } - return result; - } - - // Roles - - public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) { - RoleModel role = roleRep.getId()!=null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName()); - if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription()); - } - - private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) { - if (roleRep.getComposites() == null) return; - if (roleRep.getComposites().getRealm() != null) { - for (String roleStr : roleRep.getComposites().getRealm()) { - RoleModel realmRole = realm.getRole(roleStr); - if (realmRole == null) throw new RuntimeException("Unable to find composite realm role: " + roleStr); - role.addCompositeRole(realmRole); - } - } - if (roleRep.getComposites().getApplication() != null) { - for (Map.Entry> entry : roleRep.getComposites().getApplication().entrySet()) { - ApplicationModel app = realm.getApplicationByName(entry.getKey()); - if (app == null) { - throw new RuntimeException("App doesn't exist in role definitions: " + roleRep.getName()); - } - for (String roleStr : entry.getValue()) { - RoleModel appRole = app.getRole(roleStr); - if (appRole == null) throw new RuntimeException("Unable to find composite app role: " + roleStr); - role.addCompositeRole(appRole); - } - - } - - } - - } - - // APPLICATIONS - - private static Map createApplications(RealmRepresentation rep, RealmModel realm) { - Map appMap = new HashMap(); - for (ApplicationRepresentation resourceRep : rep.getApplications()) { - ApplicationModel app = createApplication(realm, resourceRep, false); - appMap.put(app.getName(), app); - } - return appMap; - } - - /** - * Does not create scope or role mappings! - * - * @param realm - * @param resourceRep - * @return - */ - public static ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep, boolean addDefaultRoles) { - logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName()); - ApplicationModel applicationModel = resourceRep.getId()!=null ? realm.addApplication(resourceRep.getId(), resourceRep.getName()) : realm.addApplication(resourceRep.getName()); - if (resourceRep.isEnabled() != null) applicationModel.setEnabled(resourceRep.isEnabled()); - applicationModel.setManagementUrl(resourceRep.getAdminUrl()); - if (resourceRep.isSurrogateAuthRequired() != null) - applicationModel.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired()); - applicationModel.setBaseUrl(resourceRep.getBaseUrl()); - if (resourceRep.isBearerOnly() != null) applicationModel.setBearerOnly(resourceRep.isBearerOnly()); - if (resourceRep.isPublicClient() != null) applicationModel.setPublicClient(resourceRep.isPublicClient()); - applicationModel.updateApplication(); - - if (resourceRep.getNotBefore() != null) { - applicationModel.setNotBefore(resourceRep.getNotBefore()); - } - - applicationModel.setSecret(resourceRep.getSecret()); - if (applicationModel.getSecret() == null) { - KeycloakModelUtils.generateSecret(applicationModel); - } - - - if (resourceRep.getRedirectUris() != null) { - for (String redirectUri : resourceRep.getRedirectUris()) { - applicationModel.addRedirectUri(redirectUri); - } - } - if (resourceRep.getWebOrigins() != null) { - for (String webOrigin : resourceRep.getWebOrigins()) { - logger.debugv("Application: {0} webOrigin: {1}", resourceRep.getName(), webOrigin); - applicationModel.addWebOrigin(webOrigin); - } - } else { - // add origins from redirect uris - if (resourceRep.getRedirectUris() != null) { - Set origins = new HashSet(); - for (String redirectUri : resourceRep.getRedirectUris()) { - logger.info("add redirectUri to origin: " + redirectUri); - if (redirectUri.startsWith("http:")) { - URI uri = URI.create(redirectUri); - String origin = uri.getScheme() + "://" + uri.getHost(); - if (uri.getPort() != -1) { - origin += ":" + uri.getPort(); - } - logger.debugv("adding default application origin: {0}" , origin); - origins.add(origin); - } - } - if (origins.size() > 0) { - applicationModel.setWebOrigins(origins); - } - } - } - - if (addDefaultRoles && resourceRep.getDefaultRoles() != null) { - applicationModel.updateDefaultRoles(resourceRep.getDefaultRoles()); - } - - if (resourceRep.getClaims() != null) { - setClaims(applicationModel, resourceRep.getClaims()); - } else { - applicationModel.setAllowedClaimsMask(ClaimMask.USERNAME); - } - - return applicationModel; - } - - public static void updateApplication(ApplicationRepresentation rep, ApplicationModel resource) { - if (rep.getName() != null) resource.setName(rep.getName()); - if (rep.isEnabled() != null) resource.setEnabled(rep.isEnabled()); - if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly()); - if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient()); - if (rep.getAdminUrl() != null) resource.setManagementUrl(rep.getAdminUrl()); - if (rep.getBaseUrl() != null) resource.setBaseUrl(rep.getBaseUrl()); - if (rep.isSurrogateAuthRequired() != null) resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired()); - resource.updateApplication(); - - if (rep.getNotBefore() != null) { - resource.setNotBefore(rep.getNotBefore()); - } - if (rep.getDefaultRoles() != null) { - resource.updateDefaultRoles(rep.getDefaultRoles()); - } - - List redirectUris = rep.getRedirectUris(); - if (redirectUris != null) { - resource.setRedirectUris(new HashSet(redirectUris)); - } - - List webOrigins = rep.getWebOrigins(); - if (webOrigins != null) { - resource.setWebOrigins(new HashSet(webOrigins)); - } - - if (rep.getClaims() != null) { - setClaims(resource, rep.getClaims()); - } - } - - public static void setClaims(ClientModel model, ClaimRepresentation rep) { - long mask = model.getAllowedClaimsMask(); - if (rep.getAddress()) { - mask |= ClaimMask.ADDRESS; - } else { - mask &= ~ClaimMask.ADDRESS; - } - if (rep.getEmail()) { - mask |= ClaimMask.EMAIL; - } else { - mask &= ~ClaimMask.EMAIL; - } - if (rep.getGender()) { - mask |= ClaimMask.GENDER; - } else { - mask &= ~ClaimMask.GENDER; - } - if (rep.getLocale()) { - mask |= ClaimMask.LOCALE; - } else { - mask &= ~ClaimMask.LOCALE; - } - if (rep.getName()) { - mask |= ClaimMask.NAME; - } else { - mask &= ~ClaimMask.NAME; - } - if (rep.getPhone()) { - mask |= ClaimMask.PHONE; - } else { - mask &= ~ClaimMask.PHONE; - } - if (rep.getPicture()) { - mask |= ClaimMask.PICTURE; - } else { - mask &= ~ClaimMask.PICTURE; - } - if (rep.getProfile()) { - mask |= ClaimMask.PROFILE; - } else { - mask &= ~ClaimMask.PROFILE; - } - if (rep.getUsername()) { - mask |= ClaimMask.USERNAME; - } else { - mask &= ~ClaimMask.USERNAME; - } - if (rep.getWebsite()) { - mask |= ClaimMask.WEBSITE; - } else { - mask &= ~ClaimMask.WEBSITE; - } - model.setAllowedClaimsMask(mask); - } - - // OAuth clients - - private static void createOAuthClients(RealmRepresentation realmRep, RealmModel realm) { - for (OAuthClientRepresentation rep : realmRep.getOauthClients()) { - createOAuthClient(rep, realm); - } - } - - public static OAuthClientModel createOAuthClient(String id, String name, RealmModel realm) { - OAuthClientModel model = id!=null ? realm.addOAuthClient(id, name) : realm.addOAuthClient(name); - KeycloakModelUtils.generateSecret(model); - return model; - } - - public static OAuthClientModel createOAuthClient(OAuthClientRepresentation rep, RealmModel realm) { - OAuthClientModel model = createOAuthClient(rep.getId(), rep.getName(), realm); - updateOAuthClient(rep, model); - return model; - } - - public static void updateOAuthClient(OAuthClientRepresentation rep, OAuthClientModel model) { - if (rep.getName() != null) model.setClientId(rep.getName()); - if (rep.isEnabled() != null) model.setEnabled(rep.isEnabled()); - if (rep.isPublicClient() != null) model.setPublicClient(rep.isPublicClient()); - if (rep.isDirectGrantsOnly() != null) model.setDirectGrantsOnly(rep.isDirectGrantsOnly()); - if (rep.getClaims() != null) { - setClaims(model, rep.getClaims()); - } - if (rep.getNotBefore() != null) { - model.setNotBefore(rep.getNotBefore()); - } - if (rep.getSecret() != null) model.setSecret(rep.getSecret()); - List redirectUris = rep.getRedirectUris(); - if (redirectUris != null) { - model.setRedirectUris(new HashSet(redirectUris)); - } - - List webOrigins = rep.getWebOrigins(); - if (webOrigins != null) { - model.setWebOrigins(new HashSet(webOrigins)); - } - - if (rep.getClaims() != null) { - setClaims(model, rep.getClaims()); - } - - if (rep.getNotBefore() != null) { - model.setNotBefore(rep.getNotBefore()); - } - - } - - // Scope mappings - - public static void createApplicationScopeMappings(RealmModel realm, ApplicationModel applicationModel, List mappings) { - for (ScopeMappingRepresentation mapping : mappings) { - ClientModel client = realm.findClient(mapping.getClient()); - for (String roleString : mapping.getRoles()) { - RoleModel role = applicationModel.getRole(roleString.trim()); - if (role == null) { - role = applicationModel.addRole(roleString.trim()); - } - client.addScopeMapping(role); - } - } - } - - // Users - - public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep, Map appMap) { - UserModel user = session.users().addUser(newRealm, userRep.getId(), userRep.getUsername(), false); - user.setEnabled(userRep.isEnabled()); - user.setEmail(userRep.getEmail()); - user.setFirstName(userRep.getFirstName()); - user.setLastName(userRep.getLastName()); - user.setFederationLink(userRep.getFederationLink()); - if (userRep.getAttributes() != null) { - for (Map.Entry entry : userRep.getAttributes().entrySet()) { - user.setAttribute(entry.getKey(), entry.getValue()); - } - } - if (userRep.getRequiredActions() != null) { - for (String requiredAction : userRep.getRequiredActions()) { - user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction)); - } - } - if (userRep.getCredentials() != null) { - for (CredentialRepresentation cred : userRep.getCredentials()) { - updateCredential(user, cred); - } - } - if (userRep.getAuthenticationLink() != null) { - AuthenticationLinkRepresentation link = userRep.getAuthenticationLink(); - AuthenticationLinkModel authLink = new AuthenticationLinkModel(link.getAuthProvider(), link.getAuthUserId()); - user.setAuthenticationLink(authLink); - } - if (userRep.getSocialLinks() != null) { - for (SocialLinkRepresentation socialLink : userRep.getSocialLinks()) { - SocialLinkModel mappingModel = new SocialLinkModel(socialLink.getSocialProvider(), socialLink.getSocialUserId(), socialLink.getSocialUsername()); - session.users().addSocialLink(newRealm, user, mappingModel); - } - } - if (userRep.getRealmRoles() != null) { - for (String roleString : userRep.getRealmRoles()) { - RoleModel role = newRealm.getRole(roleString.trim()); - if (role == null) { - role = newRealm.addRole(roleString.trim()); - } - user.grantRole(role); - } - } - if (userRep.getApplicationRoles() != null) { - for (Map.Entry> entry : userRep.getApplicationRoles().entrySet()) { - ApplicationModel app = appMap.get(entry.getKey()); - if (app == null) { - throw new RuntimeException("Unable to find application role mappings for app: " + entry.getKey()); - } - createApplicationRoleMappings(app, user, entry.getValue()); - } - } - return user; - } - - // Detect if it is "plain-text" or "hashed" representation and update model according to it - private static void updateCredential(UserModel user, CredentialRepresentation cred) { - if (cred.getValue() != null) { - UserCredentialModel plainTextCred = convertCredential(cred); - user.updateCredential(plainTextCred); - } else { - UserCredentialValueModel hashedCred = new UserCredentialValueModel(); - hashedCred.setType(cred.getType()); - hashedCred.setDevice(cred.getDevice()); - hashedCred.setHashIterations(cred.getHashIterations()); - try { - hashedCred.setSalt(Base64.decode(cred.getSalt())); - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } - hashedCred.setValue(cred.getHashedSaltedValue()); - user.updateCredentialDirectly(hashedCred); - } - } - - public static UserCredentialModel convertCredential(CredentialRepresentation cred) { - UserCredentialModel credential = new UserCredentialModel(); - credential.setType(cred.getType()); - credential.setValue(cred.getValue()); - return credential; - } - - // Role mappings - - public static void createApplicationRoleMappings(ApplicationModel applicationModel, UserModel user, List roleNames) { - if (user == null) { - throw new RuntimeException("User not found"); - } - - for (String roleName : roleNames) { - RoleModel role = applicationModel.getRole(roleName.trim()); - if (role == null) { - role = applicationModel.addRole(roleName.trim()); - } - user.grantRole(role); - - } - } - -} +package org.keycloak.models.utils; + +import net.iharder.Base64; +import org.jboss.logging.Logger; +import org.keycloak.models.ApplicationModel; +import org.keycloak.models.AuthenticationLinkModel; +import org.keycloak.models.AuthenticationProviderModel; +import org.keycloak.models.ClaimMask; +import org.keycloak.models.ClientModel; +import org.keycloak.models.UserFederationProviderModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.OAuthClientModel; +import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.SocialLinkModel; +import org.keycloak.models.UserCredentialModel; +import org.keycloak.models.UserCredentialValueModel; +import org.keycloak.models.UserModel; +import org.keycloak.representations.idm.UserFederationProviderRepresentation; +import org.keycloak.representations.idm.ApplicationRepresentation; +import org.keycloak.representations.idm.AuthenticationLinkRepresentation; +import org.keycloak.representations.idm.AuthenticationProviderRepresentation; +import org.keycloak.representations.idm.ClaimRepresentation; +import org.keycloak.representations.idm.CredentialRepresentation; +import org.keycloak.representations.idm.OAuthClientRepresentation; +import org.keycloak.representations.idm.RealmRepresentation; +import org.keycloak.representations.idm.RoleRepresentation; +import org.keycloak.representations.idm.ScopeMappingRepresentation; +import org.keycloak.representations.idm.SocialLinkRepresentation; +import org.keycloak.representations.idm.UserRepresentation; + +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class RepresentationToModel { + + private static Logger logger = Logger.getLogger(RepresentationToModel.class); + + public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) { + newRealm.setName(rep.getRealm()); + if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled()); + if (rep.isSocial() != null) newRealm.setSocial(rep.isSocial()); + if (rep.isBruteForceProtected() != null) newRealm.setBruteForceProtected(rep.isBruteForceProtected()); + if (rep.getMaxFailureWaitSeconds() != null) newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); + if (rep.getMinimumQuickLoginWaitSeconds() != null) newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); + if (rep.getWaitIncrementSeconds() != null) newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); + if (rep.getQuickLoginCheckMilliSeconds() != null) newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); + if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); + if (rep.getFailureFactor() != null) newRealm.setFailureFactor(rep.getFailureFactor()); + + if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore()); + + if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); + else newRealm.setAccessTokenLifespan(300); + + if (rep.getSsoSessionIdleTimeout() != null) newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); + else newRealm.setSsoSessionIdleTimeout(600); + if (rep.getSsoSessionMaxLifespan() != null) newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan()); + else newRealm.setSsoSessionMaxLifespan(36000); + + if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); + else newRealm.setAccessCodeLifespan(60); + + if (rep.getAccessCodeLifespanUserAction() != null) + newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); + else newRealm.setAccessCodeLifespanUserAction(300); + + if (rep.isSslNotRequired() != null) newRealm.setSslNotRequired(rep.isSslNotRequired()); + if (rep.isPasswordCredentialGrantAllowed() != null) newRealm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); + if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); + if (rep.isRememberMe() != null) newRealm.setRememberMe(rep.isRememberMe()); + if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail()); + if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); + if (rep.isUpdateProfileOnInitialSocialLogin() != null) + newRealm.setUpdateProfileOnInitialSocialLogin(rep.isUpdateProfileOnInitialSocialLogin()); + if (rep.getPrivateKey() == null || rep.getPublicKey() == null) { + KeycloakModelUtils.generateRealmKeys(newRealm); + } else { + newRealm.setPrivateKeyPem(rep.getPrivateKey()); + newRealm.setPublicKeyPem(rep.getPublicKey()); + } + if (rep.getLoginTheme() != null) newRealm.setLoginTheme(rep.getLoginTheme()); + if (rep.getAccountTheme() != null) newRealm.setAccountTheme(rep.getAccountTheme()); + if (rep.getAdminTheme() != null) newRealm.setAdminTheme(rep.getAdminTheme()); + if (rep.getEmailTheme() != null) newRealm.setEmailTheme(rep.getEmailTheme()); + + if (rep.getRequiredCredentials() != null) { + for (String requiredCred : rep.getRequiredCredentials()) { + addRequiredCredential(newRealm, requiredCred); + } + } else { + addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); + } + + if (rep.getPasswordPolicy() != null) newRealm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy())); + + if (rep.getApplications() != null) { + Map appMap = createApplications(rep, newRealm); + } + + if (rep.getRoles() != null) { + if (rep.getRoles().getRealm() != null) { // realm roles + for (RoleRepresentation roleRep : rep.getRoles().getRealm()) { + createRole(newRealm, roleRep); + } + } + if (rep.getRoles().getApplication() != null) { + for (Map.Entry> entry : rep.getRoles().getApplication().entrySet()) { + ApplicationModel app = newRealm.getApplicationByName(entry.getKey()); + if (app == null) { + throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey()); + } + for (RoleRepresentation roleRep : entry.getValue()) { + // Application role may already exists (for example if it is defaultRole) + RoleModel role = roleRep.getId()!=null ? app.addRole(roleRep.getId(), roleRep.getName()) : app.addRole(roleRep.getName()); + role.setDescription(roleRep.getDescription()); + } + } + } + // now that all roles are created, re-iterate and set up composites + if (rep.getRoles().getRealm() != null) { // realm roles + for (RoleRepresentation roleRep : rep.getRoles().getRealm()) { + RoleModel role = newRealm.getRole(roleRep.getName()); + addComposites(role, roleRep, newRealm); + } + } + if (rep.getRoles().getApplication() != null) { + for (Map.Entry> entry : rep.getRoles().getApplication().entrySet()) { + ApplicationModel app = newRealm.getApplicationByName(entry.getKey()); + if (app == null) { + throw new RuntimeException("App doesn't exist in role definitions: " + entry.getKey()); + } + for (RoleRepresentation roleRep : entry.getValue()) { + RoleModel role = app.getRole(roleRep.getName()); + addComposites(role, roleRep, newRealm); + } + } + } + } + + // Setup realm default roles + if (rep.getDefaultRoles() != null) { + for (String roleString : rep.getDefaultRoles()) { + newRealm.addDefaultRole(roleString.trim()); + } + } + // Setup application default roles + if (rep.getApplications() != null) { + for (ApplicationRepresentation resourceRep : rep.getApplications()) { + if (resourceRep.getDefaultRoles() != null) { + ApplicationModel appModel = newRealm.getApplicationByName(resourceRep.getName()); + appModel.updateDefaultRoles(resourceRep.getDefaultRoles()); + } + } + } + + if (rep.getOauthClients() != null) { + createOAuthClients(rep, newRealm); + } + + + // Now that all possible roles and applications are created, create scope mappings + + Map appMap = newRealm.getApplicationNameMap(); + + if (rep.getApplicationScopeMappings() != null) { + + for (Map.Entry> entry : rep.getApplicationScopeMappings().entrySet()) { + ApplicationModel app = appMap.get(entry.getKey()); + if (app == null) { + throw new RuntimeException("Unable to find application role mappings for app: " + entry.getKey()); + } + createApplicationScopeMappings(newRealm, app, entry.getValue()); + } + } + + if (rep.getScopeMappings() != null) { + for (ScopeMappingRepresentation scope : rep.getScopeMappings()) { + ClientModel client = newRealm.findClient(scope.getClient()); + for (String roleString : scope.getRoles()) { + RoleModel role = newRealm.getRole(roleString.trim()); + if (role == null) { + role = newRealm.addRole(roleString.trim()); + } + client.addScopeMapping(role); + } + + } + } + + if (rep.getSmtpServer() != null) { + newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer())); + } + + if (rep.getSocialProviders() != null) { + newRealm.setSocialConfig(new HashMap(rep.getSocialProviders())); + } + if (rep.getLdapServer() != null) { + newRealm.setLdapServerConfig(new HashMap(rep.getLdapServer())); + } + + if (rep.getAuthenticationProviders() != null) { + List authProviderModels = convertAuthenticationProviders(rep.getAuthenticationProviders()); + newRealm.setAuthenticationProviders(authProviderModels); + } else { + List authProviderModels = Arrays.asList(AuthenticationProviderModel.DEFAULT_PROVIDER); + newRealm.setAuthenticationProviders(authProviderModels); + } + + if (rep.getUserFederationProviders() != null) { + List providerModels = convertFederationProviders(rep.getUserFederationProviders()); + newRealm.setUserFederationProviders(providerModels); + } + + // create users and their role mappings and social mappings + + if (rep.getUsers() != null) { + for (UserRepresentation userRep : rep.getUsers()) { + UserModel user = createUser(session, newRealm, userRep, appMap); + } + } + } + + public static void updateRealm(RealmRepresentation rep, RealmModel realm) { + if (rep.getRealm() != null) { + realm.setName(rep.getRealm()); + } + if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled()); + if (rep.isSocial() != null) realm.setSocial(rep.isSocial()); + if (rep.isBruteForceProtected() != null) realm.setBruteForceProtected(rep.isBruteForceProtected()); + if (rep.getMaxFailureWaitSeconds() != null) realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); + if (rep.getMinimumQuickLoginWaitSeconds() != null) realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); + if (rep.getWaitIncrementSeconds() != null) realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); + if (rep.getQuickLoginCheckMilliSeconds() != null) realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); + if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); + if (rep.getFailureFactor() != null) realm.setFailureFactor(rep.getFailureFactor()); + if (rep.isPasswordCredentialGrantAllowed() != null) realm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); + if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed()); + if (rep.isRememberMe() != null) realm.setRememberMe(rep.isRememberMe()); + if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail()); + if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); + if (rep.isUpdateProfileOnInitialSocialLogin() != null) + realm.setUpdateProfileOnInitialSocialLogin(rep.isUpdateProfileOnInitialSocialLogin()); + if (rep.isSslNotRequired() != null) realm.setSslNotRequired((rep.isSslNotRequired())); + if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); + if (rep.getAccessCodeLifespanUserAction() != null) + realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); + if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore()); + if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); + if (rep.getSsoSessionIdleTimeout() != null) realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); + if (rep.getSsoSessionMaxLifespan() != null) realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan()); + if (rep.getRequiredCredentials() != null) { + realm.updateRequiredCredentials(rep.getRequiredCredentials()); + } + if (rep.getLoginTheme() != null) realm.setLoginTheme(rep.getLoginTheme()); + if (rep.getAccountTheme() != null) realm.setAccountTheme(rep.getAccountTheme()); + if (rep.getAdminTheme() != null) realm.setAdminTheme(rep.getAdminTheme()); + if (rep.getEmailTheme() != null) realm.setEmailTheme(rep.getEmailTheme()); + + if (rep.getPasswordPolicy() != null) realm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy())); + + if (rep.getDefaultRoles() != null) { + realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()])); + } + + if (rep.getSmtpServer() != null) { + realm.setSmtpConfig(new HashMap(rep.getSmtpServer())); + } + + if (rep.getSocialProviders() != null) { + realm.setSocialConfig(new HashMap(rep.getSocialProviders())); + } + + if (rep.getLdapServer() != null) { + realm.setLdapServerConfig(new HashMap(rep.getLdapServer())); + } + if (rep.getAuthenticationProviders() != null) { + List authProviderModels = convertAuthenticationProviders(rep.getAuthenticationProviders()); + realm.setAuthenticationProviders(authProviderModels); + } + + if (rep.getUserFederationProviders() != null) { + List providerModels = convertFederationProviders(rep.getUserFederationProviders()); + realm.setUserFederationProviders(providerModels); + } + + if ("GENERATE".equals(rep.getPublicKey())) { + KeycloakModelUtils.generateRealmKeys(realm); + } + } + + // Basic realm stuff + + public static void addRequiredCredential(RealmModel newRealm, String requiredCred) { + newRealm.addRequiredCredential(requiredCred); + } + + + private static List convertAuthenticationProviders(List authenticationProviders) { + List result = new ArrayList(); + + for (AuthenticationProviderRepresentation representation : authenticationProviders) { + AuthenticationProviderModel model = new AuthenticationProviderModel(representation.getProviderName(), + representation.isPasswordUpdateSupported(), representation.getConfig()); + result.add(model); + } + return result; + } + + private static List convertFederationProviders(List providers) { + List result = new ArrayList(); + + for (UserFederationProviderRepresentation representation : providers) { + UserFederationProviderModel model = new UserFederationProviderModel(representation.getId(), representation.getProviderName(), + representation.getConfig(), representation.getPriority()); + result.add(model); + } + return result; + } + + // Roles + + public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) { + RoleModel role = roleRep.getId()!=null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName()); + if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription()); + } + + private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) { + if (roleRep.getComposites() == null) return; + if (roleRep.getComposites().getRealm() != null) { + for (String roleStr : roleRep.getComposites().getRealm()) { + RoleModel realmRole = realm.getRole(roleStr); + if (realmRole == null) throw new RuntimeException("Unable to find composite realm role: " + roleStr); + role.addCompositeRole(realmRole); + } + } + if (roleRep.getComposites().getApplication() != null) { + for (Map.Entry> entry : roleRep.getComposites().getApplication().entrySet()) { + ApplicationModel app = realm.getApplicationByName(entry.getKey()); + if (app == null) { + throw new RuntimeException("App doesn't exist in role definitions: " + roleRep.getName()); + } + for (String roleStr : entry.getValue()) { + RoleModel appRole = app.getRole(roleStr); + if (appRole == null) throw new RuntimeException("Unable to find composite app role: " + roleStr); + role.addCompositeRole(appRole); + } + + } + + } + + } + + // APPLICATIONS + + private static Map createApplications(RealmRepresentation rep, RealmModel realm) { + Map appMap = new HashMap(); + for (ApplicationRepresentation resourceRep : rep.getApplications()) { + ApplicationModel app = createApplication(realm, resourceRep, false); + appMap.put(app.getName(), app); + } + return appMap; + } + + /** + * Does not create scope or role mappings! + * + * @param realm + * @param resourceRep + * @return + */ + public static ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep, boolean addDefaultRoles) { + logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName()); + ApplicationModel applicationModel = resourceRep.getId()!=null ? realm.addApplication(resourceRep.getId(), resourceRep.getName()) : realm.addApplication(resourceRep.getName()); + if (resourceRep.isEnabled() != null) applicationModel.setEnabled(resourceRep.isEnabled()); + applicationModel.setManagementUrl(resourceRep.getAdminUrl()); + if (resourceRep.isSurrogateAuthRequired() != null) + applicationModel.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired()); + applicationModel.setBaseUrl(resourceRep.getBaseUrl()); + if (resourceRep.isBearerOnly() != null) applicationModel.setBearerOnly(resourceRep.isBearerOnly()); + if (resourceRep.isPublicClient() != null) applicationModel.setPublicClient(resourceRep.isPublicClient()); + applicationModel.updateApplication(); + + if (resourceRep.getNotBefore() != null) { + applicationModel.setNotBefore(resourceRep.getNotBefore()); + } + + applicationModel.setSecret(resourceRep.getSecret()); + if (applicationModel.getSecret() == null) { + KeycloakModelUtils.generateSecret(applicationModel); + } + + + if (resourceRep.getRedirectUris() != null) { + for (String redirectUri : resourceRep.getRedirectUris()) { + applicationModel.addRedirectUri(redirectUri); + } + } + if (resourceRep.getWebOrigins() != null) { + for (String webOrigin : resourceRep.getWebOrigins()) { + logger.debugv("Application: {0} webOrigin: {1}", resourceRep.getName(), webOrigin); + applicationModel.addWebOrigin(webOrigin); + } + } else { + // add origins from redirect uris + if (resourceRep.getRedirectUris() != null) { + Set origins = new HashSet(); + for (String redirectUri : resourceRep.getRedirectUris()) { + logger.info("add redirectUri to origin: " + redirectUri); + if (redirectUri.startsWith("http:")) { + URI uri = URI.create(redirectUri); + String origin = uri.getScheme() + "://" + uri.getHost(); + if (uri.getPort() != -1) { + origin += ":" + uri.getPort(); + } + logger.debugv("adding default application origin: {0}" , origin); + origins.add(origin); + } + } + if (origins.size() > 0) { + applicationModel.setWebOrigins(origins); + } + } + } + + if (addDefaultRoles && resourceRep.getDefaultRoles() != null) { + applicationModel.updateDefaultRoles(resourceRep.getDefaultRoles()); + } + + if (resourceRep.getClaims() != null) { + setClaims(applicationModel, resourceRep.getClaims()); + } else { + applicationModel.setAllowedClaimsMask(ClaimMask.USERNAME); + } + + return applicationModel; + } + + public static void updateApplication(ApplicationRepresentation rep, ApplicationModel resource) { + if (rep.getName() != null) resource.setName(rep.getName()); + if (rep.isEnabled() != null) resource.setEnabled(rep.isEnabled()); + if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly()); + if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient()); + if (rep.getAdminUrl() != null) resource.setManagementUrl(rep.getAdminUrl()); + if (rep.getBaseUrl() != null) resource.setBaseUrl(rep.getBaseUrl()); + if (rep.isSurrogateAuthRequired() != null) resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired()); + resource.updateApplication(); + + if (rep.getNotBefore() != null) { + resource.setNotBefore(rep.getNotBefore()); + } + if (rep.getDefaultRoles() != null) { + resource.updateDefaultRoles(rep.getDefaultRoles()); + } + + List redirectUris = rep.getRedirectUris(); + if (redirectUris != null) { + resource.setRedirectUris(new HashSet(redirectUris)); + } + + List webOrigins = rep.getWebOrigins(); + if (webOrigins != null) { + resource.setWebOrigins(new HashSet(webOrigins)); + } + + if (rep.getClaims() != null) { + setClaims(resource, rep.getClaims()); + } + } + + public static void setClaims(ClientModel model, ClaimRepresentation rep) { + long mask = model.getAllowedClaimsMask(); + if (rep.getAddress()) { + mask |= ClaimMask.ADDRESS; + } else { + mask &= ~ClaimMask.ADDRESS; + } + if (rep.getEmail()) { + mask |= ClaimMask.EMAIL; + } else { + mask &= ~ClaimMask.EMAIL; + } + if (rep.getGender()) { + mask |= ClaimMask.GENDER; + } else { + mask &= ~ClaimMask.GENDER; + } + if (rep.getLocale()) { + mask |= ClaimMask.LOCALE; + } else { + mask &= ~ClaimMask.LOCALE; + } + if (rep.getName()) { + mask |= ClaimMask.NAME; + } else { + mask &= ~ClaimMask.NAME; + } + if (rep.getPhone()) { + mask |= ClaimMask.PHONE; + } else { + mask &= ~ClaimMask.PHONE; + } + if (rep.getPicture()) { + mask |= ClaimMask.PICTURE; + } else { + mask &= ~ClaimMask.PICTURE; + } + if (rep.getProfile()) { + mask |= ClaimMask.PROFILE; + } else { + mask &= ~ClaimMask.PROFILE; + } + if (rep.getUsername()) { + mask |= ClaimMask.USERNAME; + } else { + mask &= ~ClaimMask.USERNAME; + } + if (rep.getWebsite()) { + mask |= ClaimMask.WEBSITE; + } else { + mask &= ~ClaimMask.WEBSITE; + } + model.setAllowedClaimsMask(mask); + } + + // OAuth clients + + private static void createOAuthClients(RealmRepresentation realmRep, RealmModel realm) { + for (OAuthClientRepresentation rep : realmRep.getOauthClients()) { + createOAuthClient(rep, realm); + } + } + + public static OAuthClientModel createOAuthClient(String id, String name, RealmModel realm) { + OAuthClientModel model = id!=null ? realm.addOAuthClient(id, name) : realm.addOAuthClient(name); + KeycloakModelUtils.generateSecret(model); + return model; + } + + public static OAuthClientModel createOAuthClient(OAuthClientRepresentation rep, RealmModel realm) { + OAuthClientModel model = createOAuthClient(rep.getId(), rep.getName(), realm); + updateOAuthClient(rep, model); + return model; + } + + public static void updateOAuthClient(OAuthClientRepresentation rep, OAuthClientModel model) { + if (rep.getName() != null) model.setClientId(rep.getName()); + if (rep.isEnabled() != null) model.setEnabled(rep.isEnabled()); + if (rep.isPublicClient() != null) model.setPublicClient(rep.isPublicClient()); + if (rep.isDirectGrantsOnly() != null) model.setDirectGrantsOnly(rep.isDirectGrantsOnly()); + if (rep.getClaims() != null) { + setClaims(model, rep.getClaims()); + } + if (rep.getNotBefore() != null) { + model.setNotBefore(rep.getNotBefore()); + } + if (rep.getSecret() != null) model.setSecret(rep.getSecret()); + List redirectUris = rep.getRedirectUris(); + if (redirectUris != null) { + model.setRedirectUris(new HashSet(redirectUris)); + } + + List webOrigins = rep.getWebOrigins(); + if (webOrigins != null) { + model.setWebOrigins(new HashSet(webOrigins)); + } + + if (rep.getClaims() != null) { + setClaims(model, rep.getClaims()); + } + + if (rep.getNotBefore() != null) { + model.setNotBefore(rep.getNotBefore()); + } + + } + + // Scope mappings + + public static void createApplicationScopeMappings(RealmModel realm, ApplicationModel applicationModel, List mappings) { + for (ScopeMappingRepresentation mapping : mappings) { + ClientModel client = realm.findClient(mapping.getClient()); + for (String roleString : mapping.getRoles()) { + RoleModel role = applicationModel.getRole(roleString.trim()); + if (role == null) { + role = applicationModel.addRole(roleString.trim()); + } + client.addScopeMapping(role); + } + } + } + + // Users + + public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep, Map appMap) { + UserModel user = session.users().addUser(newRealm, userRep.getId(), userRep.getUsername(), false); + user.setEnabled(userRep.isEnabled()); + user.setEmail(userRep.getEmail()); + user.setFirstName(userRep.getFirstName()); + user.setLastName(userRep.getLastName()); + user.setFederationLink(userRep.getFederationLink()); + if (userRep.getAttributes() != null) { + for (Map.Entry entry : userRep.getAttributes().entrySet()) { + user.setAttribute(entry.getKey(), entry.getValue()); + } + } + if (userRep.getRequiredActions() != null) { + for (String requiredAction : userRep.getRequiredActions()) { + user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction)); + } + } + if (userRep.getCredentials() != null) { + for (CredentialRepresentation cred : userRep.getCredentials()) { + updateCredential(user, cred); + } + } + if (userRep.getAuthenticationLink() != null) { + AuthenticationLinkRepresentation link = userRep.getAuthenticationLink(); + AuthenticationLinkModel authLink = new AuthenticationLinkModel(link.getAuthProvider(), link.getAuthUserId()); + user.setAuthenticationLink(authLink); + } + if (userRep.getSocialLinks() != null) { + for (SocialLinkRepresentation socialLink : userRep.getSocialLinks()) { + SocialLinkModel mappingModel = new SocialLinkModel(socialLink.getSocialProvider(), socialLink.getSocialUserId(), socialLink.getSocialUsername()); + session.users().addSocialLink(newRealm, user, mappingModel); + } + } + if (userRep.getRealmRoles() != null) { + for (String roleString : userRep.getRealmRoles()) { + RoleModel role = newRealm.getRole(roleString.trim()); + if (role == null) { + role = newRealm.addRole(roleString.trim()); + } + user.grantRole(role); + } + } + if (userRep.getApplicationRoles() != null) { + for (Map.Entry> entry : userRep.getApplicationRoles().entrySet()) { + ApplicationModel app = appMap.get(entry.getKey()); + if (app == null) { + throw new RuntimeException("Unable to find application role mappings for app: " + entry.getKey()); + } + createApplicationRoleMappings(app, user, entry.getValue()); + } + } + return user; + } + + // Detect if it is "plain-text" or "hashed" representation and update model according to it + private static void updateCredential(UserModel user, CredentialRepresentation cred) { + if (cred.getValue() != null) { + UserCredentialModel plainTextCred = convertCredential(cred); + user.updateCredential(plainTextCred); + } else { + UserCredentialValueModel hashedCred = new UserCredentialValueModel(); + hashedCred.setType(cred.getType()); + hashedCred.setDevice(cred.getDevice()); + hashedCred.setHashIterations(cred.getHashIterations()); + try { + hashedCred.setSalt(Base64.decode(cred.getSalt())); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + hashedCred.setValue(cred.getHashedSaltedValue()); + user.updateCredentialDirectly(hashedCred); + } + } + + public static UserCredentialModel convertCredential(CredentialRepresentation cred) { + UserCredentialModel credential = new UserCredentialModel(); + credential.setType(cred.getType()); + credential.setValue(cred.getValue()); + return credential; + } + + // Role mappings + + public static void createApplicationRoleMappings(ApplicationModel applicationModel, UserModel user, List roleNames) { + if (user == null) { + throw new RuntimeException("User not found"); + } + + for (String roleName : roleNames) { + RoleModel role = applicationModel.getRole(roleName.trim()); + if (role == null) { + role = applicationModel.addRole(roleName.trim()); + } + user.grantRole(role); + + } + } + +} diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmAdapter.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmAdapter.java index 4d9bf616e4..6353b50c02 100755 --- a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmAdapter.java +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmAdapter.java @@ -608,7 +608,7 @@ public class RealmAdapter implements RealmModel { @Override public List getUserFederationProviders() { if (updated != null) return updated.getUserFederationProviders(); - return cached.getFederationProviders(); + return cached.getUserFederationProviders(); } @Override @@ -617,6 +617,19 @@ public class RealmAdapter implements RealmModel { updated.setUserFederationProviders(providers); } + @Override + public UserFederationProviderModel addUserFederationProvider(String providerName, Map config, int priority) { + getDelegateForUpdate(); + return updated.addUserFederationProvider(providerName, config, priority); + } + + @Override + public void removeUserFederationProvider(UserFederationProviderModel provider) { + getDelegateForUpdate(); + updated.removeUserFederationProvider(provider); + + } + @Override public String getLoginTheme() { if (updated != null) return updated.getLoginTheme(); diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java index c8748fe603..83befd28a1 100755 --- a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java @@ -65,7 +65,7 @@ public class CachedRealm { private List requiredCredentials = new ArrayList(); private List authenticationProviders = new ArrayList(); - private List federationProviders = new ArrayList(); + private List userFederationProviders = new ArrayList(); private Map smtpConfig = new HashMap(); private Map socialConfig = new HashMap(); @@ -122,7 +122,7 @@ public class CachedRealm { requiredCredentials = model.getRequiredCredentials(); authenticationProviders = model.getAuthenticationProviders(); - federationProviders = model.getUserFederationProviders(); + userFederationProviders = model.getUserFederationProviders(); smtpConfig.putAll(model.getSmtpConfig()); socialConfig.putAll(model.getSocialConfig()); @@ -331,7 +331,7 @@ public class CachedRealm { return auditListeners; } - public List getFederationProviders() { - return federationProviders; + public List getUserFederationProviders() { + return userFederationProviders; } } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java index e65e377521..2103f3f473 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java @@ -3,8 +3,9 @@ package org.keycloak.models.jpa; import org.keycloak.models.ApplicationModel; import org.keycloak.models.AuthenticationProviderModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.UserFederationProvider; import org.keycloak.models.UserFederationProviderModel; -import org.keycloak.models.jpa.entities.FederationProviderEntity; +import org.keycloak.models.jpa.entities.UserFederationProviderEntity; import org.keycloak.models.KeycloakSession; import org.keycloak.models.OAuthClientModel; import org.keycloak.models.PasswordPolicy; @@ -30,6 +31,7 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -728,61 +730,104 @@ public class RealmAdapter implements RealmModel { @Override public List getUserFederationProviders() { - List entities = realm.getFederationProviders(); - List copy = new ArrayList(); - for (FederationProviderEntity entity : entities) { + List entities = realm.getUserFederationProviders(); + List copy = new ArrayList(); + for (UserFederationProviderEntity entity : entities) { copy.add(entity); } - Collections.sort(copy, new Comparator() { + Collections.sort(copy, new Comparator() { @Override - public int compare(FederationProviderEntity o1, FederationProviderEntity o2) { + public int compare(UserFederationProviderEntity o1, UserFederationProviderEntity o2) { return o1.getPriority() - o2.getPriority(); } }); List result = new ArrayList(); - for (FederationProviderEntity entity : copy) { - result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig())); + for (UserFederationProviderEntity entity : copy) { + result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority())); } return result; } @Override - public void setUserFederationProviders(List providers) { - List newEntities = new ArrayList(); - int counter = 1; - for (UserFederationProviderModel model : providers) { - FederationProviderEntity entity = new FederationProviderEntity(); - entity.setId(KeycloakModelUtils.generateId()); - entity.setRealm(realm); - entity.setProviderName(model.getProviderName()); - entity.setConfig(model.getConfig()); - entity.setPriority(counter++); - newEntities.add(entity); - } - - // Remove all existing first - Collection existing = realm.getFederationProviders(); - Collection copy = new ArrayList(existing); - for (FederationProviderEntity apToRemove : copy) { - existing.remove(apToRemove); - em.remove(apToRemove); - } - - em.flush(); - - // Now create all new providers - for (FederationProviderEntity apToAdd : newEntities) { - existing.add(apToAdd); - em.persist(apToAdd); - } - + public UserFederationProviderModel addUserFederationProvider(String providerName, Map config, int priority) { + String id = KeycloakModelUtils.generateId(); + UserFederationProviderEntity entity = new UserFederationProviderEntity(); + entity.setId(id); + entity.setRealm(realm); + entity.setProviderName(providerName); + entity.setConfig(config); + entity.setPriority(priority); + em.persist(entity); + realm.getUserFederationProviders().add(entity); em.flush(); + return new UserFederationProviderModel(entity.getId(), providerName, config, priority); } + @Override + public void removeUserFederationProvider(UserFederationProviderModel provider) { + UserFederationProviderEntity entity = null; + Iterator it = realm.getUserFederationProviders().iterator(); + while (it.hasNext()) { + if (entity.getId().equals(provider.getId())) { + it.remove(); + em.remove(entity); + return; + } + } + } + + @Override + public void setUserFederationProviders(List providers) { + + Iterator it = realm.getUserFederationProviders().iterator(); + while (it.hasNext()) { + UserFederationProviderEntity entity = it.next(); + boolean found = false; + for (UserFederationProviderModel model : providers) { + if (entity.getId().equals(model.getId())) { + entity.setConfig(model.getConfig()); + entity.setPriority(model.getPriority()); + entity.setProviderName(model.getProviderName()); + entity.setPriority(model.getPriority()); + found = true; + break; + } + + } + if (found) continue; + it.remove(); + em.remove(entity); + } + + List add = new LinkedList(); + for (UserFederationProviderModel model : providers) { + boolean found = false; + for (UserFederationProviderEntity entity : realm.getUserFederationProviders()) { + if (entity.getId().equals(model.getId())) { + found = true; + break; + } + } + if (!found) add.add(model); + } + + for (UserFederationProviderModel model : providers) { + UserFederationProviderEntity entity = new UserFederationProviderEntity(); + if (model.getId() != null) entity.setId(model.getId()); + else entity.setId(KeycloakModelUtils.generateId()); + entity.setConfig(model.getConfig()); + entity.setPriority(model.getPriority()); + entity.setProviderName(model.getProviderName()); + entity.setPriority(model.getPriority()); + em.persist(entity); + realm.getUserFederationProviders().add(entity); + + } + } @Override public RoleModel getRole(String name) { diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java index b7af403ff4..eef663afa5 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java @@ -117,7 +117,7 @@ public class RealmEntity { @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true) @JoinTable(name="FED_PROVIDERS") - List federationProviders = new ArrayList(); + List userFederationProviders = new ArrayList(); @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @JoinTable(name="REALM_APPLICATION", joinColumns={ @JoinColumn(name="APPLICATION_ID") }, inverseJoinColumns={ @JoinColumn(name="REALM_ID") }) @@ -513,12 +513,12 @@ public class RealmEntity { this.masterAdminApp = masterAdminApp; } - public List getFederationProviders() { - return federationProviders; + public List getUserFederationProviders() { + return userFederationProviders; } - public void setFederationProviders(List federationProviders) { - this.federationProviders = federationProviders; + public void setUserFederationProviders(List userFederationProviders) { + this.userFederationProviders = userFederationProviders; } } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/FederationProviderEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserFederationProviderEntity.java similarity index 93% rename from model/jpa/src/main/java/org/keycloak/models/jpa/entities/FederationProviderEntity.java rename to model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserFederationProviderEntity.java index 830065c193..d4a40c2c2f 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/FederationProviderEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserFederationProviderEntity.java @@ -19,8 +19,8 @@ import java.util.Map; * @author Bill Burke */ @Entity -@Table(name="FEDERATION_PROVIDER") -public class FederationProviderEntity { +@Table(name="USER_FEDERATION_PROVIDER") +public class UserFederationProviderEntity { @Id @Column(name="ID", length = 36) @@ -38,7 +38,7 @@ public class FederationProviderEntity { @ElementCollection @MapKeyColumn(name="name") @Column(name="value") - @CollectionTable(name="FEDERATION_PROVIDER_CONFIG") + @CollectionTable(name="USER_FEDERATION_CONFIG") private Map config; public String getId() { 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 index 2e563f5296..2ce26cbdea 100755 --- 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 @@ -8,7 +8,7 @@ import org.keycloak.models.ApplicationModel; import org.keycloak.models.AuthenticationProviderModel; import org.keycloak.models.ClientModel; import org.keycloak.models.UserFederationProviderModel; -import org.keycloak.models.entities.FederationProviderEntity; +import org.keycloak.models.entities.UserFederationProviderEntity; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmProvider; import org.keycloak.models.OAuthClientModel; @@ -29,8 +29,11 @@ import java.security.PublicKey; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -790,12 +793,51 @@ public class RealmAdapter extends AbstractMongoAdapter impleme realm.setAuthenticationProviders(entities); updateRealm(); } + + @Override + public UserFederationProviderModel addUserFederationProvider(String providerName, Map config, int priority) { + UserFederationProviderEntity entity = new UserFederationProviderEntity(); + entity.setId(KeycloakModelUtils.generateId()); + entity.setPriority(priority); + entity.setProviderName(providerName); + entity.setConfig(config); + realm.getUserFederationProviders().add(entity); + updateRealm(); + + return new UserFederationProviderModel(entity.getId(), providerName, config, priority); + } + + @Override + public void removeUserFederationProvider(UserFederationProviderModel provider) { + Iterator it = realm.getUserFederationProviders().iterator(); + while (it.hasNext()) { + UserFederationProviderEntity entity = it.next(); + if (entity.getId().equals(provider.getId())) { + it.remove(); + } + } + updateRealm(); + } + @Override public List getUserFederationProviders() { - List entities = realm.getFederationProviders(); - List result = new ArrayList(); - for (FederationProviderEntity entity : entities) { - result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig())); + List entities = realm.getUserFederationProviders(); + List copy = new LinkedList(); + for (UserFederationProviderEntity entity : entities) { + copy.add(entity); + + } + Collections.sort(copy, new Comparator() { + + @Override + public int compare(UserFederationProviderEntity o1, UserFederationProviderEntity o2) { + return o1.getPriority() - o2.getPriority(); + } + + }); + List result = new LinkedList(); + for (UserFederationProviderEntity entity : copy) { + result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority())); } return result; @@ -803,16 +845,18 @@ public class RealmAdapter extends AbstractMongoAdapter impleme @Override public void setUserFederationProviders(List providers) { - List entities = new ArrayList(); + List entities = new LinkedList(); for (UserFederationProviderModel model : providers) { - FederationProviderEntity entity = new FederationProviderEntity(); - entity.setId(KeycloakModelUtils.generateId()); + UserFederationProviderEntity entity = new UserFederationProviderEntity(); + if (model.getId() != null) entity.setId(model.getId()); + else entity.setId(KeycloakModelUtils.generateId()); entity.setProviderName(model.getProviderName()); entity.setConfig(model.getConfig()); + entity.setPriority(model.getPriority()); entities.add(entity); } - realm.setFederationProviders(entities); + realm.setUserFederationProviders(entities); updateRealm(); } diff --git a/model/picketlink/pom.xml b/model/picketlink/pom.xml deleted file mode 100755 index 5e677ceb46..0000000000 --- a/model/picketlink/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - keycloak-parent - org.keycloak - 1.0-beta-3-SNAPSHOT - ../../pom.xml - - 4.0.0 - - keycloak-model-picketlink - Keycloak Model Picketlink - - - - - org.bouncycastle - bcprov-jdk16 - provided - - - org.keycloak - keycloak-core - ${project.version} - provided - - - org.keycloak - keycloak-model-api - ${project.version} - - - org.jboss.logging - jboss-logging - provided - - - org.picketlink - picketlink-idm-api - provided - - - org.picketlink - picketlink-common - provided - - - org.picketlink - picketlink-idm-impl - provided - - - org.picketlink - picketlink-idm-simple-schema - provided - - - org.picketlink - picketlink-config - provided - - - org.hibernate.javax.persistence - hibernate-jpa-2.0-api - provided - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/ApplicationAdapter.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/ApplicationAdapter.java deleted file mode 100755 index 9b02e1436b..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/ApplicationAdapter.java +++ /dev/null @@ -1,313 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.ApplicationModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.picketlink.mappings.ApplicationData; -import org.keycloak.models.picketlink.relationships.ScopeRelationship; -import org.picketlink.idm.IdentityManagementException; -import org.picketlink.idm.IdentityManager; -import org.picketlink.idm.PartitionManager; -import org.picketlink.idm.RelationshipManager; -import org.picketlink.idm.model.IdentityType; -import org.picketlink.idm.model.sample.Grant; -import org.picketlink.idm.model.sample.Role; -import org.picketlink.idm.model.sample.SampleModel; -import org.picketlink.idm.query.IdentityQuery; -import org.picketlink.idm.query.RelationshipQuery; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class ApplicationAdapter implements ApplicationModel { - protected ApplicationData applicationData; - protected RealmAdapter realm; - protected IdentityManager idm; - protected PartitionManager partitionManager; - protected RelationshipManager relationshipManager; - - public ApplicationAdapter(ApplicationData applicationData, RealmAdapter realm, PartitionManager partitionManager) { - this.applicationData = applicationData; - this.realm = realm; - this.partitionManager = partitionManager; - } - - protected IdentityManager getIdm() { - if (idm == null) idm = partitionManager.createIdentityManager(applicationData); - return idm; - } - - protected RelationshipManager getRelationshipManager() { - if (relationshipManager == null) relationshipManager = partitionManager.createRelationshipManager(); - return relationshipManager; - } - - @Override - public void updateApplication() { - partitionManager.update(applicationData); - } - - @Override - public UserAdapter getApplicationUser() { - return new UserAdapter(applicationData.getResourceUser(), realm.getIdm()); - } - - @Override - public String getId() { - // for some reason picketlink queries by name when finding partition, don't know what ID is used for now - return applicationData.getName(); - } - - @Override - public String getName() { - return applicationData.getResourceName(); - } - - @Override - public void setName(String name) { - applicationData.setResourceName(name); - updateApplication(); - } - - @Override - public boolean isEnabled() { - return applicationData.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - applicationData.setEnabled(enabled); - updateApplication(); - } - - @Override - public boolean isSurrogateAuthRequired() { - return applicationData.isSurrogateAuthRequired(); - } - - @Override - public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { - applicationData.setSurrogateAuthRequired(surrogateAuthRequired); - updateApplication(); - } - - @Override - public String getManagementUrl() { - return applicationData.getManagementUrl(); - } - - @Override - public void setManagementUrl(String url) { - applicationData.setManagementUrl(url); - updateApplication(); - } - - @Override - public String getBaseUrl() { - return applicationData.getBaseUrl(); - } - - @Override - public void setBaseUrl(String url) { - applicationData.setBaseUrl(url); - updateApplication(); - } - - @Override - public RoleAdapter getRole(String name) { - Role role = SampleModel.getRole(getIdm(), name); - if (role == null) return null; - return new RoleAdapter(role, getIdm()); - } - - @Override - public RoleModel getRoleById(String id) { - IdentityQuery query = getIdm().createIdentityQuery(Role.class); - query.setParameter(IdentityType.ID, id); - List roles = query.getResultList(); - if (roles.size() == 0) return null; - return new RoleAdapter(roles.get(0), getIdm()); - } - - @Override - public void grantRole(UserModel user, RoleModel role) { - SampleModel.grantRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); - } - - @Override - public boolean hasRole(UserModel user, RoleModel role) { - return SampleModel.hasRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); - } - - @Override - public boolean hasRole(UserModel user, String role) { - RoleModel roleModel = getRole(role); - return hasRole(user, roleModel); - } - - @Override - public RoleAdapter addRole(String name) { - Role role = new Role(name); - getIdm().add(role); - return new RoleAdapter(role, getIdm()); - } - - @Override - public boolean removeRoleById(String id) { - try { - getIdm().remove(getIdm().lookupIdentityById(Role.class, id)); - return true; - } catch (IdentityManagementException e) { - return false; - } - } - - @Override - public List getRoles() { - IdentityQuery query = getIdm().createIdentityQuery(Role.class); - query.setParameter(Role.PARTITION, applicationData); - List roles = query.getResultList(); - List roleModels = new ArrayList(); - for (Role role : roles) { - roleModels.add(new RoleAdapter(role, idm)); - } - return roleModels; - } - - @Override - public Set getRoleMappingValues(UserModel user) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(Grant.class); - query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); - List grants = query.getResultList(); - HashSet set = new HashSet(); - for (Grant grant : grants) { - if (grant.getRole().getPartition().getId().equals(applicationData.getId())) set.add(grant.getRole().getName()); - } - return set; - } - - @Override - public List getRoleMappings(UserModel user) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(Grant.class); - query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); - List grants = query.getResultList(); - List set = new ArrayList(); - for (Grant grant : grants) { - if (grant.getRole().getPartition().getId().equals(applicationData.getId())) set.add(new RoleAdapter(grant.getRole(), getIdm())); - } - return set; - } - - @Override - public void deleteRoleMapping(UserModel user, RoleModel role) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(Grant.class); - query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); - query.setParameter(Grant.ROLE, ((RoleAdapter)role).getRole()); - List grants = query.getResultList(); - for (Grant grant : grants) { - getRelationshipManager().remove(grant); - } - } - - @Override - public void addScopeMapping(UserModel agent, String roleName) { - IdentityManager idm = getIdm(); - Role role = SampleModel.getRole(idm,roleName); - if (role == null) throw new RuntimeException("role not found"); - addScopeMapping(agent, new RoleAdapter(role, idm)); - - } - - @Override - public void addScopeMapping(UserModel agent, RoleModel role) { - ScopeRelationship scope = new ScopeRelationship(); - scope.setClient(((UserAdapter)agent).getUser()); - scope.setScope(((RoleAdapter)role).getRole()); - getRelationshipManager().add(scope); - } - - @Override - public void deleteScopeMapping(UserModel user, RoleModel role) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); - query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)user).getUser()); - query.setParameter(ScopeRelationship.SCOPE, ((RoleAdapter)role).getRole()); - List grants = query.getResultList(); - for (ScopeRelationship grant : grants) { - getRelationshipManager().remove(grant); - } - } - - - @Override - public Set getScopeMappingValues(UserModel agent) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); - query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)agent).getUser()); - List scope = query.getResultList(); - HashSet set = new HashSet(); - for (ScopeRelationship rel : scope) { - if (rel.getScope().getPartition().getId().equals(applicationData.getId())) set.add(rel.getScope().getName()); - } - return set; - } - - @Override - public List getScopeMappings(UserModel agent) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); - query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)agent).getUser()); - List scope = query.getResultList(); - List roles = new ArrayList(); - for (ScopeRelationship rel : scope) { - if (rel.getScope().getPartition().getId().equals(applicationData.getId())) roles.add(new RoleAdapter(rel.getScope(), getIdm())); - } - return roles; - } - - @Override - public List getDefaultRoles() { - if ( applicationData.getDefaultRoles() != null) { - return Arrays.asList(applicationData.getDefaultRoles()); - } - else { - return Collections.emptyList(); - } - } - - @Override - public void addDefaultRole(String name) { - if (getRole(name) == null) { - addRole(name); - } - - String[] defaultRoles = applicationData.getDefaultRoles(); - if (defaultRoles == null) { - defaultRoles = new String[1]; - } else { - defaultRoles = Arrays.copyOf(defaultRoles, defaultRoles.length + 1); - } - defaultRoles[defaultRoles.length - 1] = name; - - applicationData.setDefaultRoles(defaultRoles); - updateApplication(); - } - - @Override - public void updateDefaultRoles(String[] defaultRoles) { - for (String name : defaultRoles) { - if (getRole(name) == null) { - addRole(name); - } - } - - applicationData.setDefaultRoles(defaultRoles); - updateApplication(); - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/OAuthClientAdapter.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/OAuthClientAdapter.java deleted file mode 100755 index 474a0b54d4..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/OAuthClientAdapter.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.OAuthClientModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.picketlink.relationships.OAuthClientRelationship; -import org.picketlink.idm.IdentityManager; -import org.picketlink.idm.RelationshipManager; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class OAuthClientAdapter implements OAuthClientModel { - protected OAuthClientRelationship delegate; - protected IdentityManager idm; - protected RelationshipManager relationshipManager; - - public OAuthClientAdapter(OAuthClientRelationship delegate, IdentityManager idm, RelationshipManager relationshipManager) { - this.delegate = delegate; - this.idm = idm; - this.relationshipManager = relationshipManager; - } - - @Override - public String getId() { - return delegate.getId(); - } - - @Override - public UserModel getOAuthAgent() { - return new UserAdapter(delegate.getOauthAgent(), idm); - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSession.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSession.java deleted file mode 100755 index b51b773540..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSession.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakTransaction; -import org.keycloak.models.RealmModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.picketlink.mappings.RealmData; -import org.keycloak.models.picketlink.relationships.RealmListingRelationship; -import org.keycloak.models.utils.KeycloakSessionUtils; -import org.picketlink.idm.PartitionManager; -import org.picketlink.idm.RelationshipManager; -import org.picketlink.idm.query.RelationshipQuery; - -import javax.persistence.EntityManager; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class PicketlinkKeycloakSession implements KeycloakSession { - public static ThreadLocal currentEntityManager = new ThreadLocal(); - public static ThreadLocal setWhere = new ThreadLocal(); - protected PartitionManager partitionManager; - protected EntityManager entityManager; - - public PicketlinkKeycloakSession(PartitionManager partitionManager, EntityManager entityManager) { - this.partitionManager = partitionManager; - this.entityManager = entityManager; - if (currentEntityManager.get() != null) - { - setWhere.get().printStackTrace(); - - throw new IllegalStateException("Thread local was leaked!"); - } - currentEntityManager.set(entityManager); - setWhere.set(new Exception()); - } - - @Override - public KeycloakTransaction getTransaction() { - return new PicketlinkKeycloakTransaction(entityManager.getTransaction()); - } - - @Override - public RealmAdapter createRealm(String name) { - return createRealm(KeycloakSessionUtils.generateId(), name); - } - - @Override - public RealmAdapter createRealm(String id, String name) { - // Picketlink beta 6 uses name attribute for getPartition() - RealmData newRealm = new RealmData(id); - newRealm.setId(id); - newRealm.setRealmName(name); - partitionManager.add(newRealm); - RealmListingRelationship rel = new RealmListingRelationship(); - // picketlink beta 6 uses Realm name for lookup! Don't forget! - rel.setRealm(newRealm.getName()); - partitionManager.createRelationshipManager().add(rel); - - RealmAdapter realm = new RealmAdapter(this, newRealm, partitionManager); - return realm; - } - - @Override - public List getRealms(UserModel admin) { - // todo ability to assign realm management to a specific admin - // currently each admin is allowed to access all realms so just do a big query - RelationshipManager relationshipManager = partitionManager.createRelationshipManager(); - RelationshipQuery query = relationshipManager.createRelationshipQuery(RealmListingRelationship.class); - List results = query.getResultList(); - List realmModels = new ArrayList(); - for (RealmListingRelationship relationship : results) { - String realmName = relationship.getRealm(); - RealmModel model = getRealm(realmName); - if (model == null) { - relationshipManager.remove(relationship); - } else { - realmModels.add(model); - } - } - return realmModels; - } - - @Override - public RealmAdapter getRealm(String id) { - // picketlink beta 6 uses Realm name for lookup! Don't forget! - RealmData existing = partitionManager.getPartition(RealmData.class, id); - if (existing == null) { - return null; - } - return new RealmAdapter(this, existing, partitionManager); - } - - @Override - public RealmModel getRealmByName(String name) { - throw new RuntimeException("NOT IMPLEMENTED YET"); - } - - @Override - public boolean removeRealm(String id) { - RealmData partition = partitionManager.getPartition(RealmData.class, id); - if (partition == null) { - return false; - } - partitionManager.remove(partition); - return true; - } - - @Override - public void close() { - setWhere.set(null); - currentEntityManager.set(null); - if (entityManager.getTransaction().isActive()) entityManager.getTransaction().rollback(); - if (entityManager.isOpen()) entityManager.close(); - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSessionFactory.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSessionFactory.java deleted file mode 100755 index 1d01f906ac..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakSessionFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.KeycloakSessionFactory; -import org.picketlink.idm.PartitionManager; - -import javax.persistence.EntityManagerFactory; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class PicketlinkKeycloakSessionFactory implements KeycloakSessionFactory { - protected EntityManagerFactory factory; - protected PartitionManager partitionManager; - - public PicketlinkKeycloakSessionFactory(EntityManagerFactory factory, PartitionManager partitionManager) { - this.factory = factory; - this.partitionManager = partitionManager; - } - - @Override - public KeycloakSession createSession() { - return new PicketlinkKeycloakSession(partitionManager, factory.createEntityManager()); - } - - @Override - public void close() { - factory.close(); - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakTransaction.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakTransaction.java deleted file mode 100755 index 4eb14ccf4d..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkKeycloakTransaction.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.KeycloakTransaction; - -import javax.persistence.EntityTransaction; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class PicketlinkKeycloakTransaction implements KeycloakTransaction { - protected EntityTransaction transaction; - - public PicketlinkKeycloakTransaction(EntityTransaction transaction) { - this.transaction = transaction; - } - - public void begin() { - transaction.begin(); - } - - public void setRollbackOnly() { - transaction.setRollbackOnly(); - } - - public boolean isActive() { - return transaction.isActive(); - } - - public boolean getRollbackOnly() { - return transaction.getRollbackOnly(); - } - - public void commit() { - transaction.commit(); - } - - public void rollback() { - transaction.rollback(); - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkModelProvider.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkModelProvider.java deleted file mode 100755 index 3a87fa3111..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/PicketlinkModelProvider.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.KeycloakSessionFactory; -import org.keycloak.models.ModelProvider; -import org.keycloak.models.picketlink.mappings.ApplicationEntity; -import org.keycloak.models.picketlink.mappings.RealmEntity; -import org.picketlink.idm.PartitionManager; -import org.picketlink.idm.config.IdentityConfigurationBuilder; -import org.picketlink.idm.internal.DefaultPartitionManager; -import org.picketlink.idm.jpa.internal.JPAContextInitializer; -import org.picketlink.idm.jpa.model.sample.simple.AccountTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.AttributeTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.AttributedTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.DigestCredentialTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.GroupTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.IdentityTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.OTPCredentialTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.PartitionTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.PasswordCredentialTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.RelationshipIdentityTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.RelationshipTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.RoleTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.X509CredentialTypeEntity; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class PicketlinkModelProvider implements ModelProvider { - @Override - public KeycloakSessionFactory createFactory() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory("picketlink-keycloak-identity-store"); - return new PicketlinkKeycloakSessionFactory(emf, buildPartitionManager()); - } - - @Override - public String getId() { - return "picketlink"; - } - - public static PartitionManager buildPartitionManager() { - IdentityConfigurationBuilder builder = new IdentityConfigurationBuilder(); - - builder - .named("KEYCLOAK_JPA_CONFIG") - .stores() - .jpa() - .mappedEntity( - AttributedTypeEntity.class, - AccountTypeEntity.class, - RoleTypeEntity.class, - GroupTypeEntity.class, - IdentityTypeEntity.class, - RelationshipTypeEntity.class, - RelationshipIdentityTypeEntity.class, - PartitionTypeEntity.class, - PasswordCredentialTypeEntity.class, - DigestCredentialTypeEntity.class, - X509CredentialTypeEntity.class, - OTPCredentialTypeEntity.class, - AttributeTypeEntity.class, - RealmEntity.class, - ApplicationEntity.class - ) - .supportGlobalRelationship(org.picketlink.idm.model.Relationship.class) - .addContextInitializer(new JPAContextInitializer(null) { - @Override - public EntityManager getEntityManager() { - return PicketlinkKeycloakSession.currentEntityManager.get(); - } - }) - .supportAllFeatures(); - - DefaultPartitionManager partitionManager = new DefaultPartitionManager(builder.buildAll()); - return partitionManager; - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/RealmAdapter.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/RealmAdapter.java deleted file mode 100755 index bb1b564cce..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/RealmAdapter.java +++ /dev/null @@ -1,1046 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.bouncycastle.openssl.PEMWriter; -import org.keycloak.models.ApplicationModel; -import org.keycloak.models.IdGenerator; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.OAuthClientModel; -import org.keycloak.models.PasswordPolicy; -import org.keycloak.models.RealmModel; -import org.keycloak.models.RequiredCredentialModel; -import org.keycloak.models.RoleModel; -import org.keycloak.models.SocialLinkModel; -import org.keycloak.models.UserCredentialModel; -import org.keycloak.models.UserModel; -import org.keycloak.models.picketlink.mappings.ApplicationData; -import org.keycloak.models.picketlink.mappings.RealmData; -import org.keycloak.models.picketlink.relationships.ApplicationRelationship; -import org.keycloak.models.picketlink.relationships.OAuthClientRelationship; -import org.keycloak.models.picketlink.relationships.OAuthClientRequiredCredentialRelationship; -import org.keycloak.models.picketlink.relationships.RequiredApplicationCredentialRelationship; -import org.keycloak.models.picketlink.relationships.RequiredCredentialRelationship; -import org.keycloak.models.picketlink.relationships.ScopeRelationship; -import org.keycloak.models.picketlink.relationships.SocialLinkRelationship; -import org.keycloak.util.PemUtils; -import org.picketlink.idm.IdentityManagementException; -import org.picketlink.idm.IdentityManager; -import org.picketlink.idm.PartitionManager; -import org.picketlink.idm.RelationshipManager; -import org.picketlink.idm.credential.Credentials; -import org.picketlink.idm.credential.Password; -import org.picketlink.idm.credential.TOTPCredential; -import org.picketlink.idm.credential.TOTPCredentials; -import org.picketlink.idm.credential.UsernamePasswordCredentials; -import org.picketlink.idm.credential.X509CertificateCredentials; -import org.picketlink.idm.model.IdentityType; -import org.picketlink.idm.model.sample.Grant; -import org.picketlink.idm.model.sample.Role; -import org.picketlink.idm.model.sample.SampleModel; -import org.picketlink.idm.model.sample.User; -import org.picketlink.idm.query.IdentityQuery; -import org.picketlink.idm.query.QueryParameter; -import org.picketlink.idm.query.RelationshipQuery; - -import java.io.IOException; -import java.io.StringWriter; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Meant to be a per-request object - * - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RealmAdapter implements RealmModel { - - protected RealmData realm; - protected volatile transient PublicKey publicKey; - protected volatile transient PrivateKey privateKey; - protected IdentityManager idm; - protected PartitionManager partitionManager; - protected RelationshipManager relationshipManager; - protected KeycloakSession session; - private PasswordPolicy passwordPolicy; - - public RealmAdapter(KeycloakSession session, RealmData realm, PartitionManager partitionManager) { - this.session = session; - this.realm = realm; - this.partitionManager = partitionManager; - } - - protected IdentityManager getIdm() { - if (idm == null) idm = partitionManager.createIdentityManager(realm); - return idm; - } - - protected RelationshipManager getRelationshipManager() { - if (relationshipManager == null) relationshipManager = partitionManager.createRelationshipManager(); - return relationshipManager; - } - - protected void updateRealm() { - partitionManager.update(realm); - } - - @Override - public String getId() { - // for some reason picketlink queries by name when finding partition, don't know what ID is used for now - return realm.getName(); - } - - @Override - public String getName() { - return realm.getRealmName(); - } - - @Override - public void setName(String name) { - realm.setRealmName(name); - updateRealm(); - } - - @Override - public boolean isEnabled() { - return realm.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - realm.setEnabled(enabled); - updateRealm(); - } - - @Override - public boolean isSocial() { - return realm.isSocial(); - } - - @Override - public void setSocial(boolean social) { - realm.setSocial(social); - updateRealm(); - } - - @Override - public boolean isUpdateProfileOnInitialSocialLogin() { - return realm.isUpdateProfileOnInitialSocialLogin(); - } - - @Override - public void setUpdateProfileOnInitialSocialLogin(boolean updateProfileOnInitialSocialLogin) { - realm.setUpdateProfileOnInitialSocialLogin(updateProfileOnInitialSocialLogin); - updateRealm(); - } - - @Override - public boolean isSslNotRequired() { - return realm.isSslNotRequired(); - } - - @Override - public void setSslNotRequired(boolean sslNotRequired) { - realm.setSslNotRequired(sslNotRequired); - updateRealm(); - } - - @Override - public boolean isRegistrationAllowed() { - return realm.isRegistrationAllowed(); - } - - @Override - public void setRegistrationAllowed(boolean registrationAllowed) { - realm.setRegistrationAllowed(registrationAllowed); - updateRealm(); - } - - @Override - public boolean isVerifyEmail() { - return realm.isVerifyEmail(); - } - - @Override - public void setVerifyEmail(boolean verifyEmail) { - realm.setVerifyEmail(verifyEmail); - updateRealm(); - } - - @Override - public boolean isResetPasswordAllowed() { - return realm.isResetPasswordAllowed(); - } - - @Override - public void setResetPasswordAllowed(boolean resetPassword) { - realm.setResetPasswordAllowed(resetPassword); - updateRealm(); - } - - @Override - public int getTokenLifespan() { - return realm.getTokenLifespan(); - } - - @Override - public void setTokenLifespan(int tokenLifespan) { - realm.setTokenLifespan(tokenLifespan); - 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 String getPublicKeyPem() { - return realm.getPublicKeyPem(); - } - - @Override - public void setPublicKeyPem(String publicKeyPem) { - realm.setPublicKeyPem(publicKeyPem); - this.publicKey = null; - updateRealm(); - } - - @Override - public String getPrivateKeyPem() { - return realm.getPrivateKeyPem(); - } - - @Override - public void setPrivateKeyPem(String privateKeyPem) { - realm.setPrivateKeyPem(privateKeyPem); - this.privateKey = null; - updateRealm(); - } - - @Override - public PublicKey getPublicKey() { - if (publicKey != null) return publicKey; - String pem = getPublicKeyPem(); - if (pem != null) { - try { - publicKey = PemUtils.decodePublicKey(pem); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - return publicKey; - } - - @Override - public void setPublicKey(PublicKey publicKey) { - this.publicKey = publicKey; - StringWriter writer = new StringWriter(); - PEMWriter pemWriter = new PEMWriter(writer); - try { - pemWriter.writeObject(publicKey); - pemWriter.flush(); - } catch (IOException e) { - throw new RuntimeException(e); - } - String s = writer.toString(); - setPublicKeyPem(PemUtils.removeBeginEnd(s)); - } - - @Override - public PrivateKey getPrivateKey() { - if (privateKey != null) return privateKey; - String pem = getPrivateKeyPem(); - if (pem != null) { - try { - privateKey = PemUtils.decodePrivateKey(pem); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - return privateKey; - } - - @Override - public void setPrivateKey(PrivateKey privateKey) { - this.privateKey = privateKey; - StringWriter writer = new StringWriter(); - PEMWriter pemWriter = new PEMWriter(writer); - try { - pemWriter.writeObject(privateKey); - pemWriter.flush(); - } catch (IOException e) { - throw new RuntimeException(e); - } - String s = writer.toString(); - setPrivateKeyPem(PemUtils.removeBeginEnd(s)); - } - - @Override - public List getRequiredCredentials() { - List results = getRequiredCredentialRelationships(); - return getRequiredCredentialModels(results); - } - - protected List getRequiredCredentialRelationships() { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(RequiredCredentialRelationship.class); - query.setParameter(RequiredCredentialRelationship.REALM, realm.getName()); - return query.getResultList(); - } - - - public void addRequiredApplicationCredential(RequiredCredentialModel cred) { - RequiredApplicationCredentialRelationship relationship = new RequiredApplicationCredentialRelationship(); - addRequiredCredential(cred, relationship); - } - - @Override - public List getRequiredApplicationCredentials() { - List results = getResourceRequiredCredentialRelationships(); - return getRequiredCredentialModels(results); - } - - protected List getResourceRequiredCredentialRelationships() { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(RequiredApplicationCredentialRelationship.class); - query.setParameter(RequiredApplicationCredentialRelationship.REALM, realm.getName()); - return query.getResultList(); - } - - public void addRequiredOAuthClientCredential(RequiredCredentialModel cred) { - OAuthClientRequiredCredentialRelationship relationship = new OAuthClientRequiredCredentialRelationship(); - addRequiredCredential(cred, relationship); - } - - @Override - public List getRequiredOAuthClientCredentials() { - List results = getOAuthClientRequiredCredentialRelationships(); - return getRequiredCredentialModels(results); - } - - protected List getOAuthClientRequiredCredentialRelationships() { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(OAuthClientRequiredCredentialRelationship.class); - query.setParameter(RequiredApplicationCredentialRelationship.REALM, realm.getName()); - return query.getResultList(); - } - - public void addRequiredCredential(RequiredCredentialModel cred) { - RequiredCredentialRelationship relationship = new RequiredCredentialRelationship(); - addRequiredCredential(cred, relationship); - } - - - protected List getRequiredCredentialModels(List results) { - List rtn = new ArrayList(); - for (RequiredCredentialRelationship relationship : results) { - RequiredCredentialModel model = new RequiredCredentialModel(); - model.setInput(relationship.isInput()); - model.setSecret(relationship.isSecret()); - model.setType(relationship.getCredentialType()); - model.setFormLabel(relationship.getFormLabel()); - rtn.add(model); - } - return rtn; - } - protected void addRequiredCredential(RequiredCredentialModel cred, RequiredCredentialRelationship relationship) { - relationship.setCredentialType(cred.getType()); - relationship.setInput(cred.isInput()); - relationship.setSecret(cred.isSecret()); - relationship.setRealm(realm.getName()); - relationship.setFormLabel(cred.getFormLabel()); - getRelationshipManager().add(relationship); - } - - @Override - public void updateRequiredCredentials(Set creds) { - List relationships = getRequiredCredentialRelationships(); - RelationshipManager rm = getRelationshipManager(); - Set already = new HashSet(); - for (RequiredCredentialRelationship rel : relationships) { - if (!creds.contains(rel.getCredentialType())) { - rm.remove(rel); - } else { - already.add(rel.getCredentialType()); - } - } - for (String cred : creds) { - if (!already.contains(cred)) { - addRequiredCredential(cred); - } - } - } - - @Override - public void updateRequiredOAuthClientCredentials(Set creds) { - List relationships = getOAuthClientRequiredCredentialRelationships(); - RelationshipManager rm = getRelationshipManager(); - Set already = new HashSet(); - for (RequiredCredentialRelationship rel : relationships) { - if (!creds.contains(rel.getCredentialType())) { - rm.remove(rel); - } else { - already.add(rel.getCredentialType()); - } - } - for (String cred : creds) { - if (!already.contains(cred)) { - addRequiredOAuthClientCredential(cred); - } - } - } - - @Override - public void updateRequiredApplicationCredentials(Set creds) { - List relationships = getResourceRequiredCredentialRelationships(); - RelationshipManager rm = getRelationshipManager(); - Set already = new HashSet(); - for (RequiredCredentialRelationship rel : relationships) { - if (!creds.contains(rel.getCredentialType())) { - rm.remove(rel); - } else { - already.add(rel.getCredentialType()); - } - } - for (String cred : creds) { - if (!already.contains(cred)) { - addRequiredResourceCredential(cred); - } - } - } - - - @Override - public void addRequiredCredential(String type) { - RequiredCredentialModel model = initRequiredCredentialModel(type); - addRequiredCredential(model); - } - - @Override - public void addRequiredOAuthClientCredential(String type) { - RequiredCredentialModel model = initRequiredCredentialModel(type); - addRequiredOAuthClientCredential(model); - } - - @Override - public void addRequiredResourceCredential(String type) { - RequiredCredentialModel model = initRequiredCredentialModel(type); - addRequiredApplicationCredential(model); - } - - 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 boolean validatePassword(UserModel user, String password) { - UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getLoginName(), new Password(password)); - getIdm().validateCredentials(creds); - return creds.getStatus() == Credentials.Status.VALID; - } - - @Override - public boolean validateTOTP(UserModel user, String password, String token) { - TOTPCredentials creds = new TOTPCredentials(); - creds.setToken(token); - creds.setUsername(user.getLoginName()); - creds.setPassword(new Password(password)); - getIdm().validateCredentials(creds); - return creds.getStatus() == Credentials.Status.VALID; - } - - @Override - public void updateCredential(UserModel user, UserCredentialModel cred) { - IdentityManager idm = getIdm(); - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - Password password = new Password(cred.getValue()); - idm.updateCredential(((UserAdapter)user).getUser(), password); - } else if (cred.getType().equals(UserCredentialModel.TOTP)) { - TOTPCredential totp = new TOTPCredential(cred.getValue()); - totp.setDevice(cred.getDevice()); - idm.updateCredential(((UserAdapter)user).getUser(), totp); - } else if (cred.getType().equals(UserCredentialModel.CLIENT_CERT)) { - X509Certificate cert = null; - try { - cert = PemUtils.decodeCertificate(cred.getValue()); - } catch (Exception e) { - throw new RuntimeException(e); - } - X509CertificateCredentials creds = new X509CertificateCredentials(cert); - idm.updateCredential(((UserAdapter)user).getUser(), creds); - } - } - - @Override - public UserAdapter getUser(String name) { - User user = findPicketlinkUser(name); - if (user == null) return null; - return new UserAdapter(user, getIdm()); - } - - @Override - public UserModel getUserByEmail(String email) { - IdentityQuery query = getIdm().createIdentityQuery(User.class); - query.setParameter(User.EMAIL, email); - List users = query.getResultList(); - return users.isEmpty() ? null : new UserAdapter(users.get(0), getIdm()); - } - - protected User findPicketlinkUser(String name) { - return SampleModel.getUser(getIdm(), name); - } - - @Override - public UserAdapter addUser(String username) { - User user = findPicketlinkUser(username); - if (user != null) throw new IllegalStateException("User already exists"); - user = new User(username); - getIdm().add(user); - UserAdapter userModel = new UserAdapter(user, getIdm()); - - for (String r : getDefaultRoles()) { - grantRole(userModel, getRole(r)); - } - - for (ApplicationModel application : getApplications()) { - for (String r : application.getDefaultRoles()) { - application.grantRole(userModel, application.getRole(r)); - } - } - - return userModel; - } - - @Override - public boolean removeUser(String name) { - User user = findPicketlinkUser(name); - if (user == null) { - return false; - } - getIdm().remove(user); - return true; - } - - @Override - public RoleAdapter getRole(String name) { - Role role = SampleModel.getRole(getIdm(), name); - if (role == null) return null; - return new RoleAdapter(role, getIdm()); - } - - @Override - public RoleModel getRoleById(String id) { - IdentityQuery query = getIdm().createIdentityQuery(Role.class); - query.setParameter(IdentityType.ID, id); - List roles = query.getResultList(); - if (roles.size() == 0) return null; - return new RoleAdapter(roles.get(0), getIdm()); - } - - @Override - public RoleAdapter addRole(String name) { - Role role = new Role(name); - getIdm().add(role); - return new RoleAdapter(role, getIdm()); - } - - @Override - public boolean removeRoleById(String id) { - try { - getIdm().remove(getIdm().lookupIdentityById(Role.class, id)); - return true; - } catch (IdentityManagementException e) { - return false; - } - } - - @Override - public List getRoles() { - IdentityManager idm = getIdm(); - IdentityQuery query = idm.createIdentityQuery(Role.class); - query.setParameter(Role.PARTITION, realm); - List roles = query.getResultList(); - List roleModels = new ArrayList(); - for (Role role : roles) { - roleModels.add(new RoleAdapter(role, idm)); - } - return roleModels; - } - - - /** - * Key name, value resource - * - * @return - */ - @Override - public Map getApplicationNameMap() { - Map resourceMap = new HashMap(); - for (ApplicationModel resource : getApplications()) { - resourceMap.put(resource.getName(), resource); - } - return resourceMap; - } - - /** - * Makes sure that the resource returned is owned by the realm - * - * @return - */ - @Override - public ApplicationModel getApplicationById(String id) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ApplicationRelationship.class); - query.setParameter(ApplicationRelationship.REALM, realm.getName()); - query.setParameter(ApplicationRelationship.APPLICATION, id); - List results = query.getResultList(); - if (results.size() == 0) return null; - ApplicationData resource = partitionManager.getPartition(ApplicationData.class, id); - ApplicationModel model = new ApplicationAdapter(resource, this, partitionManager); - return model; - } - - @Override - public ApplicationModel getApplicationByName(String name) { - return getApplicationNameMap().get(name); - } - - - - @Override - public List getApplications() { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ApplicationRelationship.class); - query.setParameter(ApplicationRelationship.REALM, realm.getName()); - List results = query.getResultList(); - List resources = new ArrayList(); - for (ApplicationRelationship relationship : results) { - ApplicationData resource = partitionManager.getPartition(ApplicationData.class, relationship.getApplication()); - ApplicationModel model = new ApplicationAdapter(resource, this, partitionManager); - resources.add(model); - } - - return resources; - } - - @Override - public ApplicationModel addApplication(String name) { - ApplicationData applicationData = new ApplicationData(IdGenerator.generateId()); - User resourceUser = new User(name); - idm.add(resourceUser); - applicationData.setResourceUser(resourceUser); - applicationData.setResourceName(name); - partitionManager.add(applicationData); - ApplicationRelationship resourceRelationship = new ApplicationRelationship(); - resourceRelationship.setRealm(realm.getName()); - resourceRelationship.setApplication(applicationData.getName()); - getRelationshipManager().add(resourceRelationship); - ApplicationModel resource = new ApplicationAdapter(applicationData, this, partitionManager); - return resource; - } - - @Override - public boolean removeApplication(String id) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ApplicationRelationship.class); - query.setParameter(ApplicationRelationship.REALM, realm.getName()); - query.setParameter(ApplicationRelationship.APPLICATION, id); - List results = query.getResultList(); - if (results.size() == 0) return false; - ApplicationRelationship relationship = results.get(0); - ApplicationData application = partitionManager.getPartition(ApplicationData.class, relationship.getApplication()); - partitionManager.remove(application); - return true; - } - - @Override - public boolean hasRole(UserModel user, RoleModel role) { - return SampleModel.hasRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); - } - - @Override - public boolean hasRole(UserModel user, String role) { - RoleModel roleModel = getRole(role); - return hasRole(user, roleModel); - } - - - @Override - public void grantRole(UserModel user, RoleModel role) { - SampleModel.grantRole(getRelationshipManager(), ((UserAdapter) user).getUser(), ((RoleAdapter) role).getRole()); - } - - @Override - public void deleteRoleMapping(UserModel user, RoleModel role) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(Grant.class); - query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); - query.setParameter(Grant.ROLE, ((RoleAdapter)role).getRole()); - List grants = query.getResultList(); - for (Grant grant : grants) { - getRelationshipManager().remove(grant); - } - } - - @Override - public Set getRoleMappingValues(UserModel user) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(Grant.class); - query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); - List grants = query.getResultList(); - HashSet set = new HashSet(); - for (Grant grant : grants) { - if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(grant.getRole().getName()); - } - return set; - } - - @Override - public List getRoleMappings(UserModel user) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(Grant.class); - query.setParameter(Grant.ASSIGNEE, ((UserAdapter)user).getUser()); - List grants = query.getResultList(); - List set = new ArrayList(); - for (Grant grant : grants) { - if (grant.getRole().getPartition().getId().equals(realm.getId())) set.add(new RoleAdapter(grant.getRole(), getIdm())); - } - return set; - } - - @Override - public void addScopeMapping(UserModel agent, String roleName) { - IdentityManager idm = getIdm(); - Role role = SampleModel.getRole(idm, roleName); - if (role == null) throw new RuntimeException("role not found"); - ScopeRelationship scope = new ScopeRelationship(); - scope.setClient(((UserAdapter)agent).getUser()); - scope.setScope(role); - getRelationshipManager().add(scope); - } - - @Override - public void addScopeMapping(UserModel agent, RoleModel role) { - ScopeRelationship scope = new ScopeRelationship(); - scope.setClient(((UserAdapter) agent).getUser()); - scope.setScope(((RoleAdapter)role).getRole()); - getRelationshipManager().add(scope); - } - - @Override - public void deleteScopeMapping(UserModel user, RoleModel role) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); - query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)user).getUser()); - query.setParameter(ScopeRelationship.SCOPE, ((RoleAdapter)role).getRole()); - List grants = query.getResultList(); - for (ScopeRelationship grant : grants) { - getRelationshipManager().remove(grant); - } - } - - @Override - public OAuthClientModel addOAuthClient(String name) { - User client = new User(name); - getIdm().add(client); - OAuthClientRelationship rel = new OAuthClientRelationship(); - rel.setOauthAgent(client); - rel.setRealm(realm.getName()); - getRelationshipManager().add(rel); - return new OAuthClientAdapter(rel, getIdm(), getRelationshipManager()); - } - - @Override - public boolean removeOAuthClient(String id) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(OAuthClientRelationship.class); - query.setParameter(OAuthClientRelationship.REALM, realm.getName()); - query.setParameter(OAuthClientRelationship.ID, id); - List results = query.getResultList(); - if (results.size() == 0) return false; - OAuthClientRelationship relationship = results.get(0); - getRelationshipManager().remove(relationship); - return true; - } - - - @Override - public OAuthClientModel getOAuthClient(String name) { - User user = findPicketlinkUser(name); - if (user == null) return null; - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(OAuthClientRelationship.class); - query.setParameter(OAuthClientRelationship.OAUTH_AGENT, user); - List results = query.getResultList(); - if (results.size() == 0) return null; - return new OAuthClientAdapter(results.get(0), getIdm(), getRelationshipManager()); - } - - @Override - public OAuthClientModel getOAuthClientById(String id) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(OAuthClientRelationship.class); - query.setParameter(OAuthClientRelationship.REALM, realm.getName()); - query.setParameter(OAuthClientRelationship.ID, id); - List results = query.getResultList(); - if (results.size() == 0) return null; - return new OAuthClientAdapter(results.get(0), getIdm(), getRelationshipManager()); - } - - - @Override - public List getOAuthClients() { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(OAuthClientRelationship.class); - query.setParameter(OAuthClientRelationship.REALM, realm.getName()); - List results = query.getResultList(); - List list = new ArrayList(); - for (OAuthClientRelationship rel : results) { - list.add(new OAuthClientAdapter(rel, getIdm(), getRelationshipManager())); - } - return list; - } - - @Override - public List getScopeMappings(UserModel agent) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); - query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)agent).getUser()); - List scope = query.getResultList(); - List roles = new ArrayList(); - for (ScopeRelationship rel : scope) { - if (rel.getScope().getPartition().getId().equals(realm.getId())) roles.add(new RoleAdapter(rel.getScope(), getIdm())); - } - return roles; - } - - @Override - public Set getScopeMappingValues(UserModel agent) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(ScopeRelationship.class); - query.setParameter(ScopeRelationship.CLIENT, ((UserAdapter)agent).getUser()); - List scope = query.getResultList(); - HashSet set = new HashSet(); - for (ScopeRelationship rel : scope) { - if (rel.getScope().getPartition().getId().equals(realm.getId())) set.add(rel.getScope().getName()); - } - return set; - } - - @Override - public List getDefaultRoles() { - if (realm.getDefaultRoles() == null) return Collections.emptyList(); - List list = new ArrayList(); - for (String role : realm.getDefaultRoles()) { - RoleModel model = getRole(role); - if (model == null) throw new RuntimeException("default role missing"); - list.add(role); - } - return list; - } - - @Override - public void addDefaultRole(String name) { - if (getRole(name) == null) { - addRole(name); - } - - String[] defaultRoles = realm.getDefaultRoles(); - if (defaultRoles == null) { - defaultRoles = new String[1]; - } else { - defaultRoles = Arrays.copyOf(defaultRoles, defaultRoles.length + 1); - } - defaultRoles[defaultRoles.length - 1] = name; - - realm.setDefaultRoles(defaultRoles); - updateRealm(); - } - - @Override - public void updateDefaultRoles(String[] defaultRoles) { - for (String name : defaultRoles) { - if (getRole(name) == null) { - addRole(name); - } - } - - realm.setDefaultRoles(defaultRoles); - updateRealm(); - } - - @Override - public UserModel getUserBySocialLink(SocialLinkModel socialLink) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(SocialLinkRelationship.class); - query.setParameter(SocialLinkRelationship.SOCIAL_PROVIDER, socialLink.getSocialProvider()); - query.setParameter(SocialLinkRelationship.SOCIAL_USERNAME, socialLink.getSocialUserId()); - query.setParameter(SocialLinkRelationship.REALM, realm.getName()); - List results = query.getResultList(); - if (results.isEmpty()) { - return null; - } else if (results.size() > 1) { - throw new IllegalStateException("More results found for socialProvider=" + socialLink.getSocialProvider() + - ", socialUserId=" + socialLink.getSocialUserId() + ", results=" + results); - } else { - User user = results.get(0).getUser(); - return new UserAdapter(user, getIdm()); - } - } - - @Override - public Set getSocialLinks(UserModel user) { - RelationshipQuery query = getRelationshipManager().createRelationshipQuery(SocialLinkRelationship.class); - query.setParameter(SocialLinkRelationship.USER, ((UserAdapter) user).getUser()); - List plSocialLinks = query.getResultList(); - - Set results = new HashSet(); - for (SocialLinkRelationship relationship : plSocialLinks) { - results.add(new SocialLinkModel(relationship.getSocialProvider(), relationship.getSocialUserId())); - } - return results; - } - - @Override - public void addSocialLink(UserModel user, SocialLinkModel socialLink) { - SocialLinkRelationship relationship = new SocialLinkRelationship(); - relationship.setUser(((UserAdapter)user).getUser()); - relationship.setSocialProvider(socialLink.getSocialProvider()); - relationship.setSocialUserId(socialLink.getSocialUserId()); - relationship.setRealm(realm.getName()); - - getRelationshipManager().add(relationship); - } - - @Override - public void removeSocialLink(UserModel user, SocialLinkModel socialLink) { - SocialLinkRelationship relationship = new SocialLinkRelationship(); - relationship.setUser(((UserAdapter)user).getUser()); - relationship.setSocialProvider(socialLink.getSocialProvider()); - relationship.setSocialUserId(socialLink.getSocialUserId()); - relationship.setRealm(realm.getName()); - - getRelationshipManager().remove(relationship); - } - - @Override - public List getUsers() { - List userModels = new ArrayList(); - IdentityQuery query = getIdm().createIdentityQuery(User.class); - for (User u : query.getResultList()) { - userModels.add(new UserAdapter(u, idm)); - } - return userModels; - } - - @Override - public List searchForUser(String search) { - QueryParameter[] params = new QueryParameter[] { User.LOGIN_NAME, User.FIRST_NAME, User.LAST_NAME, User.EMAIL }; - - List userModels = new ArrayList(); - for (QueryParameter p : params) { - IdentityQuery query = getIdm().createIdentityQuery(User.class); - query.setParameter(p, search.toLowerCase()); - for (User u : query.getResultList()) { - userModels.add(new UserAdapter(u, idm)); - } - } - return userModels; - } - - @Override - public List searchForUserByAttributes(Map attributes) { - IdentityQuery query = getIdm().createIdentityQuery(User.class); - for (Map.Entry entry : attributes.entrySet()) { - if (entry.getKey().equals(UserModel.LOGIN_NAME)) { - query.setParameter(User.LOGIN_NAME, entry.getValue()); - } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) { - query.setParameter(User.FIRST_NAME, entry.getValue()); - - } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) { - query.setParameter(User.LAST_NAME, entry.getValue()); - - } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) { - query.setParameter(User.EMAIL, entry.getValue()); - } - } - List users = query.getResultList(); - List userModels = new ArrayList(); - for (User user : users) { - userModels.add(new UserAdapter(user, idm)); - } - return userModels; - } - - @Override - public Map getSmtpConfig() { - return realm.getSmtpConfig(); - } - - @Override - public void setSmtpConfig(Map smtpConfig) { - realm.setSmtpConfig(smtpConfig); - updateRealm(); - } - - @Override - public Map getSocialConfig() { - return realm.getSocialConfig(); - } - - @Override - public void setSocialConfig(Map socialConfig) { - realm.setSocialConfig(socialConfig); - updateRealm(); - } - - @Override - public PasswordPolicy getPasswordPolicy() { - if (passwordPolicy == null) { - passwordPolicy = new PasswordPolicy(realm.getPasswordPolicy()); - } - return passwordPolicy; - } - - @Override - public void setPasswordPolicy(PasswordPolicy policy) { - this.passwordPolicy = policy; - realm.setPasswordPolicy(policy.toString()); - updateRealm(); - } - - @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(); - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/RoleAdapter.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/RoleAdapter.java deleted file mode 100755 index efe14037f9..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/RoleAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.RoleModel; -import org.picketlink.idm.IdentityManager; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.sample.Role; - -import java.io.Serializable; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RoleAdapter implements RoleModel { - protected Role role; - protected IdentityManager idm; - - public RoleAdapter(Role role, IdentityManager idm) { - this.role = role; - this.idm = idm; - } - - protected Role getRole() { - return role; - } - - @Override - public String getId() { - return role.getId(); - } - - @Override - public String getName() { - return role.getName(); - } - - @Override - public void setName(String name) { - role.setName(name); - idm.update(role); - } - - @Override - public String getDescription() { - Attribute description = role.getAttribute("description"); - if (description == null) return null; - return (String) description.getValue(); - } - - @Override - public void setDescription(String description) { - if (description == null) { - role.removeAttribute("description"); - } else { - role.setAttribute(new Attribute("description", description)); - } - idm.update(role); - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/UserAdapter.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/UserAdapter.java deleted file mode 100755 index 2555f74d5b..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/UserAdapter.java +++ /dev/null @@ -1,249 +0,0 @@ -package org.keycloak.models.picketlink; - -import org.keycloak.models.UserModel; -import org.picketlink.idm.IdentityManager; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.sample.User; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class UserAdapter implements UserModel { - private static final String EMAIL_VERIFIED_ATTR = "emailVerified"; - private static final String KEYCLOAK_TOTP_ATTR = "totpEnabled"; - private static final String REQUIRED_ACTIONS_ATTR = "requiredActions"; - - private static final String REDIRECT_URIS = "redirectUris"; - private static final String WEB_ORIGINS = "webOrigins"; - - protected User user; - protected IdentityManager idm; - - public UserAdapter(User user, IdentityManager idm) { - this.user = user; - this.idm = idm; - } - - protected User getUser() { - return user; - } - - @Override - public String getLoginName() { - return user.getLoginName(); - } - - @Override - public boolean isEnabled() { - return user.isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - user.setEnabled(enabled); - idm.update(user); - } - - @Override - public String getFirstName() { - return user.getFirstName(); - } - - @Override - public void setFirstName(String firstName) { - user.setFirstName(firstName); - idm.update(user); - } - - @Override - public String getLastName() { - return user.getLastName(); - } - - @Override - public void setLastName(String lastName) { - user.setLastName(lastName); - idm.update(user); - } - - @Override - public String getEmail() { - return user.getEmail(); - } - - @Override - public void setEmail(String email) { - user.setEmail(email); - idm.update(user); - } - - @Override - public boolean isEmailVerified() { - Attribute a = user.getAttribute(EMAIL_VERIFIED_ATTR); - return a != null ? a.getValue() : false; - } - - @Override - public void setEmailVerified(boolean verified) { - user.setAttribute(new Attribute(EMAIL_VERIFIED_ATTR, verified)); - idm.update(user); - } - - @Override - public void setAttribute(String name, String value) { - user.setAttribute(new Attribute(name, value)); - idm.update(user); - } - - @Override - public void removeAttribute(String name) { - user.removeAttribute(name); - idm.update(user); - } - - @Override - public String getAttribute(String name) { - Attribute attribute = user.getAttribute(name); - if (attribute == null || attribute.getValue() == null) - return null; - return attribute.getValue().toString(); - } - - @Override - public Map getAttributes() { - Map attributes = new HashMap(); - for (Attribute attribute : user.getAttributes()) { - if (attribute.getValue() != null) - attributes.put(attribute.getName(), attribute.getValue().toString()); - } - return attributes; - } - - @Override - public Set getRequiredActions() { - return getAttributeSet(REQUIRED_ACTIONS_ATTR); - } - - @Override - public void addRequiredAction(RequiredAction action) { - addToAttributeSet(REQUIRED_ACTIONS_ATTR, action); - } - - @Override - public void removeRequiredAction(RequiredAction action) { - removeFromAttributeSet(REQUIRED_ACTIONS_ATTR, action); - } - - @Override - public Set getRedirectUris() { - return getAttributeSet(REDIRECT_URIS); - } - - @Override - public void setRedirectUris(Set redirectUris) { - setAttributeSet(REDIRECT_URIS, redirectUris); - } - - @Override - public void addRedirectUri(String redirectUri) { - addToAttributeSet(REDIRECT_URIS, redirectUri); - } - - @Override - public void removeRedirectUri(String redirectUri) { - removeFromAttributeSet(REDIRECT_URIS, redirectUri); - } - - @Override - public Set getWebOrigins() { - return getAttributeSet(WEB_ORIGINS); - } - - @Override - public void setWebOrigins(Set webOrigins) { - setAttributeSet(WEB_ORIGINS, webOrigins); - } - - @Override - public void addWebOrigin(String webOrigin) { - addToAttributeSet(WEB_ORIGINS, webOrigin); - } - - @Override - public void removeWebOrigin(String webOrigin) { - removeFromAttributeSet(WEB_ORIGINS, webOrigin); - } - - @Override - public boolean isTotp() { - Attribute a = user.getAttribute(KEYCLOAK_TOTP_ATTR); - return a != null ? a.getValue() : false; - } - - @Override - public void setTotp(boolean totp) { - user.setAttribute(new Attribute(KEYCLOAK_TOTP_ATTR, totp)); - idm.update(user); - } - - @SuppressWarnings("unchecked") - private Set getAttributeSet(String name) { - Attribute a = user.getAttribute(name); - - Set s = new HashSet(); - - if (a != null) { - Serializable o = a.getValue(); - if (o instanceof Serializable[]) { - for (Serializable t : (Serializable[]) o) { - s.add(t); - } - } else { - s.add(o); - } - } - - return (Set) s; - } - - private void setAttributeSet(String name, Set set) { - if (set.isEmpty()) { - user.removeAttribute(name); - } else { - user.setAttribute(new Attribute(name, set.toArray(new Serializable[set.size()]))); - } - idm.update(user); - } - - private void addToAttributeSet(String name, T t) { - Set set = getAttributeSet(name); - if (set == null) { - set = new HashSet(); - } - - if (set.add(t)) { - setAttributeSet(name, set); - idm.update(user); - } - } - - private void removeFromAttributeSet(String name, T t) { - Set set = getAttributeSet(name); - if (set == null) { - return; - } - - if (set.remove(t)) { - setAttributeSet(name, set); - idm.update(user); - } - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationData.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationData.java deleted file mode 100755 index ec4b4e7aca..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationData.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.keycloak.models.picketlink.mappings; - -import org.picketlink.idm.model.AbstractPartition; -import org.picketlink.idm.model.annotation.AttributeProperty; -import org.picketlink.idm.model.sample.User; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class ApplicationData extends AbstractPartition { - private String resourceName; - private boolean enabled; - private boolean surrogateAuthRequired; - private String managementUrl; - private String baseUrl; - private User resourceUser; - private String[] defaultRoles; - - public ApplicationData() { - super(null); - } - public ApplicationData(String name) { - super(name); - } - - @AttributeProperty - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public User getResourceUser() { - return resourceUser; - } - - public void setResourceUser(User resourceUser) { - this.resourceUser = resourceUser; - } - - @AttributeProperty - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - @AttributeProperty - public boolean isSurrogateAuthRequired() { - return surrogateAuthRequired; - } - - public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { - this.surrogateAuthRequired = surrogateAuthRequired; - } - - @AttributeProperty - public String getBaseUrl() { - return baseUrl; - } - - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - } - - @AttributeProperty - public String getManagementUrl() { - return managementUrl; - } - - public void setManagementUrl(String managementUrl) { - this.managementUrl = managementUrl; - } - - @AttributeProperty - public String[] getDefaultRoles() { - return defaultRoles; - } - - public void setDefaultRoles(String[] defaultRoles) { - this.defaultRoles = defaultRoles; - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationEntity.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationEntity.java deleted file mode 100755 index 8e450a72e7..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/ApplicationEntity.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.keycloak.models.picketlink.mappings; - -import org.picketlink.idm.jpa.annotations.AttributeValue; -import org.picketlink.idm.jpa.annotations.OwnerReference; -import org.picketlink.idm.jpa.annotations.entity.IdentityManaged; -import org.picketlink.idm.jpa.model.sample.simple.AccountTypeEntity; -import org.picketlink.idm.jpa.model.sample.simple.PartitionTypeEntity; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import java.io.Serializable; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -@IdentityManaged(ApplicationData.class) -@Entity -public class ApplicationEntity implements Serializable { - @OneToOne - @Id - @OwnerReference - private PartitionTypeEntity partitionTypeEntity; - - @AttributeValue - private String resourceName; - @AttributeValue - private boolean enabled; - @AttributeValue - private boolean surrogateAuthRequired; - @AttributeValue - private String managementUrl; - @AttributeValue - private String baseUrl; - - @AttributeValue - private String[] defaultRoles; - - @OneToOne - @AttributeValue - AccountTypeEntity resourceUser; - - - public PartitionTypeEntity getPartitionTypeEntity() { - return partitionTypeEntity; - } - - public void setPartitionTypeEntity(PartitionTypeEntity partitionTypeEntity) { - this.partitionTypeEntity = partitionTypeEntity; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String realmName) { - this.resourceName = realmName; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - 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 AccountTypeEntity getResourceUser() { - return resourceUser; - } - - public void setResourceUser(AccountTypeEntity resourceUser) { - this.resourceUser = resourceUser; - } - - public String[] getDefaultRoles() { - return defaultRoles; - } - - public void setDefaultRoles(String[] defaultRoles) { - this.defaultRoles = defaultRoles; - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmData.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmData.java deleted file mode 100755 index 497add81c8..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmData.java +++ /dev/null @@ -1,208 +0,0 @@ -package org.keycloak.models.picketlink.mappings; - -import org.picketlink.idm.model.AbstractPartition; -import org.picketlink.idm.model.annotation.AttributeProperty; - -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RealmData extends AbstractPartition { - private String realmName; - private boolean enabled; - private boolean sslNotRequired; - private boolean registrationAllowed; - private boolean verifyEmail; - private boolean resetPasswordAllowed; - private boolean social; - private boolean updateProfileOnInitialSocialLogin; - private int tokenLifespan; - private int accessCodeLifespan; - private int accessCodeLifespanUserAction; - private String publicKeyPem; - private String privateKeyPem; - private String[] defaultRoles; - private Map smtpConfig; - private Map socialConfig; - private String passwordPolicy; - private String loginTheme; - private String accountTheme; - - public RealmData() { - super(null); - } - public RealmData(String name) { - super(name); - } - - @AttributeProperty - public String getRealmName() { - return realmName; - } - - public void setRealmName(String realmName) { - this.realmName = realmName; - } - - @AttributeProperty - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - @AttributeProperty - public boolean isSocial() { - return social; - } - - public void setSocial(boolean social) { - this.social = social; - } - - @AttributeProperty - public boolean isUpdateProfileOnInitialSocialLogin() { - return updateProfileOnInitialSocialLogin; - } - - public void setUpdateProfileOnInitialSocialLogin(boolean updateProfileOnInitialSocialLogin) { - this.updateProfileOnInitialSocialLogin = updateProfileOnInitialSocialLogin; - } - - @AttributeProperty - public boolean isSslNotRequired() { - return sslNotRequired; - } - - public void setSslNotRequired(boolean sslNotRequired) { - this.sslNotRequired = sslNotRequired; - } - - @AttributeProperty - public boolean isRegistrationAllowed() { - return registrationAllowed; - } - - public void setRegistrationAllowed(boolean registrationAllowed) { - this.registrationAllowed = registrationAllowed; - } - - public boolean isVerifyEmail() { - return verifyEmail; - } - - public void setVerifyEmail(boolean verifyEmail) { - this.verifyEmail = verifyEmail; - } - - public boolean isResetPasswordAllowed() { - return resetPasswordAllowed; - } - - public void setResetPasswordAllowed(boolean resetPassword) { - this.resetPasswordAllowed = resetPassword; - } - - @AttributeProperty - public int getTokenLifespan() { - return tokenLifespan; - } - - public void setTokenLifespan(int tokenLifespan) { - this.tokenLifespan = tokenLifespan; - } - - @AttributeProperty - public int getAccessCodeLifespan() { - return accessCodeLifespan; - } - - public void setAccessCodeLifespan(int accessCodeLifespan) { - this.accessCodeLifespan = accessCodeLifespan; - } - - @AttributeProperty - public int getAccessCodeLifespanUserAction() { - return accessCodeLifespanUserAction; - } - - public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { - this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; - } - - @AttributeProperty - public String getPublicKeyPem() { - return publicKeyPem; - } - - public void setPublicKeyPem(String publicKeyPem) { - this.publicKeyPem = publicKeyPem; - } - - @AttributeProperty - public String getPrivateKeyPem() { - return privateKeyPem; - } - - public void setPrivateKeyPem(String privateKeyPem) { - this.privateKeyPem = privateKeyPem; - } - - @AttributeProperty - public String[] getDefaultRoles() { - return defaultRoles; - } - - public void setDefaultRoles(String[] defaultRoles) { - this.defaultRoles = defaultRoles; - } - - @AttributeProperty - public Map getSmtpConfig() { - return smtpConfig; - } - - public void setSmtpConfig(Map smtpConfig) { - this.smtpConfig = smtpConfig; - } - - @AttributeProperty - public Map getSocialConfig() { - return socialConfig; - } - - public void setSocialConfig(Map socialConfig) { - this.socialConfig = socialConfig; - } - - @AttributeProperty - public String getPasswordPolicy() { - return passwordPolicy; - } - - public void setPasswordPolicy(String passwordPolicy) { - this.passwordPolicy = passwordPolicy; - } - - @AttributeProperty - public String getLoginTheme() { - return loginTheme; - } - - public void setLoginTheme(String theme) { - this.loginTheme = theme; - } - - @AttributeProperty - public String getAccountTheme() { - return accountTheme; - } - - public void setAccountTheme(String theme) { - this.accountTheme = theme; - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmEntity.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmEntity.java deleted file mode 100755 index 4b6abb6a7c..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/mappings/RealmEntity.java +++ /dev/null @@ -1,204 +0,0 @@ -package org.keycloak.models.picketlink.mappings; - -import org.picketlink.idm.jpa.annotations.AttributeValue; -import org.picketlink.idm.jpa.annotations.OwnerReference; -import org.picketlink.idm.jpa.annotations.entity.IdentityManaged; -import org.picketlink.idm.jpa.model.sample.simple.PartitionTypeEntity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.OneToOne; -import java.io.Serializable; -import java.util.HashMap; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -@IdentityManaged(RealmData.class) -@Entity -public class RealmEntity implements Serializable { - @OneToOne - @Id - @OwnerReference - private PartitionTypeEntity partitionTypeEntity; - - - @AttributeValue - private String realmName; - @AttributeValue - private boolean enabled; - @AttributeValue - private boolean sslNotRequired; - @AttributeValue - private boolean registrationAllowed; - @AttributeValue - private boolean verifyEmail; - @AttributeValue - private boolean resetPasswordAllowed; - @AttributeValue - private boolean social; - @AttributeValue - private boolean updateProfileOnInitialSocialLogin; - @AttributeValue - private int tokenLifespan; - @AttributeValue - private int accessCodeLifespan; - @AttributeValue - private int accessCodeLifespanUserAction; - @AttributeValue - @Column(length = 2048) - private String publicKeyPem; - @AttributeValue - @Column(length = 2048) - private String privateKeyPem; - @AttributeValue - private String[] defaultRoles; - @AttributeValue - @Lob - private HashMap smtpConfig; - @AttributeValue - @Lob - private HashMap socialConfig; - @AttributeValue - private String theme; - - - public PartitionTypeEntity getPartitionTypeEntity() { - return partitionTypeEntity; - } - - public void setPartitionTypeEntity(PartitionTypeEntity partitionTypeEntity) { - this.partitionTypeEntity = partitionTypeEntity; - } - - public String getRealmName() { - return realmName; - } - - public void setRealmName(String realmName) { - this.realmName = realmName; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isSslNotRequired() { - return sslNotRequired; - } - - public void setSslNotRequired(boolean sslNotRequired) { - this.sslNotRequired = sslNotRequired; - } - - public boolean isRegistrationAllowed() { - return registrationAllowed; - } - - public void setRegistrationAllowed(boolean registrationAllowed) { - this.registrationAllowed = registrationAllowed; - } - - public boolean isVerifyEmail() { - return verifyEmail; - } - - public void setVerifyEmail(boolean verifyEmail) { - this.verifyEmail = verifyEmail; - } - - public boolean isResetPasswordAllowed() { - return resetPasswordAllowed; - } - - public void setResetPasswordAllowed(boolean resetPassword) { - this.resetPasswordAllowed = resetPassword; - } - - public boolean isSocial() { - return social; - } - - public void setSocial(boolean social) { - this.social = social; - } - - public boolean isUpdateProfileOnInitialSocialLogin() { - return updateProfileOnInitialSocialLogin; - } - - public void setUpdateProfileOnInitialSocialLogin(boolean updateProfileOnInitialSocialLogin) { - this.updateProfileOnInitialSocialLogin = updateProfileOnInitialSocialLogin; - } - - public int getTokenLifespan() { - return tokenLifespan; - } - - public void setTokenLifespan(int tokenLifespan) { - this.tokenLifespan = tokenLifespan; - } - - 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 String getPublicKeyPem() { - return publicKeyPem; - } - - public void setPublicKeyPem(String publicKeyPem) { - this.publicKeyPem = publicKeyPem; - } - - public String getPrivateKeyPem() { - return privateKeyPem; - } - - public void setPrivateKeyPem(String privateKeyPem) { - this.privateKeyPem = privateKeyPem; - } - - public HashMap getSmtpConfig() { - return smtpConfig; - } - - public void setSmtpConfig(HashMap smtpConfig) { - this.smtpConfig = smtpConfig; - } - - public HashMap getSocialConfig() { - return socialConfig; - } - - public void setSocialConfig(HashMap socialConfig) { - this.socialConfig = socialConfig; - } - - public String getTheme() { - return theme; - } - - public void setTheme(String theme) { - this.theme = theme; - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ApplicationRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ApplicationRelationship.java deleted file mode 100755 index 679e761b25..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ApplicationRelationship.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.model.annotation.AttributeProperty; -import org.picketlink.idm.query.AttributeParameter; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class ApplicationRelationship extends AbstractAttributedType implements Relationship { - private static final long serialVersionUID = 1L; - - public static final AttributeParameter REALM = new AttributeParameter("realm"); - public static final AttributeParameter APPLICATION = new AttributeParameter("application"); - - public ApplicationRelationship() { - } - - @AttributeProperty - public String getRealm() { - return (String)getAttribute("realm").getValue(); - } - - public void setRealm(String realm) { - setAttribute(new Attribute("realm", realm)); - } - - - @AttributeProperty - public String getApplication() { - return (String)getAttribute("application").getValue(); - } - - public void setApplication(String app) { - setAttribute(new Attribute("application", app)); - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRelationship.java deleted file mode 100755 index a42536e949..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRelationship.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.model.annotation.AttributeProperty; -import org.picketlink.idm.model.sample.User; -import org.picketlink.idm.query.AttributeParameter; -import org.picketlink.idm.query.RelationshipQueryParameter; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class OAuthClientRelationship extends AbstractAttributedType implements Relationship { - private static final long serialVersionUID = 1L; - - public static final AttributeParameter REALM = new AttributeParameter("realm"); - public static final RelationshipQueryParameter OAUTH_AGENT = new RelationshipQueryParameter() { - - @Override - public String getName() { - return "oauthAgent"; - } - }; - protected User oauthAgent; - - - public OAuthClientRelationship() { - } - - public String getRealm() { - return (String)getAttribute("realm").getValue(); - } - - public void setRealm(String realm) { - setAttribute(new Attribute("realm", realm)); - } - - public User getOauthAgent() { - return oauthAgent; - } - - public void setOauthAgent(User oauthAgent) { - this.oauthAgent = oauthAgent; - } - - @AttributeProperty - public String getBaseUrl() { - return (String)getAttribute("baseUrl").getValue(); - } - - public void setBaseUrl(String base) { - setAttribute(new Attribute("baseUrl", base)); - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRequiredCredentialRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRequiredCredentialRelationship.java deleted file mode 100755 index 441b2106e8..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/OAuthClientRequiredCredentialRelationship.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class OAuthClientRequiredCredentialRelationship extends RequiredCredentialRelationship { -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmAdminRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmAdminRelationship.java deleted file mode 100755 index 1a8de46cd9..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmAdminRelationship.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.model.sample.User; -import org.picketlink.idm.query.AttributeParameter; -import org.picketlink.idm.query.RelationshipQueryParameter; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RealmAdminRelationship extends AbstractAttributedType implements Relationship { - private static final long serialVersionUID = 1L; - - public static final AttributeParameter REALM = new AttributeParameter("realm"); - - public static final RelationshipQueryParameter ADMIN = new RelationshipQueryParameter() { - - @Override - public String getName() { - return "admin"; - } - }; - - //protected String realm; - protected User admin; - - public String getRealm() { - return (String)getAttribute("realm").getValue(); - } - - public void setRealm(String realm) { - setAttribute(new Attribute("realm", realm)); - } - - public User getAdmin() { - return admin; - } - - public void setAdmin(User admin) { - this.admin = admin; - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmListingRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmListingRelationship.java deleted file mode 100755 index bb4856a695..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RealmListingRelationship.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.query.AttributeParameter; - -/** - * Picketlink doesn't allow you to query for all partitions, thus this stupid relationship... - * - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RealmListingRelationship extends AbstractAttributedType implements Relationship { - private static final long serialVersionUID = 1L; - - public static final AttributeParameter REALM = new AttributeParameter("realm"); - - public String getRealm() { - return (String)getAttribute("realm").getValue(); - } - - public void setRealm(String realm) { - setAttribute(new Attribute("realm", realm)); - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredApplicationCredentialRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredApplicationCredentialRelationship.java deleted file mode 100755 index f811e1243f..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredApplicationCredentialRelationship.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RequiredApplicationCredentialRelationship extends RequiredCredentialRelationship { -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredCredentialRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredCredentialRelationship.java deleted file mode 100755 index 03dfa5e18f..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/RequiredCredentialRelationship.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.model.annotation.AttributeProperty; -import org.picketlink.idm.query.AttributeParameter; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class RequiredCredentialRelationship extends AbstractAttributedType implements Relationship { - private static final long serialVersionUID = 1L; - - public static final AttributeParameter REALM = new AttributeParameter("realm"); - - - //protected String realm; - //protected String credentialType; - //protected boolean input; - //protected boolean secret; - - public RequiredCredentialRelationship() { - } - - /* - @AttributeProperty - public String getRealm() { - return realm; - } - - public void setRealm(String realm) { - this.realm = realm; - }*/ - - public String getRealm() { - return (String)getAttribute("realm").getValue(); - } - - public void setRealm(String realm) { - setAttribute(new Attribute("realm", realm)); - } - - @AttributeProperty - public String getCredentialType() { - return (String)getAttribute("credentialType").getValue(); - } - - public void setCredentialType(String credentialType) { - setAttribute(new Attribute("credentialType", credentialType)); - } - - @AttributeProperty - public boolean isInput() { - return (Boolean)getAttribute("input").getValue(); - } - - public void setInput(boolean input) { - setAttribute(new Attribute("input", input)); - } - - @AttributeProperty - public boolean isSecret() { - return (Boolean)getAttribute("secret").getValue(); - } - - public void setSecret(boolean secret) { - setAttribute(new Attribute("secret", secret)); - } - - @AttributeProperty - public String getFormLabel() { - return (String)getAttribute("formLabel").getValue(); - } - - public void setFormLabel(String label) { - setAttribute(new Attribute("formLabel", label)); - } - -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ScopeRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ScopeRelationship.java deleted file mode 100755 index 4931218e7b..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/ScopeRelationship.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.model.sample.Role; -import org.picketlink.idm.model.sample.User; -import org.picketlink.idm.query.RelationshipQueryParameter; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class ScopeRelationship extends AbstractAttributedType implements Relationship { - private static final long serialVersionUID = 1L; - - public static final RelationshipQueryParameter CLIENT = new RelationshipQueryParameter() { - - @Override - public String getName() { - return "client"; - } - }; - - public static final RelationshipQueryParameter SCOPE = new RelationshipQueryParameter() { - - @Override - public String getName() { - return OAuth2Constants.SCOPE; - } - }; - - - protected User client; - protected Role scope; - - public User getClient() { - return client; - } - - public void setClient(User client) { - this.client = client; - } - - public Role getScope() { - return scope; - } - - public void setScope(Role scope) { - this.scope = scope; - } -} diff --git a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/SocialLinkRelationship.java b/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/SocialLinkRelationship.java deleted file mode 100755 index 12f8d03251..0000000000 --- a/model/picketlink/src/main/java/org/keycloak/models/picketlink/relationships/SocialLinkRelationship.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.keycloak.models.picketlink.relationships; - -import org.picketlink.idm.model.AbstractAttributedType; -import org.picketlink.idm.model.Attribute; -import org.picketlink.idm.model.Relationship; -import org.picketlink.idm.model.annotation.AttributeProperty; -import org.picketlink.idm.model.sample.User; -import org.picketlink.idm.query.AttributeParameter; -import org.picketlink.idm.query.RelationshipQueryParameter; - -/** - * Binding between user and his social username for particular Social provider - * - * Example: Keycloak user "john" has username "john123" in social provider "facebook" - * - * @author Marek Posolda - */ -public class SocialLinkRelationship extends AbstractAttributedType implements Relationship { - - private static final long serialVersionUID = 154879L; - - public static final AttributeParameter SOCIAL_PROVIDER = new AttributeParameter("socialProvider"); - public static final AttributeParameter SOCIAL_USERID = new AttributeParameter("socialUserId"); - - // realm is needed to allow searching as combination socialUserId+socialProvider may not be unique - // (Same user could have mapped same facebook account to username "foo" in "realm1" and to username "bar" in "realm2") - public static final AttributeParameter REALM = new AttributeParameter("realm"); - - public static final RelationshipQueryParameter USER = new RelationshipQueryParameter() { - - @Override - public String getName() { - return "user"; - } - }; - - private User user; - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - @AttributeProperty - public String getSocialProvider() { - return (String)getAttribute("socialProvider").getValue(); - } - - public void setSocialProvider(String socialProvider) { - setAttribute(new Attribute("socialProvider", socialProvider)); - } - - @AttributeProperty - public String getSocialUserId() { - return (String)getAttribute("socialUserId").getValue(); - } - - public void setSocialUserId(String socialUserId) { - setAttribute(new Attribute("socialUserId", socialUserId)); - } - - @AttributeProperty - public String getRealm() { - return (String)getAttribute("realm").getValue(); - } - - public void setRealm(String realm) { - setAttribute(new Attribute("realm", realm)); - } -} diff --git a/model/picketlink/src/main/resources/META-INF/services/org.keycloak.models.ModelProvider b/model/picketlink/src/main/resources/META-INF/services/org.keycloak.models.ModelProvider deleted file mode 100644 index 225bcaa8fb..0000000000 --- a/model/picketlink/src/main/resources/META-INF/services/org.keycloak.models.ModelProvider +++ /dev/null @@ -1 +0,0 @@ -org.keycloak.models.picketlink.PicketlinkModelProvider \ No newline at end of file diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/forms/FederationProvidersIntegrationTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/forms/FederationProvidersIntegrationTest.java index 353aae22e9..d638db41f3 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/forms/FederationProvidersIntegrationTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/forms/FederationProvidersIntegrationTest.java @@ -61,8 +61,7 @@ public class FederationProvidersIntegrationTest { ldapConfig.put(LDAPConstants.VENDOR, ldapServer.getVendor()); - UserFederationProviderModel ldapProvider = new UserFederationProviderModel(null, LDAPFederationProviderFactory.PROVIDER_NAME, ldapConfig); - appRealm.setUserFederationProviders(Arrays.asList(ldapProvider)); + appRealm.addUserFederationProvider(LDAPFederationProviderFactory.PROVIDER_NAME, ldapConfig, 0); // Configure LDAP ldapRule.getEmbeddedServer().setupLdapInRealm(appRealm);