code formatting improved to keep only real changes done for

KEYCLOAK-1074
This commit is contained in:
Vlastimil Elias 2015-03-11 15:38:42 +01:00
parent c8c0449124
commit dec8d33af1
15 changed files with 643 additions and 921 deletions

View file

@ -32,7 +32,7 @@ public class RealmRepresentation {
protected Boolean userCacheEnabled; protected Boolean userCacheEnabled;
protected Boolean realmCacheEnabled; protected Boolean realmCacheEnabled;
// --- brute force settings //--- brute force settings
protected Boolean bruteForceProtected; protected Boolean bruteForceProtected;
protected Integer maxFailureWaitSeconds; protected Integer maxFailureWaitSeconds;
protected Integer minimumQuickLoginWaitSeconds; protected Integer minimumQuickLoginWaitSeconds;
@ -40,7 +40,7 @@ public class RealmRepresentation {
protected Long quickLoginCheckMilliSeconds; protected Long quickLoginCheckMilliSeconds;
protected Integer maxDeltaTimeSeconds; protected Integer maxDeltaTimeSeconds;
protected Integer failureFactor; protected Integer failureFactor;
// --- end brute force settings //--- end brute force settings
protected String privateKey; protected String privateKey;
protected String publicKey; protected String publicKey;
@ -95,8 +95,7 @@ public class RealmRepresentation {
public ApplicationRepresentation resource(String name) { public ApplicationRepresentation resource(String name) {
ApplicationRepresentation resource = new ApplicationRepresentation(); ApplicationRepresentation resource = new ApplicationRepresentation();
if (applications == null) if (applications == null) applications = new ArrayList<ApplicationRepresentation>();
applications = new ArrayList<ApplicationRepresentation>();
applications.add(resource); applications.add(resource);
resource.setName(name); resource.setName(name);
return resource; return resource;
@ -109,8 +108,7 @@ public class RealmRepresentation {
public UserRepresentation user(String username) { public UserRepresentation user(String username) {
UserRepresentation user = new UserRepresentation(); UserRepresentation user = new UserRepresentation();
user.setUsername(username); user.setUsername(username);
if (users == null) if (users == null) users = new ArrayList<UserRepresentation>();
users = new ArrayList<UserRepresentation>();
users.add(user); users.add(user);
return user; return user;
} }
@ -166,8 +164,7 @@ public class RealmRepresentation {
public ScopeMappingRepresentation scopeMapping(String username) { public ScopeMappingRepresentation scopeMapping(String username) {
ScopeMappingRepresentation mapping = new ScopeMappingRepresentation(); ScopeMappingRepresentation mapping = new ScopeMappingRepresentation();
mapping.setClient(username); mapping.setClient(username);
if (scopeMappings == null) if (scopeMappings == null) scopeMappings = new ArrayList<ScopeMappingRepresentation>();
scopeMappings = new ArrayList<ScopeMappingRepresentation>();
scopeMappings.add(mapping); scopeMappings.add(mapping);
return mapping; return mapping;
} }
@ -272,7 +269,7 @@ public class RealmRepresentation {
return registrationEmailAsUsername; return registrationEmailAsUsername;
} }
public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) { public void setRegistrationEmailAsUsername(Boolean registrationEmailAsUsername) {
this.registrationEmailAsUsername = registrationEmailAsUsername; this.registrationEmailAsUsername = registrationEmailAsUsername;
} }
@ -509,8 +506,7 @@ public class RealmRepresentation {
} }
public void addProtocolMapper(ProtocolMapperRepresentation rep) { public void addProtocolMapper(ProtocolMapperRepresentation rep) {
if (protocolMappers == null) if (protocolMappers == null) protocolMappers = new LinkedList<ProtocolMapperRepresentation>();
protocolMappers = new LinkedList<ProtocolMapperRepresentation>();
protocolMappers.add(rep); protocolMappers.add(rep);
} }

View file

@ -1,5 +1,8 @@
package org.keycloak.models; package org.keycloak.models;
import org.keycloak.enums.SslRequired;
import org.keycloak.provider.ProviderEvent;
import java.security.Key; import java.security.Key;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@ -8,9 +11,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.enums.SslRequired;
import org.keycloak.provider.ProviderEvent;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -178,7 +178,6 @@ public interface RealmModel extends RoleContainerModel {
List<OAuthClientModel> getOAuthClients(); List<OAuthClientModel> getOAuthClients();
Map<String, String> getBrowserSecurityHeaders(); Map<String, String> getBrowserSecurityHeaders();
void setBrowserSecurityHeaders(Map<String, String> headers); void setBrowserSecurityHeaders(Map<String, String> headers);
Map<String, String> getSmtpConfig(); Map<String, String> getSmtpConfig();
@ -186,24 +185,16 @@ public interface RealmModel extends RoleContainerModel {
void setSmtpConfig(Map<String, String> smtpConfig); void setSmtpConfig(Map<String, String> smtpConfig);
List<IdentityProviderModel> getIdentityProviders(); List<IdentityProviderModel> getIdentityProviders();
IdentityProviderModel getIdentityProviderById(String identityProviderId); IdentityProviderModel getIdentityProviderById(String identityProviderId);
void addIdentityProvider(IdentityProviderModel identityProvider); void addIdentityProvider(IdentityProviderModel identityProvider);
void removeIdentityProviderById(String providerId); void removeIdentityProviderById(String providerId);
void updateIdentityProvider(IdentityProviderModel identityProvider); void updateIdentityProvider(IdentityProviderModel identityProvider);
List<UserFederationProviderModel> getUserFederationProviders(); List<UserFederationProviderModel> getUserFederationProviders();
UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync);
String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync);
void updateUserFederationProvider(UserFederationProviderModel provider); void updateUserFederationProvider(UserFederationProviderModel provider);
void removeUserFederationProvider(UserFederationProviderModel provider); void removeUserFederationProvider(UserFederationProviderModel provider);
void setUserFederationProviders(List<UserFederationProviderModel> providers); void setUserFederationProviders(List<UserFederationProviderModel> providers);
String getLoginTheme(); String getLoginTheme();
@ -222,6 +213,7 @@ public interface RealmModel extends RoleContainerModel {
void setEmailTheme(String name); void setEmailTheme(String name);
/** /**
* Time in seconds since epoc * Time in seconds since epoc
* *

View file

@ -20,7 +20,7 @@ public class RealmEntity extends AbstractIdentifiableEntity {
private boolean passwordCredentialGrantAllowed; private boolean passwordCredentialGrantAllowed;
private boolean resetPasswordAllowed; private boolean resetPasswordAllowed;
private String passwordPolicy; private String passwordPolicy;
// --- brute force settings //--- brute force settings
private boolean bruteForceProtected; private boolean bruteForceProtected;
private int maxFailureWaitSeconds; private int maxFailureWaitSeconds;
private int minimumQuickLoginWaitSeconds; private int minimumQuickLoginWaitSeconds;
@ -28,7 +28,7 @@ public class RealmEntity extends AbstractIdentifiableEntity {
private long quickLoginCheckMilliSeconds; private long quickLoginCheckMilliSeconds;
private int maxDeltaTimeSeconds; private int maxDeltaTimeSeconds;
private int failureFactor; private int failureFactor;
// --- end brute force settings //--- end brute force settings
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@ -240,7 +240,6 @@ public class RealmEntity extends AbstractIdentifiableEntity {
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
} }
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }
@ -409,3 +408,5 @@ public class RealmEntity extends AbstractIdentifiableEntity {
this.certificatePem = certificatePem; this.certificatePem = certificatePem;
} }
} }

View file

@ -1,13 +1,5 @@
package org.keycloak.models.utils; package org.keycloak.models.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimMask; import org.keycloak.models.ClaimMask;
import org.keycloak.models.ClientIdentityProviderMappingModel; import org.keycloak.models.ClientIdentityProviderMappingModel;
@ -39,6 +31,14 @@ import org.keycloak.representations.idm.UserFederationProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.UserSessionRepresentation; import org.keycloak.representations.idm.UserSessionRepresentation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -57,7 +57,7 @@ public class ModelToRepresentation {
rep.setFederationLink(user.getFederationLink()); rep.setFederationLink(user.getFederationLink());
List<String> reqActions = new ArrayList<String>(); List<String> reqActions = new ArrayList<String>();
for (UserModel.RequiredAction ra : user.getRequiredActions()) { for (UserModel.RequiredAction ra : user.getRequiredActions()){
reqActions.add(ra.name()); reqActions.add(ra.name());
} }
@ -205,8 +205,8 @@ public class ModelToRepresentation {
public static UserSessionRepresentation toRepresentation(UserSessionModel session) { public static UserSessionRepresentation toRepresentation(UserSessionModel session) {
UserSessionRepresentation rep = new UserSessionRepresentation(); UserSessionRepresentation rep = new UserSessionRepresentation();
rep.setId(session.getId()); rep.setId(session.getId());
rep.setStart(((long) session.getStarted()) * 1000L); rep.setStart(((long)session.getStarted()) * 1000L);
rep.setLastAccess(((long) session.getLastSessionRefresh()) * 1000L); rep.setLastAccess(((long)session.getLastSessionRefresh())* 1000L);
rep.setUser(session.getUser().getUsername()); rep.setUser(session.getUser().getUsername());
rep.setIpAddress(session.getIpAddress()); rep.setIpAddress(session.getIpAddress());
for (ClientSessionModel clientSession : session.getClientSessions()) { for (ClientSessionModel clientSession : session.getClientSessions()) {
@ -270,8 +270,7 @@ public class ModelToRepresentation {
return rep; return rep;
} }
private static List<ClientIdentityProviderMappingRepresentation> toRepresentation( private static List<ClientIdentityProviderMappingRepresentation> toRepresentation(List<ClientIdentityProviderMappingModel> identityProviders) {
List<ClientIdentityProviderMappingModel> identityProviders) {
ArrayList<ClientIdentityProviderMappingRepresentation> representations = new ArrayList<ClientIdentityProviderMappingRepresentation>(); ArrayList<ClientIdentityProviderMappingRepresentation> representations = new ArrayList<ClientIdentityProviderMappingRepresentation>();
for (ClientIdentityProviderMappingModel model : identityProviders) { for (ClientIdentityProviderMappingModel model : identityProviders) {

View file

@ -1,16 +1,6 @@
package org.keycloak.models.utils; package org.keycloak.models.utils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.iharder.Base64; import net.iharder.Base64;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
@ -44,81 +34,60 @@ import org.keycloak.representations.idm.ScopeMappingRepresentation;
import org.keycloak.representations.idm.UserFederationProviderRepresentation; import org.keycloak.representations.idm.UserFederationProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserRepresentation;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RepresentationToModel { public class RepresentationToModel {
private static Logger logger = Logger.getLogger(RepresentationToModel.class); private static Logger logger = Logger.getLogger(RepresentationToModel.class);
public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) { public static void importRealm(KeycloakSession session, RealmRepresentation rep, RealmModel newRealm) {
newRealm.setName(rep.getRealm()); newRealm.setName(rep.getRealm());
if (rep.isEnabled() != null) if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled());
newRealm.setEnabled(rep.isEnabled()); if (rep.isBruteForceProtected() != null) newRealm.setBruteForceProtected(rep.isBruteForceProtected());
if (rep.isBruteForceProtected() != null) if (rep.getMaxFailureWaitSeconds() != null) newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
newRealm.setBruteForceProtected(rep.isBruteForceProtected()); if (rep.getMinimumQuickLoginWaitSeconds() != null) newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
if (rep.getMaxFailureWaitSeconds() != null) if (rep.getWaitIncrementSeconds() != null) newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
newRealm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); if (rep.getQuickLoginCheckMilliSeconds() != null) newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null) if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
newRealm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); if (rep.getFailureFactor() != null) newRealm.setFailureFactor(rep.getFailureFactor());
if (rep.getWaitIncrementSeconds() != null) if (rep.isEventsEnabled() != null) newRealm.setEventsEnabled(rep.isEventsEnabled());
newRealm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); if (rep.getEventsExpiration() != null) newRealm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getQuickLoginCheckMilliSeconds() != null) if (rep.getEventsListeners() != null) newRealm.setEventsListeners(new HashSet<String>(rep.getEventsListeners()));
newRealm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.getMaxDeltaTimeSeconds() != null)
newRealm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
if (rep.getFailureFactor() != null)
newRealm.setFailureFactor(rep.getFailureFactor());
if (rep.isEventsEnabled() != null)
newRealm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEventsExpiration() != null)
newRealm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEventsListeners() != null)
newRealm.setEventsListeners(new HashSet<String>(rep.getEventsListeners()));
if (rep.getNotBefore() != null) if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore());
newRealm.setNotBefore(rep.getNotBefore());
if (rep.getAccessTokenLifespan() != null) if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); else newRealm.setAccessTokenLifespan(300);
else
newRealm.setAccessTokenLifespan(300);
if (rep.getSsoSessionIdleTimeout() != null) if (rep.getSsoSessionIdleTimeout() != null) newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
newRealm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout()); else newRealm.setSsoSessionIdleTimeout(1800);
else if (rep.getSsoSessionMaxLifespan() != null) newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
newRealm.setSsoSessionIdleTimeout(1800); else newRealm.setSsoSessionMaxLifespan(36000);
if (rep.getSsoSessionMaxLifespan() != null)
newRealm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
else
newRealm.setSsoSessionMaxLifespan(36000);
if (rep.getAccessCodeLifespan() != null) if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); else newRealm.setAccessCodeLifespan(60);
else
newRealm.setAccessCodeLifespan(60);
if (rep.getAccessCodeLifespanUserAction() != null) if (rep.getAccessCodeLifespanUserAction() != null)
newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
else else newRealm.setAccessCodeLifespanUserAction(300);
newRealm.setAccessCodeLifespanUserAction(300);
if (rep.getAccessCodeLifespanLogin() != null) if (rep.getAccessCodeLifespanLogin() != null)
newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin()); newRealm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
else else newRealm.setAccessCodeLifespanLogin(1800);
newRealm.setAccessCodeLifespanLogin(1800);
if (rep.getSslRequired() != null) if (rep.getSslRequired() != null) newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
newRealm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase())); if (rep.isPasswordCredentialGrantAllowed() != null) newRealm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed());
if (rep.isPasswordCredentialGrantAllowed() != null) if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed());
newRealm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); if (rep.isRememberMe() != null) newRealm.setRememberMe(rep.isRememberMe());
if (rep.isRegistrationAllowed() != null) if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail());
newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
if (rep.isRegistrationEmailAsUsername() != null)
newRealm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
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.getPrivateKey() == null || rep.getPublicKey() == null) { if (rep.getPrivateKey() == null || rep.getPublicKey() == null) {
KeycloakModelUtils.generateRealmKeys(newRealm); KeycloakModelUtils.generateRealmKeys(newRealm);
} else { } else {
@ -136,14 +105,10 @@ public class RepresentationToModel {
newRealm.setCodeSecret(rep.getCodeSecret()); newRealm.setCodeSecret(rep.getCodeSecret());
} }
if (rep.getLoginTheme() != null) if (rep.getLoginTheme() != null) newRealm.setLoginTheme(rep.getLoginTheme());
newRealm.setLoginTheme(rep.getLoginTheme()); if (rep.getAccountTheme() != null) newRealm.setAccountTheme(rep.getAccountTheme());
if (rep.getAccountTheme() != null) if (rep.getAdminTheme() != null) newRealm.setAdminTheme(rep.getAdminTheme());
newRealm.setAccountTheme(rep.getAccountTheme()); if (rep.getEmailTheme() != null) newRealm.setEmailTheme(rep.getEmailTheme());
if (rep.getAdminTheme() != null)
newRealm.setAdminTheme(rep.getAdminTheme());
if (rep.getEmailTheme() != null)
newRealm.setEmailTheme(rep.getEmailTheme());
if (rep.getRequiredCredentials() != null) { if (rep.getRequiredCredentials() != null) {
for (String requiredCred : rep.getRequiredCredentials()) { for (String requiredCred : rep.getRequiredCredentials()) {
@ -153,8 +118,7 @@ public class RepresentationToModel {
addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD);
} }
if (rep.getPasswordPolicy() != null) if (rep.getPasswordPolicy() != null) newRealm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy()));
newRealm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy()));
importIdentityProviders(rep, newRealm); importIdentityProviders(rep, newRealm);
@ -176,8 +140,7 @@ public class RepresentationToModel {
} }
for (RoleRepresentation roleRep : entry.getValue()) { for (RoleRepresentation roleRep : entry.getValue()) {
// Application role may already exists (for example if it is defaultRole) // Application role may already exists (for example if it is defaultRole)
RoleModel role = roleRep.getId() != null ? app.addRole(roleRep.getId(), roleRep.getName()) : app RoleModel role = roleRep.getId()!=null ? app.addRole(roleRep.getId(), roleRep.getName()) : app.addRole(roleRep.getName());
.addRole(roleRep.getName());
role.setDescription(roleRep.getDescription()); role.setDescription(roleRep.getDescription());
} }
} }
@ -223,6 +186,7 @@ public class RepresentationToModel {
createOAuthClients(rep, newRealm); createOAuthClients(rep, newRealm);
} }
// Now that all possible roles and applications are created, create scope mappings // Now that all possible roles and applications are created, create scope mappings
Map<String, ApplicationModel> appMap = newRealm.getApplicationNameMap(); Map<String, ApplicationModel> appMap = newRealm.getApplicationNameMap();
@ -283,70 +247,40 @@ public class RepresentationToModel {
if (rep.getRealm() != null) { if (rep.getRealm() != null) {
realm.setName(rep.getRealm()); realm.setName(rep.getRealm());
} }
if (rep.isEnabled() != null) if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled());
realm.setEnabled(rep.isEnabled()); if (rep.isBruteForceProtected() != null) realm.setBruteForceProtected(rep.isBruteForceProtected());
if (rep.isBruteForceProtected() != null) if (rep.getMaxFailureWaitSeconds() != null) realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds());
realm.setBruteForceProtected(rep.isBruteForceProtected()); if (rep.getMinimumQuickLoginWaitSeconds() != null) realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds());
if (rep.getMaxFailureWaitSeconds() != null) if (rep.getWaitIncrementSeconds() != null) realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds());
realm.setMaxFailureWaitSeconds(rep.getMaxFailureWaitSeconds()); if (rep.getQuickLoginCheckMilliSeconds() != null) realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null) if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds());
realm.setMinimumQuickLoginWaitSeconds(rep.getMinimumQuickLoginWaitSeconds()); if (rep.getFailureFactor() != null) realm.setFailureFactor(rep.getFailureFactor());
if (rep.getWaitIncrementSeconds() != null) if (rep.isPasswordCredentialGrantAllowed() != null) realm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed());
realm.setWaitIncrementSeconds(rep.getWaitIncrementSeconds()); if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.getQuickLoginCheckMilliSeconds() != null) if (rep.isRegistrationEmailAsUsername() != null) realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
realm.setQuickLoginCheckMilliSeconds(rep.getQuickLoginCheckMilliSeconds()); if (rep.isRememberMe() != null) realm.setRememberMe(rep.isRememberMe());
if (rep.getMaxDeltaTimeSeconds() != null) if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail());
realm.setMaxDeltaTimeSeconds(rep.getMaxDeltaTimeSeconds()); if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed());
if (rep.getFailureFactor() != null) if (rep.getSslRequired() != null) realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
realm.setFailureFactor(rep.getFailureFactor()); if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
if (rep.isPasswordCredentialGrantAllowed() != null) if (rep.getAccessCodeLifespanUserAction() != null) realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
realm.setPasswordCredentialGrantAllowed(rep.isPasswordCredentialGrantAllowed()); if (rep.getAccessCodeLifespanLogin() != null) realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
if (rep.isRegistrationAllowed() != null) if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore());
realm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
if (rep.isRegistrationEmailAsUsername() != null) if (rep.getSsoSessionIdleTimeout() != null) realm.setSsoSessionIdleTimeout(rep.getSsoSessionIdleTimeout());
realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername()); if (rep.getSsoSessionMaxLifespan() != null) realm.setSsoSessionMaxLifespan(rep.getSsoSessionMaxLifespan());
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.getSslRequired() != null)
realm.setSslRequired(SslRequired.valueOf(rep.getSslRequired().toUpperCase()));
if (rep.getAccessCodeLifespan() != null)
realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
if (rep.getAccessCodeLifespanUserAction() != null)
realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
if (rep.getAccessCodeLifespanLogin() != null)
realm.setAccessCodeLifespanLogin(rep.getAccessCodeLifespanLogin());
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) { if (rep.getRequiredCredentials() != null) {
realm.updateRequiredCredentials(rep.getRequiredCredentials()); realm.updateRequiredCredentials(rep.getRequiredCredentials());
} }
if (rep.getLoginTheme() != null) if (rep.getLoginTheme() != null) realm.setLoginTheme(rep.getLoginTheme());
realm.setLoginTheme(rep.getLoginTheme()); if (rep.getAccountTheme() != null) realm.setAccountTheme(rep.getAccountTheme());
if (rep.getAccountTheme() != null) if (rep.getAdminTheme() != null) realm.setAdminTheme(rep.getAdminTheme());
realm.setAccountTheme(rep.getAccountTheme()); if (rep.getEmailTheme() != null) realm.setEmailTheme(rep.getEmailTheme());
if (rep.getAdminTheme() != null) if (rep.isEventsEnabled() != null) realm.setEventsEnabled(rep.isEventsEnabled());
realm.setAdminTheme(rep.getAdminTheme()); if (rep.getEventsExpiration() != null) realm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEmailTheme() != null) if (rep.getEventsListeners() != null) realm.setEventsListeners(new HashSet<String>(rep.getEventsListeners()));
realm.setEmailTheme(rep.getEmailTheme());
if (rep.isEventsEnabled() != null)
realm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEventsExpiration() != null)
realm.setEventsExpiration(rep.getEventsExpiration());
if (rep.getEventsListeners() != null)
realm.setEventsListeners(new HashSet<String>(rep.getEventsListeners()));
if (rep.getPasswordPolicy() != null) if (rep.getPasswordPolicy() != null) realm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy()));
realm.setPasswordPolicy(new PasswordPolicy(rep.getPasswordPolicy()));
if (rep.getDefaultRoles() != null) { if (rep.getDefaultRoles() != null) {
realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()])); realm.updateDefaultRoles(rep.getDefaultRoles().toArray(new String[rep.getDefaultRoles().size()]));
@ -376,15 +310,14 @@ public class RepresentationToModel {
newRealm.addRequiredCredential(requiredCred); newRealm.addRequiredCredential(requiredCred);
} }
private static List<UserFederationProviderModel> convertFederationProviders(
List<UserFederationProviderRepresentation> providers) { private static List<UserFederationProviderModel> convertFederationProviders(List<UserFederationProviderRepresentation> providers) {
List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>();
for (UserFederationProviderRepresentation representation : providers) { for (UserFederationProviderRepresentation representation : providers) {
UserFederationProviderModel model = new UserFederationProviderModel(representation.getId(), UserFederationProviderModel model = new UserFederationProviderModel(representation.getId(), representation.getProviderName(),
representation.getProviderName(), representation.getConfig(), representation.getPriority(), representation.getConfig(), representation.getPriority(), representation.getDisplayName(),
representation.getDisplayName(), representation.getFullSyncPeriod(), representation.getChangedSyncPeriod(), representation.getFullSyncPeriod(), representation.getChangedSyncPeriod(), representation.getLastSync());
representation.getLastSync());
result.add(model); result.add(model);
} }
return result; return result;
@ -393,20 +326,16 @@ public class RepresentationToModel {
// Roles // Roles
public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) { public static void createRole(RealmModel newRealm, RoleRepresentation roleRep) {
RoleModel role = roleRep.getId() != null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm RoleModel role = roleRep.getId()!=null ? newRealm.addRole(roleRep.getId(), roleRep.getName()) : newRealm.addRole(roleRep.getName());
.addRole(roleRep.getName()); if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription());
if (roleRep.getDescription() != null)
role.setDescription(roleRep.getDescription());
} }
private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) { private static void addComposites(RoleModel role, RoleRepresentation roleRep, RealmModel realm) {
if (roleRep.getComposites() == null) if (roleRep.getComposites() == null) return;
return;
if (roleRep.getComposites().getRealm() != null) { if (roleRep.getComposites().getRealm() != null) {
for (String roleStr : roleRep.getComposites().getRealm()) { for (String roleStr : roleRep.getComposites().getRealm()) {
RoleModel realmRole = realm.getRole(roleStr); RoleModel realmRole = realm.getRole(roleStr);
if (realmRole == null) if (realmRole == null) throw new RuntimeException("Unable to find composite realm role: " + roleStr);
throw new RuntimeException("Unable to find composite realm role: " + roleStr);
role.addCompositeRole(realmRole); role.addCompositeRole(realmRole);
} }
} }
@ -418,8 +347,7 @@ public class RepresentationToModel {
} }
for (String roleStr : entry.getValue()) { for (String roleStr : entry.getValue()) {
RoleModel appRole = app.getRole(roleStr); RoleModel appRole = app.getRole(roleStr);
if (appRole == null) if (appRole == null) throw new RuntimeException("Unable to find composite app role: " + roleStr);
throw new RuntimeException("Unable to find composite app role: " + roleStr);
role.addCompositeRole(appRole); role.addCompositeRole(appRole);
} }
@ -447,25 +375,18 @@ public class RepresentationToModel {
* @param resourceRep * @param resourceRep
* @return * @return
*/ */
public static ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep, public static ApplicationModel createApplication(RealmModel realm, ApplicationRepresentation resourceRep, boolean addDefaultRoles) {
boolean addDefaultRoles) {
logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName()); logger.debug("************ CREATE APPLICATION: {0}" + resourceRep.getName());
ApplicationModel applicationModel = resourceRep.getId() != null ? realm.addApplication(resourceRep.getId(), ApplicationModel applicationModel = resourceRep.getId()!=null ? realm.addApplication(resourceRep.getId(), resourceRep.getName()) : realm.addApplication(resourceRep.getName());
resourceRep.getName()) : realm.addApplication(resourceRep.getName()); if (resourceRep.isEnabled() != null) applicationModel.setEnabled(resourceRep.isEnabled());
if (resourceRep.isEnabled() != null)
applicationModel.setEnabled(resourceRep.isEnabled());
applicationModel.setManagementUrl(resourceRep.getAdminUrl()); applicationModel.setManagementUrl(resourceRep.getAdminUrl());
if (resourceRep.isSurrogateAuthRequired() != null) if (resourceRep.isSurrogateAuthRequired() != null)
applicationModel.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired()); applicationModel.setSurrogateAuthRequired(resourceRep.isSurrogateAuthRequired());
applicationModel.setBaseUrl(resourceRep.getBaseUrl()); applicationModel.setBaseUrl(resourceRep.getBaseUrl());
if (resourceRep.isBearerOnly() != null) if (resourceRep.isBearerOnly() != null) applicationModel.setBearerOnly(resourceRep.isBearerOnly());
applicationModel.setBearerOnly(resourceRep.isBearerOnly()); if (resourceRep.isPublicClient() != null) applicationModel.setPublicClient(resourceRep.isPublicClient());
if (resourceRep.isPublicClient() != null) if (resourceRep.isFrontchannelLogout() != null) applicationModel.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
applicationModel.setPublicClient(resourceRep.isPublicClient()); if (resourceRep.getProtocol() != null) applicationModel.setProtocol(resourceRep.getProtocol());
if (resourceRep.isFrontchannelLogout() != null)
applicationModel.setFrontchannelLogout(resourceRep.isFrontchannelLogout());
if (resourceRep.getProtocol() != null)
applicationModel.setProtocol(resourceRep.getProtocol());
if (resourceRep.isFullScopeAllowed() != null) { if (resourceRep.isFullScopeAllowed() != null) {
applicationModel.setFullScopeAllowed(resourceRep.isFullScopeAllowed()); applicationModel.setFullScopeAllowed(resourceRep.isFullScopeAllowed());
} else { } else {
@ -493,6 +414,7 @@ public class RepresentationToModel {
} }
} }
if (resourceRep.getRedirectUris() != null) { if (resourceRep.getRedirectUris() != null) {
for (String redirectUri : resourceRep.getRedirectUris()) { for (String redirectUri : resourceRep.getRedirectUris()) {
applicationModel.addRedirectUri(redirectUri); applicationModel.addRedirectUri(redirectUri);
@ -515,7 +437,7 @@ public class RepresentationToModel {
if (uri.getPort() != -1) { if (uri.getPort() != -1) {
origin += ":" + uri.getPort(); origin += ":" + uri.getPort();
} }
logger.debugv("adding default application origin: {0}", origin); logger.debugv("adding default application origin: {0}" , origin);
origins.add(origin); origins.add(origin);
} }
} }
@ -538,8 +460,7 @@ public class RepresentationToModel {
if (resourceRep.getProtocolMappers() != null) { if (resourceRep.getProtocolMappers() != null) {
// first, remove all default/built in mappers // first, remove all default/built in mappers
Set<ProtocolMapperModel> mappers = applicationModel.getProtocolMappers(); Set<ProtocolMapperModel> mappers = applicationModel.getProtocolMappers();
for (ProtocolMapperModel mapper : mappers) for (ProtocolMapperModel mapper : mappers) applicationModel.removeProtocolMapper(mapper);
applicationModel.removeProtocolMapper(mapper);
for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) { for (ProtocolMapperRepresentation mapper : resourceRep.getProtocolMappers()) {
applicationModel.addProtocolMapper(toModel(mapper)); applicationModel.addProtocolMapper(toModel(mapper));
@ -552,36 +473,26 @@ public class RepresentationToModel {
} }
public static void updateApplication(ApplicationRepresentation rep, ApplicationModel resource) { public static void updateApplication(ApplicationRepresentation rep, ApplicationModel resource) {
if (rep.getName() != null) if (rep.getName() != null) resource.setName(rep.getName());
resource.setName(rep.getName()); if (rep.isEnabled() != null) resource.setEnabled(rep.isEnabled());
if (rep.isEnabled() != null) if (rep.isBearerOnly() != null) resource.setBearerOnly(rep.isBearerOnly());
resource.setEnabled(rep.isEnabled()); if (rep.isPublicClient() != null) resource.setPublicClient(rep.isPublicClient());
if (rep.isBearerOnly() != null) if (rep.isFullScopeAllowed() != null) resource.setFullScopeAllowed(rep.isFullScopeAllowed());
resource.setBearerOnly(rep.isBearerOnly()); if (rep.isFrontchannelLogout() != null) resource.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.isPublicClient() != null) if (rep.getAdminUrl() != null) resource.setManagementUrl(rep.getAdminUrl());
resource.setPublicClient(rep.isPublicClient()); if (rep.getBaseUrl() != null) resource.setBaseUrl(rep.getBaseUrl());
if (rep.isFullScopeAllowed() != null) if (rep.isSurrogateAuthRequired() != null) resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired());
resource.setFullScopeAllowed(rep.isFullScopeAllowed()); if (rep.getNodeReRegistrationTimeout() != null) resource.setNodeReRegistrationTimeout(rep.getNodeReRegistrationTimeout());
if (rep.isFrontchannelLogout() != null)
resource.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.getAdminUrl() != null)
resource.setManagementUrl(rep.getAdminUrl());
if (rep.getBaseUrl() != null)
resource.setBaseUrl(rep.getBaseUrl());
if (rep.isSurrogateAuthRequired() != null)
resource.setSurrogateAuthRequired(rep.isSurrogateAuthRequired());
if (rep.getNodeReRegistrationTimeout() != null)
resource.setNodeReRegistrationTimeout(rep.getNodeReRegistrationTimeout());
resource.updateApplication(); resource.updateApplication();
if (rep.getProtocol() != null) if (rep.getProtocol() != null) resource.setProtocol(rep.getProtocol());
resource.setProtocol(rep.getProtocol());
if (rep.getAttributes() != null) { if (rep.getAttributes() != null) {
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) { for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
resource.setAttribute(entry.getKey(), entry.getValue()); resource.setAttribute(entry.getKey(), entry.getValue());
} }
} }
if (rep.getNotBefore() != null) { if (rep.getNotBefore() != null) {
resource.setNotBefore(rep.getNotBefore()); resource.setNotBefore(rep.getNotBefore());
} }
@ -672,7 +583,7 @@ public class RepresentationToModel {
} }
public static OAuthClientModel createOAuthClient(String id, String name, RealmModel realm) { public static OAuthClientModel createOAuthClient(String id, String name, RealmModel realm) {
OAuthClientModel model = id != null ? realm.addOAuthClient(id, name) : realm.addOAuthClient(name); OAuthClientModel model = id!=null ? realm.addOAuthClient(id, name) : realm.addOAuthClient(name);
KeycloakModelUtils.generateSecret(model); KeycloakModelUtils.generateSecret(model);
return model; return model;
} }
@ -687,26 +598,19 @@ public class RepresentationToModel {
} }
public static void updateOAuthClient(OAuthClientRepresentation rep, OAuthClientModel model) { public static void updateOAuthClient(OAuthClientRepresentation rep, OAuthClientModel model) {
if (rep.getName() != null) if (rep.getName() != null) model.setClientId(rep.getName());
model.setClientId(rep.getName()); if (rep.isEnabled() != null) model.setEnabled(rep.isEnabled());
if (rep.isEnabled() != null) if (rep.isPublicClient() != null) model.setPublicClient(rep.isPublicClient());
model.setEnabled(rep.isEnabled()); if (rep.isFrontchannelLogout() != null) model.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.isPublicClient() != null) if (rep.isFullScopeAllowed() != null) model.setFullScopeAllowed(rep.isFullScopeAllowed());
model.setPublicClient(rep.isPublicClient()); if (rep.isDirectGrantsOnly() != null) model.setDirectGrantsOnly(rep.isDirectGrantsOnly());
if (rep.isFrontchannelLogout() != null)
model.setFrontchannelLogout(rep.isFrontchannelLogout());
if (rep.isFullScopeAllowed() != null)
model.setFullScopeAllowed(rep.isFullScopeAllowed());
if (rep.isDirectGrantsOnly() != null)
model.setDirectGrantsOnly(rep.isDirectGrantsOnly());
if (rep.getClaims() != null) { if (rep.getClaims() != null) {
setClaims(model, rep.getClaims()); setClaims(model, rep.getClaims());
} }
if (rep.getNotBefore() != null) { if (rep.getNotBefore() != null) {
model.setNotBefore(rep.getNotBefore()); model.setNotBefore(rep.getNotBefore());
} }
if (rep.getSecret() != null) if (rep.getSecret() != null) model.setSecret(rep.getSecret());
model.setSecret(rep.getSecret());
List<String> redirectUris = rep.getRedirectUris(); List<String> redirectUris = rep.getRedirectUris();
if (redirectUris != null) { if (redirectUris != null) {
model.setRedirectUris(new HashSet<String>(redirectUris)); model.setRedirectUris(new HashSet<String>(redirectUris));
@ -720,8 +624,7 @@ public class RepresentationToModel {
if (rep.getNotBefore() != null) { if (rep.getNotBefore() != null) {
model.setNotBefore(rep.getNotBefore()); model.setNotBefore(rep.getNotBefore());
} }
if (rep.getProtocol() != null) if (rep.getProtocol() != null) model.setProtocol(rep.getProtocol());
model.setProtocol(rep.getProtocol());
if (rep.getAttributes() != null) { if (rep.getAttributes() != null) {
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) { for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
model.setAttribute(entry.getKey(), entry.getValue()); model.setAttribute(entry.getKey(), entry.getValue());
@ -733,8 +636,7 @@ public class RepresentationToModel {
if (rep.getProtocolMappers() != null) { if (rep.getProtocolMappers() != null) {
// first, remove all default/built in mappers // first, remove all default/built in mappers
Set<ProtocolMapperModel> mappers = model.getProtocolMappers(); Set<ProtocolMapperModel> mappers = model.getProtocolMappers();
for (ProtocolMapperModel mapper : mappers) for (ProtocolMapperModel mapper : mappers) model.removeProtocolMapper(mapper);
model.removeProtocolMapper(mapper);
for (ProtocolMapperRepresentation mapper : rep.getProtocolMappers()) { for (ProtocolMapperRepresentation mapper : rep.getProtocolMappers()) {
model.addProtocolMapper(toModel(mapper)); model.addProtocolMapper(toModel(mapper));
@ -745,8 +647,7 @@ public class RepresentationToModel {
// Scope mappings // Scope mappings
public static void createApplicationScopeMappings(RealmModel realm, ApplicationModel applicationModel, public static void createApplicationScopeMappings(RealmModel realm, ApplicationModel applicationModel, List<ScopeMappingRepresentation> mappings) {
List<ScopeMappingRepresentation> mappings) {
for (ScopeMappingRepresentation mapping : mappings) { for (ScopeMappingRepresentation mapping : mappings) {
ClientModel client = realm.findClient(mapping.getClient()); ClientModel client = realm.findClient(mapping.getClient());
if (client == null) { if (client == null) {
@ -764,8 +665,7 @@ public class RepresentationToModel {
// Users // Users
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep, public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep, Map<String, ApplicationModel> appMap) {
Map<String, ApplicationModel> appMap) {
// Import users just to user storage. Don't federate // Import users just to user storage. Don't federate
UserModel user = session.userStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false); UserModel user = session.userStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false);
user.setEnabled(userRep.isEnabled()); user.setEnabled(userRep.isEnabled());
@ -791,8 +691,7 @@ public class RepresentationToModel {
} }
if (userRep.getFederatedIdentities() != null) { if (userRep.getFederatedIdentities() != null) {
for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) { for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
identity.getUserId(), identity.getUserName());
session.users().addFederatedIdentity(newRealm, user, mappingModel); session.users().addFederatedIdentity(newRealm, user, mappingModel);
} }
} }
@ -828,8 +727,7 @@ public class RepresentationToModel {
hashedCred.setDevice(cred.getDevice()); hashedCred.setDevice(cred.getDevice());
hashedCred.setHashIterations(cred.getHashIterations()); hashedCred.setHashIterations(cred.getHashIterations());
try { try {
if (cred.getSalt() != null) if (cred.getSalt() != null) hashedCred.setSalt(Base64.decode(cred.getSalt()));
hashedCred.setSalt(Base64.decode(cred.getSalt()));
} catch (IOException ioe) { } catch (IOException ioe) {
throw new RuntimeException(ioe); throw new RuntimeException(ioe);
} }
@ -847,8 +745,7 @@ public class RepresentationToModel {
// Role mappings // Role mappings
public static void createApplicationRoleMappings(ApplicationModel applicationModel, UserModel user, public static void createApplicationRoleMappings(ApplicationModel applicationModel, UserModel user, List<String> roleNames) {
List<String> roleNames) {
if (user == null) { if (user == null) {
throw new RuntimeException("User not found"); throw new RuntimeException("User not found");
} }
@ -870,7 +767,6 @@ public class RepresentationToModel {
} }
} }
} }
public static IdentityProviderModel toModel(IdentityProviderRepresentation representation) { public static IdentityProviderModel toModel(IdentityProviderRepresentation representation) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel(); IdentityProviderModel identityProviderModel = new IdentityProviderModel();
@ -899,8 +795,7 @@ public class RepresentationToModel {
return model; return model;
} }
private static List<ClientIdentityProviderMappingModel> toModel( private static List<ClientIdentityProviderMappingModel> toModel(List<ClientIdentityProviderMappingRepresentation> repIdentityProviders, RealmModel realm) {
List<ClientIdentityProviderMappingRepresentation> repIdentityProviders, RealmModel realm) {
List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>(); List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>();
if (repIdentityProviders == null || repIdentityProviders.isEmpty()) { if (repIdentityProviders == null || repIdentityProviders.isEmpty()) {
@ -927,8 +822,7 @@ public class RepresentationToModel {
return allowedIdentityProviders; return allowedIdentityProviders;
} }
private static void updateClientIdentityProvides(List<ClientIdentityProviderMappingRepresentation> identityProviders, private static void updateClientIdentityProvides(List<ClientIdentityProviderMappingRepresentation> identityProviders, ClientModel resource) {
ClientModel resource) {
if (identityProviders != null) { if (identityProviders != null) {
List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>(); List<ClientIdentityProviderMappingModel> allowedIdentityProviders = new ArrayList<ClientIdentityProviderMappingModel>();

View file

@ -16,6 +16,21 @@
*/ */
package org.keycloak.models.file.adapter; package org.keycloak.models.file.adapter;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
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.UserFederationProviderModel;
import org.keycloak.models.entities.RequiredCredentialEntity;
import org.keycloak.models.entities.UserFederationProviderEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.security.Key; import java.security.Key;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@ -31,29 +46,14 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelDuplicateException;
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.UserFederationProviderModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.entities.ApplicationEntity; import org.keycloak.models.entities.ApplicationEntity;
import org.keycloak.models.entities.ClientEntity; import org.keycloak.models.entities.ClientEntity;
import org.keycloak.models.entities.OAuthClientEntity; import org.keycloak.models.entities.OAuthClientEntity;
import org.keycloak.models.entities.RealmEntity; import org.keycloak.models.entities.RealmEntity;
import org.keycloak.models.entities.RequiredCredentialEntity;
import org.keycloak.models.entities.RoleEntity; import org.keycloak.models.entities.RoleEntity;
import org.keycloak.models.entities.UserFederationProviderEntity;
import org.keycloak.models.file.InMemoryModel; import org.keycloak.models.file.InMemoryModel;
import org.keycloak.models.utils.KeycloakModelUtils;
/** /**
* RealmModel for JSON persistence. * RealmModel for JSON persistence.
@ -106,11 +106,9 @@ public class RealmAdapter implements RealmModel {
return; return;
} }
if (getName().equals(name)) if (getName().equals(name)) return; // allow setting name to same value
return; // allow setting name to same value
if (inMemoryModel.getRealmByName(name) != null) if (inMemoryModel.getRealmByName(name) != null) throw new ModelDuplicateException("Realm " + name + " already exists.");
throw new ModelDuplicateException("Realm " + name + " already exists.");
realm.setName(name); realm.setName(name);
} }
@ -224,6 +222,7 @@ public class RealmAdapter implements RealmModel {
realm.setMinimumQuickLoginWaitSeconds(val); realm.setMinimumQuickLoginWaitSeconds(val);
} }
@Override @Override
public int getMaxDeltaTimeSeconds() { public int getMaxDeltaTimeSeconds() {
return realm.getMaxDeltaTimeSeconds(); return realm.getMaxDeltaTimeSeconds();
@ -244,6 +243,7 @@ public class RealmAdapter implements RealmModel {
realm.setFailureFactor(failureFactor); realm.setFailureFactor(failureFactor);
} }
@Override @Override
public boolean isVerifyEmail() { public boolean isVerifyEmail() {
return realm.isVerifyEmail(); return realm.isVerifyEmail();
@ -288,6 +288,7 @@ public class RealmAdapter implements RealmModel {
realm.setNotBefore(notBefore); realm.setNotBefore(notBefore);
} }
@Override @Override
public int getSsoSessionIdleTimeout() { public int getSsoSessionIdleTimeout() {
return realm.getSsoSessionIdleTimeout(); return realm.getSsoSessionIdleTimeout();
@ -351,8 +352,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) if (certificate != null) return certificate;
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -375,6 +375,7 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public String getPrivateKeyPem() { public String getPrivateKeyPem() {
return realm.getPrivateKeyPem(); return realm.getPrivateKeyPem();
@ -388,8 +389,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) if (publicKey != null) return publicKey;
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -403,8 +403,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) if (privateKey != null) return privateKey;
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -477,8 +476,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleAdapter getRole(String name) { public RoleAdapter getRole(String name) {
for (RoleAdapter role : allRoles.values()) { for (RoleAdapter role : allRoles.values()) {
if (role.getName().equals(name)) if (role.getName().equals(name)) return role;
return role;
} }
return null; return null;
} }
@ -490,12 +488,9 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel addRole(String id, String name) { public RoleModel addRole(String id, String name) {
if (id == null) if (id == null) throw new NullPointerException("id == null");
throw new NullPointerException("id == null"); if (name == null) throw new NullPointerException("name == null");
if (name == null) if (hasRoleWithName(name)) throw new ModelDuplicateException("Realm already contains role with name " + name + ".");
throw new NullPointerException("name == null");
if (hasRoleWithName(name))
throw new ModelDuplicateException("Realm already contains role with name " + name + ".");
RoleEntity roleEntity = new RoleEntity(); RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id); roleEntity.setId(id);
@ -514,12 +509,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeRoleById(String id) { public boolean removeRoleById(String id) {
if (id == null) if (id == null) throw new NullPointerException("id == null");
throw new NullPointerException("id == null");
// try realm roles first // try realm roles first
if (allRoles.remove(id) != null) if (allRoles.remove(id) != null) return true;
return true;
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
for (RoleModel appRole : app.getRoles()) { for (RoleModel appRole : app.getRoles()) {
@ -535,19 +528,17 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
return new HashSet<RoleModel>(allRoles.values()); return new HashSet(allRoles.values());
} }
@Override @Override
public RoleModel getRoleById(String id) { public RoleModel getRoleById(String id) {
RoleModel found = allRoles.get(id); RoleModel found = allRoles.get(id);
if (found != null) if (found != null) return found;
return found;
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
for (RoleModel appRole : app.getRoles()) { for (RoleModel appRole : app.getRoles()) {
if (appRole.getId().equals(id)) if (appRole.getId().equals(id)) return appRole;
return appRole;
} }
} }
@ -567,8 +558,7 @@ public class RealmAdapter implements RealmModel {
} }
List<String> roleNames = getDefaultRoles(); List<String> roleNames = getDefaultRoles();
if (roleNames.contains(name)) if (roleNames.contains(name)) throw new IllegalArgumentException("Realm " + realm.getName() + " already contains default role named " + name);
throw new IllegalArgumentException("Realm " + realm.getName() + " already contains default role named " + name);
roleNames.add(name); roleNames.add(name);
realm.setDefaultRoles(roleNames); realm.setDefaultRoles(roleNames);
@ -576,8 +566,7 @@ public class RealmAdapter implements RealmModel {
boolean hasRoleWithName(String name) { boolean hasRoleWithName(String name) {
for (RoleModel role : allRoles.values()) { for (RoleModel role : allRoles.values()) {
if (role.getName().equals(name)) if (role.getName().equals(name)) return true;
return true;
} }
return false; return false;
@ -601,19 +590,19 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId); ClientModel model = getApplicationByName(clientId);
if (model != null) if (model != null) return model;
return model;
return getOAuthClient(clientId); return getOAuthClient(clientId);
} }
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel clientModel = getApplicationById(id); ClientModel clientModel = getApplicationById(id);
if (clientModel != null) if (clientModel != null) return clientModel;
return clientModel;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
return allApps.get(id); return allApps.get(id);
@ -622,8 +611,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
if (app.getName().equals(name)) if (app.getName().equals(name)) return app;
return app;
} }
return null; return null;
@ -650,10 +638,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ApplicationModel addApplication(String id, String name) { public ApplicationModel addApplication(String id, String name) {
if (name == null) if (name == null) throw new NullPointerException("name == null");
throw new NullPointerException("name == null"); if (id == null) throw new NullPointerException("id == null");
if (id == null)
throw new NullPointerException("id == null");
if (getApplicationNameMap().containsKey(name)) { if (getApplicationNameMap().containsKey(name)) {
throw new ModelDuplicateException("Application named '" + name + "' already exists."); throw new ModelDuplicateException("Application named '" + name + "' already exists.");
@ -692,12 +678,11 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeApplication(String id) { public boolean removeApplication(String id) {
ApplicationModel appToBeRemoved = this.getApplicationById(id); ApplicationModel appToBeRemoved = this.getApplicationById(id);
if (appToBeRemoved == null) if (appToBeRemoved == null) return false;
return false;
// remove any composite role assignments for this app // remove any composite role assignments for this app
for (RoleModel role : this.getRoles()) { for (RoleModel role : this.getRoles()) {
RoleAdapter roleAdapter = (RoleAdapter) role; RoleAdapter roleAdapter = (RoleAdapter)role;
roleAdapter.removeApplicationComposites(id); roleAdapter.removeApplicationComposites(id);
} }
@ -715,12 +700,9 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel addOAuthClient(String id, String name) { public OAuthClientModel addOAuthClient(String id, String name) {
if (id == null) if (id == null) throw new NullPointerException("id == null");
throw new NullPointerException("id == null"); if (name == null) throw new NullPointerException("name == null");
if (name == null) if (hasOAuthClientWithName(name)) throw new ModelDuplicateException("OAuth Client with name " + name + " already exists.");
throw new NullPointerException("name == null");
if (hasOAuthClientWithName(name))
throw new ModelDuplicateException("OAuth Client with name " + name + " already exists.");
OAuthClientEntity oauthClient = new OAuthClientEntity(); OAuthClientEntity oauthClient = new OAuthClientEntity();
oauthClient.setId(id); oauthClient.setId(id);
oauthClient.setRealmId(getId()); oauthClient.setRealmId(getId());
@ -734,8 +716,7 @@ public class RealmAdapter implements RealmModel {
boolean hasOAuthClientWithName(String name) { boolean hasOAuthClientWithName(String name) {
for (OAuthClientAdapter oaClient : allOAuthClients.values()) { for (OAuthClientAdapter oaClient : allOAuthClients.values()) {
if (oaClient.getName().equals(name)) if (oaClient.getName().equals(name)) return true;
return true;
} }
return false; return false;
@ -743,8 +724,7 @@ public class RealmAdapter implements RealmModel {
boolean hasOAuthClientWithClientId(String id) { boolean hasOAuthClientWithClientId(String id) {
for (OAuthClientAdapter oaClient : allOAuthClients.values()) { for (OAuthClientAdapter oaClient : allOAuthClients.values()) {
if (oaClient.getClientId().equals(id)) if (oaClient.getClientId().equals(id)) return true;
return true;
} }
return false; return false;
@ -752,10 +732,8 @@ public class RealmAdapter implements RealmModel {
boolean hasUserWithEmail(String email) { boolean hasUserWithEmail(String email) {
for (UserModel user : inMemoryModel.getUsers(getId())) { for (UserModel user : inMemoryModel.getUsers(getId())) {
if (user.getEmail() == null) if (user.getEmail() == null) continue;
continue; if (user.getEmail().equals(email)) return true;
if (user.getEmail().equals(email))
return true;
} }
return false; return false;
@ -769,8 +747,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) { for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) {
if (oAuthClient.getName().equals(name)) if (oAuthClient.getName().equals(name)) return oAuthClient;
return oAuthClient;
} }
return null; return null;
@ -779,8 +756,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel getOAuthClientById(String id) { public OAuthClientModel getOAuthClientById(String id) {
for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) { for (OAuthClientAdapter oAuthClient : allOAuthClients.values()) {
if (oAuthClient.getId().equals(id)) if (oAuthClient.getId().equals(id)) return oAuthClient;
return oAuthClient;
} }
return null; return null;
@ -788,7 +764,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
return new ArrayList<OAuthClientModel>(allOAuthClients.values()); return new ArrayList(allOAuthClients.values());
} }
@Override @Override
@ -797,8 +773,7 @@ public class RealmAdapter implements RealmModel {
addRequiredCredential(credentialModel, realm.getRequiredCredentials()); addRequiredCredential(credentialModel, realm.getRequiredCredentials());
} }
protected void addRequiredCredential(RequiredCredentialModel credentialModel, protected void addRequiredCredential(RequiredCredentialModel credentialModel, List<RequiredCredentialEntity> persistentCollection) {
List<RequiredCredentialEntity> persistentCollection) {
RequiredCredentialEntity credEntity = new RequiredCredentialEntity(); RequiredCredentialEntity credEntity = new RequiredCredentialEntity();
credEntity.setType(credentialModel.getType()); credEntity.setType(credentialModel.getType());
credEntity.setFormLabel(credentialModel.getFormLabel()); credEntity.setFormLabel(credentialModel.getFormLabel());
@ -839,8 +814,7 @@ public class RealmAdapter implements RealmModel {
return convertRequiredCredentialEntities(realm.getRequiredCredentials()); return convertRequiredCredentialEntities(realm.getRequiredCredentials());
} }
protected List<RequiredCredentialModel> convertRequiredCredentialEntities( protected List<RequiredCredentialModel> convertRequiredCredentialEntities(Collection<RequiredCredentialEntity> credEntities) {
Collection<RequiredCredentialEntity> credEntities) {
List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>();
for (RequiredCredentialEntity entity : credEntities) { for (RequiredCredentialEntity entity : credEntities) {
@ -885,7 +859,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
return new ArrayList<IdentityProviderModel>(allIdProviders.values()); return new ArrayList(allIdProviders.values());
} }
@Override @Override
@ -901,10 +875,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public void addIdentityProvider(IdentityProviderModel identityProvider) { public void addIdentityProvider(IdentityProviderModel identityProvider) {
if (identityProvider.getId() == null) if (identityProvider.getId() == null) throw new NullPointerException("identityProvider.getId() == null");
throw new NullPointerException("identityProvider.getId() == null"); if (identityProvider.getInternalId() == null) identityProvider.setInternalId(KeycloakModelUtils.generateId());
if (identityProvider.getInternalId() == null)
identityProvider.setInternalId(KeycloakModelUtils.generateId());
allIdProviders.put(identityProvider.getInternalId(), identityProvider); allIdProviders.put(identityProvider.getInternalId(), identityProvider);
} }
@ -925,8 +897,7 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
entity.setId(KeycloakModelUtils.generateId()); entity.setId(KeycloakModelUtils.generateId());
entity.setPriority(priority); entity.setPriority(priority);
@ -941,8 +912,7 @@ public class RealmAdapter implements RealmModel {
entity.setLastSync(lastSync); entity.setLastSync(lastSync);
realm.getUserFederationProviders().add(entity); realm.getUserFederationProviders().add(entity);
return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync);
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -951,11 +921,8 @@ public class RealmAdapter implements RealmModel {
while (it.hasNext()) { while (it.hasNext()) {
UserFederationProviderEntity entity = it.next(); UserFederationProviderEntity entity = it.next();
if (entity.getId().equals(provider.getId())) { if (entity.getId().equals(provider.getId())) {
session.users().preRemove( session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(),
this, entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync()));
new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(),
entity.getLastSync()));
it.remove(); it.remove();
} }
} }
@ -999,9 +966,8 @@ public class RealmAdapter implements RealmModel {
}); });
List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>();
for (UserFederationProviderEntity entity : copy) { for (UserFederationProviderEntity entity : copy) {
result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(),
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync()));
.getLastSync()));
} }
return result; return result;
@ -1012,10 +978,8 @@ public class RealmAdapter implements RealmModel {
List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>(); List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>();
for (UserFederationProviderModel model : providers) { for (UserFederationProviderModel model : providers) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
if (model.getId() != null) if (model.getId() != null) entity.setId(model.getId());
entity.setId(model.getId()); else entity.setId(KeycloakModelUtils.generateId());
else
entity.setId(KeycloakModelUtils.generateId());
entity.setProviderName(model.getProviderName()); entity.setProviderName(model.getProviderName());
entity.setConfig(model.getConfig()); entity.setConfig(model.getConfig());
entity.setPriority(model.getPriority()); entity.setPriority(model.getPriority());
@ -1089,7 +1053,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isIdentityFederationEnabled() { public boolean isIdentityFederationEnabled() {
// TODO: not sure if we will support identity federation storage for file //TODO: not sure if we will support identity federation storage for file
return getIdentityProviders() != null && !getIdentityProviders().isEmpty(); return getIdentityProviders() != null && !getIdentityProviders().isEmpty();
} }
@ -1105,10 +1069,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) return true;
return true; if (o == null || !(o instanceof RealmModel)) return false;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());

View file

@ -1,5 +1,21 @@
package org.keycloak.models.cache; package org.keycloak.models.cache;
import org.keycloak.Config;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimTypeModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.security.Key; import java.security.Key;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
@ -11,20 +27,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.Config;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
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.UserFederationProviderModel;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.utils.KeycloakModelUtils;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -48,22 +50,19 @@ public class RealmAdapter implements RealmModel {
if (updated == null) { if (updated == null) {
cacheSession.registerRealmInvalidation(getId()); cacheSession.registerRealmInvalidation(getId());
updated = cacheSession.getDelegate().getRealm(getId()); updated = cacheSession.getDelegate().getRealm(getId());
if (updated == null) if (updated == null) throw new IllegalStateException("Not found in database");
throw new IllegalStateException("Not found in database");
} }
} }
@Override @Override
public String getId() { public String getId() {
if (updated != null) if (updated != null) return updated.getId();
return updated.getId();
return cached.getId(); return cached.getId();
} }
@Override @Override
public String getName() { public String getName() {
if (updated != null) if (updated != null) return updated.getName();
return updated.getName();
return cached.getName(); return cached.getName();
} }
@ -75,8 +74,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
if (updated != null) if (updated != null) return updated.isEnabled();
return updated.isEnabled();
return cached.isEnabled(); return cached.isEnabled();
} }
@ -88,8 +86,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public SslRequired getSslRequired() { public SslRequired getSslRequired() {
if (updated != null) if (updated != null) return updated.getSslRequired();
return updated.getSslRequired();
return cached.getSslRequired(); return cached.getSslRequired();
} }
@ -101,8 +98,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isRegistrationAllowed() { public boolean isRegistrationAllowed() {
if (updated != null) if (updated != null) return updated.isRegistrationAllowed();
return updated.isRegistrationAllowed();
return cached.isRegistrationAllowed(); return cached.isRegistrationAllowed();
} }
@ -114,8 +110,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isRegistrationEmailAsUsername() { public boolean isRegistrationEmailAsUsername() {
if (updated != null) if (updated != null) return updated.isRegistrationEmailAsUsername();
return updated.isRegistrationEmailAsUsername();
return cached.isRegistrationEmailAsUsername(); return cached.isRegistrationEmailAsUsername();
} }
@ -127,8 +122,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isPasswordCredentialGrantAllowed() { public boolean isPasswordCredentialGrantAllowed() {
if (updated != null) if (updated != null) return updated.isPasswordCredentialGrantAllowed();
return updated.isPasswordCredentialGrantAllowed();
return cached.isPasswordCredentialGrantAllowed(); return cached.isPasswordCredentialGrantAllowed();
} }
@ -140,8 +134,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isRememberMe() { public boolean isRememberMe() {
if (updated != null) if (updated != null) return updated.isRememberMe();
return updated.isRememberMe();
return cached.isRememberMe(); return cached.isRememberMe();
} }
@ -153,8 +146,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isBruteForceProtected() { public boolean isBruteForceProtected() {
if (updated != null) if (updated != null) return updated.isBruteForceProtected();
return updated.isBruteForceProtected();
return cached.isBruteForceProtected(); return cached.isBruteForceProtected();
} }
@ -166,8 +158,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getMaxFailureWaitSeconds() { public int getMaxFailureWaitSeconds() {
if (updated != null) if (updated != null) return updated.getMaxFailureWaitSeconds();
return updated.getMaxFailureWaitSeconds();
return cached.getMaxFailureWaitSeconds(); return cached.getMaxFailureWaitSeconds();
} }
@ -179,8 +170,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getWaitIncrementSeconds() { public int getWaitIncrementSeconds() {
if (updated != null) if (updated != null) return updated.getWaitIncrementSeconds();
return updated.getWaitIncrementSeconds();
return cached.getWaitIncrementSeconds(); return cached.getWaitIncrementSeconds();
} }
@ -192,8 +182,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getMinimumQuickLoginWaitSeconds() { public int getMinimumQuickLoginWaitSeconds() {
if (updated != null) if (updated != null) return updated.getMinimumQuickLoginWaitSeconds();
return updated.getMinimumQuickLoginWaitSeconds();
return cached.getMinimumQuickLoginWaitSeconds(); return cached.getMinimumQuickLoginWaitSeconds();
} }
@ -205,8 +194,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public long getQuickLoginCheckMilliSeconds() { public long getQuickLoginCheckMilliSeconds() {
if (updated != null) if (updated != null) return updated.getQuickLoginCheckMilliSeconds();
return updated.getQuickLoginCheckMilliSeconds();
return cached.getQuickLoginCheckMilliSeconds(); return cached.getQuickLoginCheckMilliSeconds();
} }
@ -218,8 +206,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getMaxDeltaTimeSeconds() { public int getMaxDeltaTimeSeconds() {
if (updated != null) if (updated != null) return updated.getMaxDeltaTimeSeconds();
return updated.getMaxDeltaTimeSeconds();
return cached.getMaxDeltaTimeSeconds(); return cached.getMaxDeltaTimeSeconds();
} }
@ -231,8 +218,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getFailureFactor() { public int getFailureFactor() {
if (updated != null) if (updated != null) return updated.getFailureFactor();
return updated.getFailureFactor();
return cached.getFailureFactor(); return cached.getFailureFactor();
} }
@ -244,8 +230,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isVerifyEmail() { public boolean isVerifyEmail() {
if (updated != null) if (updated != null) return updated.isVerifyEmail();
return updated.isVerifyEmail();
return cached.isVerifyEmail(); return cached.isVerifyEmail();
} }
@ -257,8 +242,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isResetPasswordAllowed() { public boolean isResetPasswordAllowed() {
if (updated != null) if (updated != null) return updated.isResetPasswordAllowed();
return updated.isResetPasswordAllowed();
return cached.isResetPasswordAllowed(); return cached.isResetPasswordAllowed();
} }
@ -270,8 +254,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getSsoSessionIdleTimeout() { public int getSsoSessionIdleTimeout() {
if (updated != null) if (updated != null) return updated.getSsoSessionIdleTimeout();
return updated.getSsoSessionIdleTimeout();
return cached.getSsoSessionIdleTimeout(); return cached.getSsoSessionIdleTimeout();
} }
@ -283,8 +266,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getSsoSessionMaxLifespan() { public int getSsoSessionMaxLifespan() {
if (updated != null) if (updated != null) return updated.getSsoSessionMaxLifespan();
return updated.getSsoSessionMaxLifespan();
return cached.getSsoSessionMaxLifespan(); return cached.getSsoSessionMaxLifespan();
} }
@ -296,8 +278,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessTokenLifespan() { public int getAccessTokenLifespan() {
if (updated != null) if (updated != null) return updated.getAccessTokenLifespan();
return updated.getAccessTokenLifespan();
return cached.getAccessTokenLifespan(); return cached.getAccessTokenLifespan();
} }
@ -309,8 +290,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessCodeLifespan() { public int getAccessCodeLifespan() {
if (updated != null) if (updated != null) return updated.getAccessCodeLifespan();
return updated.getAccessCodeLifespan();
return cached.getAccessCodeLifespan(); return cached.getAccessCodeLifespan();
} }
@ -322,8 +302,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessCodeLifespanUserAction() { public int getAccessCodeLifespanUserAction() {
if (updated != null) if (updated != null) return updated.getAccessCodeLifespanUserAction();
return updated.getAccessCodeLifespanUserAction();
return cached.getAccessCodeLifespanUserAction(); return cached.getAccessCodeLifespanUserAction();
} }
@ -335,8 +314,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
if (updated != null) if (updated != null) return updated.getAccessCodeLifespanLogin();
return updated.getAccessCodeLifespanLogin();
return cached.getAccessCodeLifespanLogin(); return cached.getAccessCodeLifespanLogin();
} }
@ -348,8 +326,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getPublicKeyPem() { public String getPublicKeyPem() {
if (updated != null) if (updated != null) return updated.getPublicKeyPem();
return updated.getPublicKeyPem();
return cached.getPublicKeyPem(); return cached.getPublicKeyPem();
} }
@ -361,8 +338,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getPrivateKeyPem() { public String getPrivateKeyPem() {
if (updated != null) if (updated != null) return updated.getPrivateKeyPem();
return updated.getPrivateKeyPem();
return cached.getPrivateKeyPem(); return cached.getPrivateKeyPem();
} }
@ -374,8 +350,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) if (publicKey != null) return publicKey;
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -389,8 +364,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) if (certificate != null) return certificate;
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -404,8 +378,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getCertificatePem() { public String getCertificatePem() {
if (updated != null) if (updated != null) return updated.getCertificatePem();
return updated.getCertificatePem();
return cached.getCertificatePem(); return cached.getCertificatePem();
} }
@ -418,8 +391,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) if (privateKey != null) return privateKey;
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -454,10 +426,8 @@ public class RealmAdapter implements RealmModel {
public List<RequiredCredentialModel> getRequiredCredentials() { public List<RequiredCredentialModel> getRequiredCredentials() {
List<RequiredCredentialModel> copy = new LinkedList<RequiredCredentialModel>(); List<RequiredCredentialModel> copy = new LinkedList<RequiredCredentialModel>();
if (updated != null) if (updated != null) copy.addAll(updated.getRequiredCredentials());
copy.addAll(updated.getRequiredCredentials()); else copy.addAll(cached.getRequiredCredentials());
else
copy.addAll(cached.getRequiredCredentials());
return copy; return copy;
} }
@ -469,8 +439,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PasswordPolicy getPasswordPolicy() { public PasswordPolicy getPasswordPolicy() {
if (updated != null) if (updated != null) return updated.getPasswordPolicy();
return updated.getPasswordPolicy();
return cached.getPasswordPolicy(); return cached.getPasswordPolicy();
} }
@ -482,15 +451,13 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel getRoleById(String id) { public RoleModel getRoleById(String id) {
if (updated != null) if (updated != null) return updated.getRoleById(id);
return updated.getRoleById(id);
return cacheSession.getRoleById(id, this); return cacheSession.getRoleById(id, this);
} }
@Override @Override
public List<String> getDefaultRoles() { public List<String> getDefaultRoles() {
if (updated != null) if (updated != null) return updated.getDefaultRoles();
return updated.getDefaultRoles();
return cached.getDefaultRoles(); return cached.getDefaultRoles();
} }
@ -508,8 +475,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
if (updated != null) if (updated != null) return updated.findClient(clientId);
return updated.findClient(clientId);
String appId = cached.getApplications().get(clientId); String appId = cached.getApplications().get(clientId);
if (appId != null) { if (appId != null) {
return cacheSession.getApplicationById(appId, this); return cacheSession.getApplicationById(appId, this);
@ -523,8 +489,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Map<String, ApplicationModel> getApplicationNameMap() { public Map<String, ApplicationModel> getApplicationNameMap() {
if (updated != null) if (updated != null) return updated.getApplicationNameMap();
return updated.getApplicationNameMap();
Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>(); Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>();
for (String id : cached.getApplications().values()) { for (String id : cached.getApplications().values()) {
ApplicationModel model = cacheSession.getApplicationById(id, this); ApplicationModel model = cacheSession.getApplicationById(id, this);
@ -538,8 +503,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
if (updated != null) if (updated != null) return updated.getApplications();
return updated.getApplications();
List<ApplicationModel> apps = new LinkedList<ApplicationModel>(); List<ApplicationModel> apps = new LinkedList<ApplicationModel>();
for (String id : cached.getApplications().values()) { for (String id : cached.getApplications().values()) {
ApplicationModel model = cacheSession.getApplicationById(id, this); ApplicationModel model = cacheSession.getApplicationById(id, this);
@ -577,18 +541,15 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
if (updated != null) if (updated != null) return updated.getApplicationById(id);
return updated.getApplicationById(id);
return cacheSession.getApplicationById(id, this); return cacheSession.getApplicationById(id, this);
} }
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
if (updated != null) if (updated != null) return updated.getApplicationByName(name);
return updated.getApplicationByName(name);
String id = cached.getApplications().get(name); String id = cached.getApplications().get(name);
if (id == null) if (id == null) return null;
return null;
return getApplicationById(id); return getApplicationById(id);
} }
@ -616,18 +577,15 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
if (updated != null) if (updated != null) return updated.getOAuthClient(name);
return updated.getOAuthClient(name);
String id = cached.getClients().get(name); String id = cached.getClients().get(name);
if (id == null) if (id == null) return null;
return null;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public OAuthClientModel getOAuthClientById(String id) { public OAuthClientModel getOAuthClientById(String id) {
if (updated != null) if (updated != null) return updated.getOAuthClientById(id);
return updated.getOAuthClientById(id);
return cacheSession.getOAuthClientById(id, this); return cacheSession.getOAuthClientById(id, this);
} }
@ -640,8 +598,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
if (updated != null) if (updated != null) return updated.getOAuthClients();
return updated.getOAuthClients();
List<OAuthClientModel> clients = new LinkedList<OAuthClientModel>(); List<OAuthClientModel> clients = new LinkedList<OAuthClientModel>();
for (String id : cached.getClients().values()) { for (String id : cached.getClients().values()) {
OAuthClientModel model = cacheSession.getOAuthClientById(id, this); OAuthClientModel model = cacheSession.getOAuthClientById(id, this);
@ -655,8 +612,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Map<String, String> getBrowserSecurityHeaders() { public Map<String, String> getBrowserSecurityHeaders() {
if (updated != null) if (updated != null) return updated.getBrowserSecurityHeaders();
return updated.getBrowserSecurityHeaders();
return cached.getBrowserSecurityHeaders(); return cached.getBrowserSecurityHeaders();
} }
@ -669,8 +625,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Map<String, String> getSmtpConfig() { public Map<String, String> getSmtpConfig() {
if (updated != null) if (updated != null) return updated.getSmtpConfig();
return updated.getSmtpConfig();
return cached.getSmtpConfig(); return cached.getSmtpConfig();
} }
@ -680,10 +635,10 @@ public class RealmAdapter implements RealmModel {
updated.setSmtpConfig(smtpConfig); updated.setSmtpConfig(smtpConfig);
} }
@Override @Override
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
if (updated != null) if (updated != null) return updated.getIdentityProviders();
return updated.getIdentityProviders();
return cached.getIdentityProviders(); return cached.getIdentityProviders();
} }
@ -718,8 +673,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public List<UserFederationProviderModel> getUserFederationProviders() { public List<UserFederationProviderModel> getUserFederationProviders() {
if (updated != null) if (updated != null) return updated.getUserFederationProviders();
return updated.getUserFederationProviders();
return cached.getUserFederationProviders(); return cached.getUserFederationProviders();
} }
@ -730,11 +684,9 @@ public class RealmAdapter implements RealmModel {
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
getDelegateForUpdate(); getDelegateForUpdate();
return updated.addUserFederationProvider(providerName, config, priority, displayName, fullSyncPeriod, return updated.addUserFederationProvider(providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync);
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -753,8 +705,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getLoginTheme() { public String getLoginTheme() {
if (updated != null) if (updated != null) return updated.getLoginTheme();
return updated.getLoginTheme();
return cached.getLoginTheme(); return cached.getLoginTheme();
} }
@ -766,8 +717,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getAccountTheme() { public String getAccountTheme() {
if (updated != null) if (updated != null) return updated.getAccountTheme();
return updated.getAccountTheme();
return cached.getAccountTheme(); return cached.getAccountTheme();
} }
@ -779,8 +729,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getAdminTheme() { public String getAdminTheme() {
if (updated != null) if (updated != null) return updated.getAdminTheme();
return updated.getAdminTheme();
return cached.getAdminTheme(); return cached.getAdminTheme();
} }
@ -792,8 +741,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public String getEmailTheme() { public String getEmailTheme() {
if (updated != null) if (updated != null) return updated.getEmailTheme();
return updated.getEmailTheme();
return cached.getEmailTheme(); return cached.getEmailTheme();
} }
@ -805,8 +753,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public int getNotBefore() { public int getNotBefore() {
if (updated != null) if (updated != null) return updated.getNotBefore();
return updated.getNotBefore();
return cached.getNotBefore(); return cached.getNotBefore();
} }
@ -825,8 +772,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean isEventsEnabled() { public boolean isEventsEnabled() {
if (updated != null) if (updated != null) return updated.isEventsEnabled();
return updated.isEventsEnabled();
return cached.isEventsEnabled(); return cached.isEventsEnabled();
} }
@ -838,8 +784,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public long getEventsExpiration() { public long getEventsExpiration() {
if (updated != null) if (updated != null) return updated.getEventsExpiration();
return updated.getEventsExpiration();
return cached.getEventsExpiration(); return cached.getEventsExpiration();
} }
@ -851,8 +796,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<String> getEventsListeners() { public Set<String> getEventsListeners() {
if (updated != null) if (updated != null) return updated.getEventsListeners();
return updated.getEventsListeners();
return cached.getEventsListeners(); return cached.getEventsListeners();
} }
@ -875,11 +819,9 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel getRole(String name) { public RoleModel getRole(String name) {
if (updated != null) if (updated != null) return updated.getRole(name);
return updated.getRole(name);
String id = cached.getRealmRoles().get(name); String id = cached.getRealmRoles().get(name);
if (id == null) if (id == null) return null;
return null;
return cacheSession.getRoleById(id, this); return cacheSession.getRoleById(id, this);
} }
@ -908,14 +850,12 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
if (updated != null) if (updated != null) return updated.getRoles();
return updated.getRoles();
Set<RoleModel> roles = new HashSet<RoleModel>(); Set<RoleModel> roles = new HashSet<RoleModel>();
for (String id : cached.getRealmRoles().values()) { for (String id : cached.getRealmRoles().values()) {
RoleModel roleById = cacheSession.getRoleById(id, this); RoleModel roleById = cacheSession.getRoleById(id, this);
if (roleById == null) if (roleById == null) continue;
continue;
roles.add(roleById); roles.add(roleById);
} }
return roles; return roles;
@ -924,24 +864,21 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel model = getApplicationById(id); ClientModel model = getApplicationById(id);
if (model != null) if (model != null) return model;
return model;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public boolean isIdentityFederationEnabled() { public boolean isIdentityFederationEnabled() {
if (updated != null) if (updated != null) return updated.isIdentityFederationEnabled();
return updated.isIdentityFederationEnabled();
return cached.isIdentityFederationEnabled(); return cached.isIdentityFederationEnabled();
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) return true;
return true; if (o == null || !(o instanceof RealmModel)) return false;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());

View file

@ -1,5 +1,19 @@
package org.keycloak.models.cache.entities; package org.keycloak.models.cache.entities;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClaimTypeModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.RealmCache;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -8,18 +22,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.cache.RealmCache;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -31,13 +33,13 @@ public class CachedRealm {
private boolean enabled; private boolean enabled;
private SslRequired sslRequired; private SslRequired sslRequired;
private boolean registrationAllowed; private boolean registrationAllowed;
protected boolean registrationEmailAsUsername; private boolean registrationEmailAsUsername;
private boolean rememberMe; private boolean rememberMe;
private boolean verifyEmail; private boolean verifyEmail;
private boolean passwordCredentialGrantAllowed; private boolean passwordCredentialGrantAllowed;
private boolean resetPasswordAllowed; private boolean resetPasswordAllowed;
private boolean identityFederationEnabled; private boolean identityFederationEnabled;
// --- brute force settings //--- brute force settings
private boolean bruteForceProtected; private boolean bruteForceProtected;
private int maxFailureWaitSeconds; private int maxFailureWaitSeconds;
private int minimumQuickLoginWaitSeconds; private int minimumQuickLoginWaitSeconds;
@ -45,7 +47,7 @@ public class CachedRealm {
private long quickLoginCheckMilliSeconds; private long quickLoginCheckMilliSeconds;
private int maxDeltaTimeSeconds; private int maxDeltaTimeSeconds;
private int failureFactor; private int failureFactor;
// --- end brute force settings //--- end brute force settings
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@ -97,7 +99,7 @@ public class CachedRealm {
passwordCredentialGrantAllowed = model.isPasswordCredentialGrantAllowed(); passwordCredentialGrantAllowed = model.isPasswordCredentialGrantAllowed();
resetPasswordAllowed = model.isResetPasswordAllowed(); resetPasswordAllowed = model.isResetPasswordAllowed();
identityFederationEnabled = model.isIdentityFederationEnabled(); identityFederationEnabled = model.isIdentityFederationEnabled();
// --- brute force settings //--- brute force settings
bruteForceProtected = model.isBruteForceProtected(); bruteForceProtected = model.isBruteForceProtected();
maxFailureWaitSeconds = model.getMaxFailureWaitSeconds(); maxFailureWaitSeconds = model.getMaxFailureWaitSeconds();
minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds(); minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds();
@ -105,7 +107,7 @@ public class CachedRealm {
quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds(); quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds();
maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds(); maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds();
failureFactor = model.getFailureFactor(); failureFactor = model.getFailureFactor();
// --- end brute force settings //--- end brute force settings
ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout(); ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout();
ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan(); ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan();
@ -164,6 +166,7 @@ public class CachedRealm {
} }
public String getId() { public String getId() {
return id; return id;
} }
@ -271,7 +274,6 @@ public class CachedRealm {
public int getAccessCodeLifespanUserAction() { public int getAccessCodeLifespanUserAction() {
return accessCodeLifespanUserAction; return accessCodeLifespanUserAction;
} }
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }

View file

@ -1,24 +1,5 @@
package org.keycloak.models.jpa; package org.keycloak.models.jpa;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
@ -40,6 +21,24 @@ import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.jpa.entities.UserFederationProviderEntity; import org.keycloak.models.jpa.entities.UserFederationProviderEntity;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
@ -219,7 +218,6 @@ public class RealmAdapter implements RealmModel {
} }
return result; return result;
} }
@Override @Override
public boolean isBruteForceProtected() { public boolean isBruteForceProtected() {
return getAttribute("bruteForceProtected", false); return getAttribute("bruteForceProtected", false);
@ -399,8 +397,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) if (certificate != null) return certificate;
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -437,8 +434,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) if (publicKey != null) return publicKey;
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -452,8 +448,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) if (privateKey != null) return privateKey;
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -513,8 +508,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public void updateRequiredCredentials(Set<String> creds) { public void updateRequiredCredentials(Set<String> creds) {
Collection<RequiredCredentialEntity> relationships = realm.getRequiredCredentials(); Collection<RequiredCredentialEntity> relationships = realm.getRequiredCredentials();
if (relationships == null) if (relationships == null) relationships = new ArrayList<RequiredCredentialEntity>();
relationships = new ArrayList<RequiredCredentialEntity>();
Set<String> already = new HashSet<String>(); Set<String> already = new HashSet<String>();
List<RequiredCredentialEntity> remove = new ArrayList<RequiredCredentialEntity>(); List<RequiredCredentialEntity> remove = new ArrayList<RequiredCredentialEntity>();
@ -537,12 +531,12 @@ public class RealmAdapter implements RealmModel {
em.flush(); em.flush();
} }
@Override @Override
public List<RequiredCredentialModel> getRequiredCredentials() { public List<RequiredCredentialModel> getRequiredCredentials() {
List<RequiredCredentialModel> requiredCredentialModels = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> requiredCredentialModels = new ArrayList<RequiredCredentialModel>();
Collection<RequiredCredentialEntity> entities = realm.getRequiredCredentials(); Collection<RequiredCredentialEntity> entities = realm.getRequiredCredentials();
if (entities == null) if (entities == null) return requiredCredentialModels;
return requiredCredentialModels;
for (RequiredCredentialEntity entity : entities) { for (RequiredCredentialEntity entity : entities) {
RequiredCredentialModel model = new RequiredCredentialModel(); RequiredCredentialModel model = new RequiredCredentialModel();
model.setFormLabel(entity.getFormLabel()); model.setFormLabel(entity.getFormLabel());
@ -551,15 +545,15 @@ public class RealmAdapter implements RealmModel {
model.setInput(entity.isInput()); model.setInput(entity.isInput());
requiredCredentialModels.add(model); requiredCredentialModels.add(model);
} }
return requiredCredentialModels; // To change body of implemented methods use File | Settings | File Templates. return requiredCredentialModels; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public List<String> getDefaultRoles() { public List<String> getDefaultRoles() {
Collection<RoleEntity> entities = realm.getDefaultRoles(); Collection<RoleEntity> entities = realm.getDefaultRoles();
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
if (entities == null) if (entities == null) return roles;
return roles;
for (RoleEntity entity : entities) { for (RoleEntity entity : entities) {
roles.add(entity.getName()); roles.add(entity.getName());
} }
@ -585,8 +579,7 @@ public class RealmAdapter implements RealmModel {
public static boolean contains(String str, String[] array) { public static boolean contains(String str, String[] array) {
for (String s : array) { for (String s : array) {
if (str.equals(s)) if (str.equals(s)) return true;
return true;
} }
return false; return false;
} }
@ -618,16 +611,14 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId); ClientModel model = getApplicationByName(clientId);
if (model != null) if (model != null) return model;
return model;
return getOAuthClient(clientId); return getOAuthClient(clientId);
} }
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel model = getApplicationById(id); ClientModel model = getApplicationById(id);
if (model != null) if (model != null) return model;
return model;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@ -637,14 +628,13 @@ public class RealmAdapter implements RealmModel {
for (ApplicationModel app : getApplications()) { for (ApplicationModel app : getApplications()) {
map.put(app.getName(), app); map.put(app.getName(), app);
} }
return map; // To change body of implemented methods use File | Settings | File Templates. return map; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
List<ApplicationModel> list = new ArrayList<ApplicationModel>(); List<ApplicationModel> list = new ArrayList<ApplicationModel>();
if (realm.getApplications() == null) if (realm.getApplications() == null) return list;
return list;
for (ApplicationEntity entity : realm.getApplications()) { for (ApplicationEntity entity : realm.getApplications()) {
list.add(new ApplicationAdapter(this, em, session, entity)); list.add(new ApplicationAdapter(this, em, session, entity));
} }
@ -684,11 +674,9 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeApplication(String id) { public boolean removeApplication(String id) {
if (id == null) if (id == null) return false;
return false;
ApplicationModel application = getApplicationById(id); ApplicationModel application = getApplicationById(id);
if (application == null) if (application == null) return false;
return false;
for (RoleModel role : application.getRoles()) { for (RoleModel role : application.getRoles()) {
application.removeRole(role); application.removeRole(role);
@ -762,22 +750,21 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeOAuthClient(String id) { public boolean removeOAuthClient(String id) {
OAuthClientModel oauth = getOAuthClientById(id); OAuthClientModel oauth = getOAuthClientById(id);
if (oauth == null) if (oauth == null) return false;
return false;
OAuthClientEntity client = em.getReference(OAuthClientEntity.class, oauth.getId()); OAuthClientEntity client = em.getReference(OAuthClientEntity.class, oauth.getId());
em.createNamedQuery("deleteScopeMappingByClient").setParameter("client", client).executeUpdate(); em.createNamedQuery("deleteScopeMappingByClient").setParameter("client", client).executeUpdate();
em.remove(client); em.remove(client);
return true; return true;
} }
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByName", OAuthClientEntity.class); TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByName", OAuthClientEntity.class);
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<OAuthClientEntity> entities = query.getResultList(); List<OAuthClientEntity> entities = query.getResultList();
if (entities.size() == 0) if (entities.size() == 0) return null;
return null;
return new OAuthClientAdapter(this, entities.get(0), em); return new OAuthClientAdapter(this, entities.get(0), em);
} }
@ -786,14 +773,14 @@ public class RealmAdapter implements RealmModel {
return session.realms().getOAuthClientById(id, this); return session.realms().getOAuthClientById(id, this);
} }
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByRealm", OAuthClientEntity.class); TypedQuery<OAuthClientEntity> query = em.createNamedQuery("findOAuthClientByRealm", OAuthClientEntity.class);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<OAuthClientEntity> entities = query.getResultList(); List<OAuthClientEntity> entities = query.getResultList();
List<OAuthClientModel> list = new ArrayList<OAuthClientModel>(); List<OAuthClientModel> list = new ArrayList<OAuthClientModel>();
for (OAuthClientEntity entity : entities) for (OAuthClientEntity entity : entities) list.add(new OAuthClientAdapter(this, entity, em));
list.add(new OAuthClientAdapter(this, entity, em));
return list; return list;
} }
@ -847,17 +834,15 @@ public class RealmAdapter implements RealmModel {
}); });
List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new ArrayList<UserFederationProviderModel>();
for (UserFederationProviderEntity entity : copy) { for (UserFederationProviderEntity entity : copy) {
result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(),
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync()));
.getLastSync()));
} }
return result; return result;
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
String id = KeycloakModelUtils.generateId(); String id = KeycloakModelUtils.generateId();
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
entity.setId(id); entity.setId(id);
@ -875,8 +860,7 @@ public class RealmAdapter implements RealmModel {
em.persist(entity); em.persist(entity);
realm.getUserFederationProviders().add(entity); realm.getUserFederationProviders().add(entity);
em.flush(); em.flush();
return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync);
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -892,7 +876,6 @@ public class RealmAdapter implements RealmModel {
} }
} }
} }
@Override @Override
public void updateUserFederationProvider(UserFederationProviderModel model) { public void updateUserFederationProvider(UserFederationProviderModel model) {
Iterator<UserFederationProviderEntity> it = realm.getUserFederationProviders().iterator(); Iterator<UserFederationProviderEntity> it = realm.getUserFederationProviders().iterator();
@ -940,13 +923,9 @@ public class RealmAdapter implements RealmModel {
} }
} }
if (found) if (found) continue;
continue; session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(),
session.users().preRemove( entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync()));
this,
new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(),
entity.getLastSync()));
it.remove(); it.remove();
em.remove(entity); em.remove(entity);
} }
@ -960,16 +939,13 @@ public class RealmAdapter implements RealmModel {
break; break;
} }
} }
if (!found) if (!found) add.add(model);
add.add(model);
} }
for (UserFederationProviderModel model : add) { for (UserFederationProviderModel model : add) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
if (model.getId() != null) if (model.getId() != null) entity.setId(model.getId());
entity.setId(model.getId()); else entity.setId(KeycloakModelUtils.generateId());
else
entity.setId(KeycloakModelUtils.generateId());
entity.setConfig(model.getConfig()); entity.setConfig(model.getConfig());
entity.setPriority(model.getPriority()); entity.setPriority(model.getPriority());
entity.setProviderName(model.getProviderName()); entity.setProviderName(model.getProviderName());
@ -994,8 +970,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<RoleEntity> roles = query.getResultList(); List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) if (roles.size() == 0) return null;
return null;
return new RoleAdapter(this, em, roles.get(0)); return new RoleAdapter(this, em, roles.get(0));
} }
@ -1022,15 +997,13 @@ public class RealmAdapter implements RealmModel {
if (role == null) { if (role == null) {
return false; return false;
} }
if (!role.getContainer().equals(this)) if (!role.getContainer().equals(this)) return false;
return false;
session.users().preRemove(this, role); session.users().preRemove(this, role);
RoleEntity roleEntity = RoleAdapter.toRoleEntity(role, em); RoleEntity roleEntity = RoleAdapter.toRoleEntity(role, em);
realm.getRoles().remove(role); realm.getRoles().remove(role);
realm.getDefaultRoles().remove(role); realm.getDefaultRoles().remove(role);
em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", roleEntity) em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", roleEntity).executeUpdate();
.executeUpdate();
em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", roleEntity).executeUpdate(); em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", roleEntity).executeUpdate();
em.remove(roleEntity); em.remove(roleEntity);
@ -1042,8 +1015,7 @@ public class RealmAdapter implements RealmModel {
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>(); Set<RoleModel> list = new HashSet<RoleModel>();
Collection<RoleEntity> roles = realm.getRoles(); Collection<RoleEntity> roles = realm.getRoles();
if (roles == null) if (roles == null) return list;
return list;
for (RoleEntity entity : roles) { for (RoleEntity entity : roles) {
list.add(new RoleAdapter(this, em, entity)); list.add(new RoleAdapter(this, em, entity));
} }
@ -1058,8 +1030,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean removeRoleById(String id) { public boolean removeRoleById(String id) {
RoleModel role = getRoleById(id); RoleModel role = getRoleById(id);
if (role == null) if (role == null) return false;
return false;
return role.getContainer().removeRole(role); return role.getContainer().removeRole(role);
} }
@ -1080,10 +1051,8 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) return true;
return true; if (o == null || !(o instanceof RealmModel)) return false;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());
@ -1178,7 +1147,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public void setMasterAdminApp(ApplicationModel app) { public void setMasterAdminApp(ApplicationModel app) {
ApplicationEntity appEntity = app != null ? em.getReference(ApplicationEntity.class, app.getId()) : null; ApplicationEntity appEntity = app!=null ? em.getReference(ApplicationEntity.class, app.getId()) : null;
realm.setMasterAdminApp(appEntity); realm.setMasterAdminApp(appEntity);
em.flush(); em.flush();
} }
@ -1187,7 +1156,7 @@ public class RealmAdapter implements RealmModel {
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>(); List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>();
for (IdentityProviderEntity entity : realm.getIdentityProviders()) { for (IdentityProviderEntity entity: realm.getIdentityProviders()) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel(); IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setProviderId(entity.getProviderId()); identityProviderModel.setProviderId(entity.getProviderId());

View file

@ -1,13 +1,5 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
@ -23,117 +15,126 @@ import javax.persistence.NamedQuery;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Table(name = "REALM") @Table(name="REALM")
@Entity @Entity
@NamedQueries({ @NamedQuery(name = "getAllRealms", query = "select realm from RealmEntity realm"), @NamedQueries({
@NamedQuery(name = "getRealmByName", query = "select realm from RealmEntity realm where realm.name = :name"), }) @NamedQuery(name="getAllRealms", query="select realm from RealmEntity realm"),
@NamedQuery(name="getRealmByName", query="select realm from RealmEntity realm where realm.name = :name"),
})
public class RealmEntity { public class RealmEntity {
@Id @Id
@Column(name = "ID", length = 36) @Column(name="ID", length = 36)
protected String id; protected String id;
@Column(name = "NAME", unique = true) @Column(name="NAME", unique = true)
protected String name; protected String name;
@Column(name = "ENABLED") @Column(name="ENABLED")
protected boolean enabled; protected boolean enabled;
@Column(name = "SSL_REQUIRED") @Column(name="SSL_REQUIRED")
protected String sslRequired; protected String sslRequired;
@Column(name = "REGISTRATION_ALLOWED") @Column(name="REGISTRATION_ALLOWED")
protected boolean registrationAllowed; protected boolean registrationAllowed;
@Column(name = "REGISTRATION_EMAIL_AS_USERNAME") @Column(name = "REGISTRATION_EMAIL_AS_USERNAME")
protected boolean registrationEmailAsUsername; protected boolean registrationEmailAsUsername;
@Column(name = "PASSWORD_CRED_GRANT_ALLOWED") @Column(name="PASSWORD_CRED_GRANT_ALLOWED")
protected boolean passwordCredentialGrantAllowed; protected boolean passwordCredentialGrantAllowed;
@Column(name = "VERIFY_EMAIL") @Column(name="VERIFY_EMAIL")
protected boolean verifyEmail; protected boolean verifyEmail;
@Column(name = "RESET_PASSWORD_ALLOWED") @Column(name="RESET_PASSWORD_ALLOWED")
protected boolean resetPasswordAllowed; protected boolean resetPasswordAllowed;
@Column(name = "REMEMBER_ME") @Column(name="REMEMBER_ME")
protected boolean rememberMe; protected boolean rememberMe;
@Column(name = "PASSWORD_POLICY") @Column(name="PASSWORD_POLICY")
protected String passwordPolicy; protected String passwordPolicy;
@Column(name = "SSO_IDLE_TIMEOUT") @Column(name="SSO_IDLE_TIMEOUT")
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
@Column(name = "SSO_MAX_LIFESPAN") @Column(name="SSO_MAX_LIFESPAN")
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@Column(name = "ACCESS_TOKEN_LIFESPAN") @Column(name="ACCESS_TOKEN_LIFESPAN")
protected int accessTokenLifespan; protected int accessTokenLifespan;
@Column(name = "ACCESS_CODE_LIFESPAN") @Column(name="ACCESS_CODE_LIFESPAN")
protected int accessCodeLifespan; protected int accessCodeLifespan;
@Column(name = "USER_ACTION_LIFESPAN") @Column(name="USER_ACTION_LIFESPAN")
protected int accessCodeLifespanUserAction; protected int accessCodeLifespanUserAction;
@Column(name = "LOGIN_LIFESPAN") @Column(name="LOGIN_LIFESPAN")
protected int accessCodeLifespanLogin; protected int accessCodeLifespanLogin;
@Column(name = "NOT_BEFORE") @Column(name="NOT_BEFORE")
protected int notBefore; protected int notBefore;
@Column(name = "PUBLIC_KEY", length = 2048) @Column(name="PUBLIC_KEY", length = 2048)
protected String publicKeyPem; protected String publicKeyPem;
@Column(name = "PRIVATE_KEY", length = 2048) @Column(name="PRIVATE_KEY", length = 2048)
protected String privateKeyPem; protected String privateKeyPem;
@Column(name = "CERTIFICATE", length = 2048) @Column(name="CERTIFICATE", length = 2048)
protected String certificatePem; protected String certificatePem;
@Column(name = "CODE_SECRET", length = 255) @Column(name="CODE_SECRET", length = 255)
protected String codeSecret; protected String codeSecret;
@Column(name = "LOGIN_THEME") @Column(name="LOGIN_THEME")
protected String loginTheme; protected String loginTheme;
@Column(name = "ACCOUNT_THEME") @Column(name="ACCOUNT_THEME")
protected String accountTheme; protected String accountTheme;
@Column(name = "ADMIN_THEME") @Column(name="ADMIN_THEME")
protected String adminTheme; protected String adminTheme;
@Column(name = "EMAIL_THEME") @Column(name="EMAIL_THEME")
protected String emailTheme; protected String emailTheme;
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm") @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
Collection<RealmAttributeEntity> attributes = new ArrayList<RealmAttributeEntity>(); Collection<RealmAttributeEntity> attributes = new ArrayList<RealmAttributeEntity>();
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm") @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>(); Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true) @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name = "FED_PROVIDERS") @JoinTable(name="FED_PROVIDERS")
List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>(); List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name = "REALM_APPLICATION", joinColumns = { @JoinColumn(name = "APPLICATION_ID") }, inverseJoinColumns = { @JoinColumn(name = "REALM_ID") }) @JoinTable(name="REALM_APPLICATION", joinColumns={ @JoinColumn(name="APPLICATION_ID") }, inverseJoinColumns={ @JoinColumn(name="REALM_ID") })
Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>(); Collection<ApplicationEntity> applications = new ArrayList<ApplicationEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm") @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
Collection<RoleEntity> roles = new ArrayList<RoleEntity>(); Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@ElementCollection @ElementCollection
@MapKeyColumn(name = "NAME") @MapKeyColumn(name="NAME")
@Column(name = "VALUE") @Column(name="VALUE")
@CollectionTable(name = "REALM_SMTP_CONFIG", joinColumns = { @JoinColumn(name = "REALM_ID") }) @CollectionTable(name="REALM_SMTP_CONFIG", joinColumns={ @JoinColumn(name="REALM_ID") })
protected Map<String, String> smtpConfig = new HashMap<String, String>(); protected Map<String, String> smtpConfig = new HashMap<String, String>();
@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name = "REALM_DEFAULT_ROLES", joinColumns = { @JoinColumn(name = "REALM_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") }) @JoinTable(name="REALM_DEFAULT_ROLES", joinColumns = { @JoinColumn(name="REALM_ID")}, inverseJoinColumns = { @JoinColumn(name="ROLE_ID")})
protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>(); protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>();
@Column(name = "EVENTS_ENABLED") @Column(name="EVENTS_ENABLED")
protected boolean eventsEnabled; protected boolean eventsEnabled;
@Column(name = "EVENTS_EXPIRATION") @Column(name="EVENTS_EXPIRATION")
protected long eventsExpiration; protected long eventsExpiration;
@ElementCollection @ElementCollection
@Column(name = "VALUE") @Column(name="VALUE")
@CollectionTable(name = "REALM_EVENTS_LISTENERS", joinColumns = { @JoinColumn(name = "REALM_ID") }) @CollectionTable(name="REALM_EVENTS_LISTENERS", joinColumns={ @JoinColumn(name="REALM_ID") })
protected Set<String> eventsListeners = new HashSet<String>(); protected Set<String> eventsListeners = new HashSet<String>();
@OneToOne @OneToOne
@JoinColumn(name = "MASTER_ADMIN_APP") @JoinColumn(name="MASTER_ADMIN_APP")
protected ApplicationEntity masterAdminApp; protected ApplicationEntity masterAdminApp;
@OneToMany(cascade = { CascadeType.REMOVE }, orphanRemoval = true, mappedBy = "realm") @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>(); protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>();
public String getId() { public String getId() {
@ -255,7 +256,6 @@ public class RealmEntity {
public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) { public void setAccessCodeLifespanUserAction(int accessCodeLifespanUserAction) {
this.accessCodeLifespanUserAction = accessCodeLifespanUserAction; this.accessCodeLifespanUserAction = accessCodeLifespanUserAction;
} }
public int getAccessCodeLifespanLogin() { public int getAccessCodeLifespanLogin() {
return accessCodeLifespanLogin; return accessCodeLifespanLogin;
} }
@ -453,3 +453,4 @@ public class RealmEntity {
} }
} }

View file

@ -1,21 +1,7 @@
package org.keycloak.models.mongo.keycloak.adapters; package org.keycloak.models.mongo.keycloak.adapters;
import java.security.Key; import com.mongodb.DBObject;
import java.security.PrivateKey; import com.mongodb.QueryBuilder;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
@ -38,8 +24,21 @@ import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import com.mongodb.DBObject; import java.security.Key;
import com.mongodb.QueryBuilder; import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
@ -57,8 +56,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
private volatile transient PasswordPolicy passwordPolicy; private volatile transient PasswordPolicy passwordPolicy;
private volatile transient KeycloakSession session; private volatile transient KeycloakSession session;
public RealmAdapter(KeycloakSession session, MongoRealmEntity realmEntity, public RealmAdapter(KeycloakSession session, MongoRealmEntity realmEntity, MongoStoreInvocationContext invocationContext) {
MongoStoreInvocationContext invocationContext) {
super(invocationContext); super(invocationContext);
this.realm = realmEntity; this.realm = realmEntity;
this.session = session; this.session = session;
@ -200,6 +198,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public int getMaxDeltaTimeSeconds() { public int getMaxDeltaTimeSeconds() {
return realm.getMaxDeltaTimeSeconds(); return realm.getMaxDeltaTimeSeconds();
@ -222,6 +221,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public boolean isVerifyEmail() { public boolean isVerifyEmail() {
return realm.isVerifyEmail(); return realm.isVerifyEmail();
@ -270,6 +270,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public int getSsoSessionIdleTimeout() { public int getSsoSessionIdleTimeout() {
return realm.getSsoSessionIdleTimeout(); return realm.getSsoSessionIdleTimeout();
@ -350,8 +351,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
if (certificate != null) if (certificate != null) return certificate;
return certificate;
certificate = KeycloakModelUtils.getCertificate(getCertificatePem()); certificate = KeycloakModelUtils.getCertificate(getCertificatePem());
return certificate; return certificate;
} }
@ -375,6 +375,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
} }
@Override @Override
public String getPrivateKeyPem() { public String getPrivateKeyPem() {
return realm.getPrivateKeyPem(); return realm.getPrivateKeyPem();
@ -389,8 +390,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
if (publicKey != null) if (publicKey != null) return publicKey;
return publicKey;
publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem()); publicKey = KeycloakModelUtils.getPublicKey(getPublicKeyPem());
return publicKey; return publicKey;
} }
@ -404,8 +404,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
if (privateKey != null) if (privateKey != null) return privateKey;
return privateKey;
privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem()); privateKey = KeycloakModelUtils.getPrivateKey(getPrivateKeyPem());
return privateKey; return privateKey;
} }
@ -482,7 +481,10 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public RoleAdapter getRole(String name) { public RoleAdapter getRole(String name) {
DBObject query = new QueryBuilder().and("name").is(name).and("realmId").is(getId()).get(); DBObject query = new QueryBuilder()
.and("name").is(name)
.and("realmId").is(getId())
.get();
MongoRoleEntity role = getMongoStore().loadSingleEntity(MongoRoleEntity.class, query, invocationContext); MongoRoleEntity role = getMongoStore().loadSingleEntity(MongoRoleEntity.class, query, invocationContext);
if (role == null) { if (role == null) {
return null; return null;
@ -516,21 +518,21 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public boolean removeRoleById(String id) { public boolean removeRoleById(String id) {
RoleModel role = getRoleById(id); RoleModel role = getRoleById(id);
if (role == null) if (role == null) return false;
return false;
session.users().preRemove(this, role); session.users().preRemove(this, role);
return getMongoStore().removeEntity(MongoRoleEntity.class, id, invocationContext); return getMongoStore().removeEntity(MongoRoleEntity.class, id, invocationContext);
} }
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
DBObject query = new QueryBuilder().and("realmId").is(getId()).get(); DBObject query = new QueryBuilder()
.and("realmId").is(getId())
.get();
List<MongoRoleEntity> roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext); List<MongoRoleEntity> roles = getMongoStore().loadEntities(MongoRoleEntity.class, query, invocationContext);
Set<RoleModel> result = new HashSet<RoleModel>(); Set<RoleModel> result = new HashSet<RoleModel>();
if (roles == null) if (roles == null) return result;
return result;
for (MongoRoleEntity role : roles) { for (MongoRoleEntity role : roles) {
result.add(new RoleAdapter(session, this, role, this, invocationContext)); result.add(new RoleAdapter(session, this, role, this, invocationContext));
} }
@ -577,19 +579,19 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
ClientModel model = getApplicationByName(clientId); ClientModel model = getApplicationByName(clientId);
if (model != null) if (model != null) return model;
return model;
return getOAuthClient(clientId); return getOAuthClient(clientId);
} }
@Override @Override
public ClientModel findClientById(String id) { public ClientModel findClientById(String id) {
ClientModel model = getApplicationById(id); ClientModel model = getApplicationById(id);
if (model != null) if (model != null) return model;
return model;
return getOAuthClientById(id); return getOAuthClientById(id);
} }
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
return model.getApplicationById(id, this); return model.getApplicationById(id, this);
@ -597,9 +599,11 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
DBObject query = new QueryBuilder().and("realmId").is(getId()).and("name").is(name).get(); DBObject query = new QueryBuilder()
MongoApplicationEntity appEntity = getMongoStore().loadSingleEntity(MongoApplicationEntity.class, query, .and("realmId").is(getId())
invocationContext); .and("name").is(name)
.get();
MongoApplicationEntity appEntity = getMongoStore().loadSingleEntity(MongoApplicationEntity.class, query, invocationContext);
return appEntity == null ? null : new ApplicationAdapter(session, this, appEntity, invocationContext); return appEntity == null ? null : new ApplicationAdapter(session, this, appEntity, invocationContext);
} }
@ -614,9 +618,10 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
DBObject query = new QueryBuilder().and("realmId").is(getId()).get(); DBObject query = new QueryBuilder()
List<MongoApplicationEntity> appDatas = getMongoStore().loadEntities(MongoApplicationEntity.class, query, .and("realmId").is(getId())
invocationContext); .get();
List<MongoApplicationEntity> appDatas = getMongoStore().loadEntities(MongoApplicationEntity.class, query, invocationContext);
List<ApplicationModel> result = new ArrayList<ApplicationModel>(); List<ApplicationModel> result = new ArrayList<ApplicationModel>();
for (MongoApplicationEntity appData : appDatas) { for (MongoApplicationEntity appData : appDatas) {
@ -694,9 +699,11 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
DBObject query = new QueryBuilder().and("realmId").is(getId()).and("name").is(name).get(); DBObject query = new QueryBuilder()
MongoOAuthClientEntity oauthClient = getMongoStore().loadSingleEntity(MongoOAuthClientEntity.class, query, .and("realmId").is(getId())
invocationContext); .and("name").is(name)
.get();
MongoOAuthClientEntity oauthClient = getMongoStore().loadSingleEntity(MongoOAuthClientEntity.class, query, invocationContext);
return oauthClient == null ? null : new OAuthClientAdapter(session, this, oauthClient, invocationContext); return oauthClient == null ? null : new OAuthClientAdapter(session, this, oauthClient, invocationContext);
} }
@ -707,9 +714,10 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
DBObject query = new QueryBuilder().and("realmId").is(getId()).get(); DBObject query = new QueryBuilder()
List<MongoOAuthClientEntity> results = getMongoStore().loadEntities(MongoOAuthClientEntity.class, query, .and("realmId").is(getId())
invocationContext); .get();
List<MongoOAuthClientEntity> results = getMongoStore().loadEntities(MongoOAuthClientEntity.class, query, invocationContext);
List<OAuthClientModel> list = new ArrayList<OAuthClientModel>(); List<OAuthClientModel> list = new ArrayList<OAuthClientModel>();
for (MongoOAuthClientEntity data : results) { for (MongoOAuthClientEntity data : results) {
list.add(new OAuthClientAdapter(session, this, data, invocationContext)); list.add(new OAuthClientAdapter(session, this, data, invocationContext));
@ -723,8 +731,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
addRequiredCredential(credentialModel, realm.getRequiredCredentials()); addRequiredCredential(credentialModel, realm.getRequiredCredentials());
} }
protected void addRequiredCredential(RequiredCredentialModel credentialModel, protected void addRequiredCredential(RequiredCredentialModel credentialModel, List<RequiredCredentialEntity> persistentCollection) {
List<RequiredCredentialEntity> persistentCollection) {
RequiredCredentialEntity credEntity = new RequiredCredentialEntity(); RequiredCredentialEntity credEntity = new RequiredCredentialEntity();
credEntity.setType(credentialModel.getType()); credEntity.setType(credentialModel.getType());
credEntity.setFormLabel(credentialModel.getFormLabel()); credEntity.setFormLabel(credentialModel.getFormLabel());
@ -768,8 +775,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
return convertRequiredCredentialEntities(realm.getRequiredCredentials()); return convertRequiredCredentialEntities(realm.getRequiredCredentials());
} }
protected List<RequiredCredentialModel> convertRequiredCredentialEntities( protected List<RequiredCredentialModel> convertRequiredCredentialEntities(Collection<RequiredCredentialEntity> credEntities) {
Collection<RequiredCredentialEntity> credEntities) {
List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>(); List<RequiredCredentialModel> result = new ArrayList<RequiredCredentialModel>();
for (RequiredCredentialEntity entity : credEntities) { for (RequiredCredentialEntity entity : credEntities) {
@ -818,11 +824,12 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
updateRealm(); updateRealm();
} }
@Override @Override
public List<IdentityProviderModel> getIdentityProviders() { public List<IdentityProviderModel> getIdentityProviders() {
List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>(); List<IdentityProviderModel> identityProviders = new ArrayList<IdentityProviderModel>();
for (IdentityProviderEntity entity : realm.getIdentityProviders()) { for (IdentityProviderEntity entity: realm.getIdentityProviders()) {
IdentityProviderModel identityProviderModel = new IdentityProviderModel(); IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setProviderId(entity.getProviderId()); identityProviderModel.setProviderId(entity.getProviderId());
@ -900,8 +907,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
} }
@Override @Override
public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, public UserFederationProviderModel addUserFederationProvider(String providerName, Map<String, String> config, int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
int priority, String displayName, int fullSyncPeriod, int changedSyncPeriod, int lastSync) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
entity.setId(KeycloakModelUtils.generateId()); entity.setId(KeycloakModelUtils.generateId());
entity.setPriority(priority); entity.setPriority(priority);
@ -917,8 +923,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
realm.getUserFederationProviders().add(entity); realm.getUserFederationProviders().add(entity);
updateRealm(); updateRealm();
return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, return new UserFederationProviderModel(entity.getId(), providerName, config, priority, displayName, fullSyncPeriod, changedSyncPeriod, lastSync);
changedSyncPeriod, lastSync);
} }
@Override @Override
@ -927,11 +932,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
while (it.hasNext()) { while (it.hasNext()) {
UserFederationProviderEntity entity = it.next(); UserFederationProviderEntity entity = it.next();
if (entity.getId().equals(provider.getId())) { if (entity.getId().equals(provider.getId())) {
session.users().preRemove( session.users().preRemove(this, new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(),
this, entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync()));
new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(),
entity.getLastSync()));
it.remove(); it.remove();
} }
} }
@ -977,9 +979,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
}); });
List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>(); List<UserFederationProviderModel> result = new LinkedList<UserFederationProviderModel>();
for (UserFederationProviderEntity entity : copy) { for (UserFederationProviderEntity entity : copy) {
result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity result.add(new UserFederationProviderModel(entity.getId(), entity.getProviderName(), entity.getConfig(), entity.getPriority(), entity.getDisplayName(),
.getPriority(), entity.getDisplayName(), entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity entity.getFullSyncPeriod(), entity.getChangedSyncPeriod(), entity.getLastSync()));
.getLastSync()));
} }
return result; return result;
@ -990,10 +991,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>(); List<UserFederationProviderEntity> entities = new LinkedList<UserFederationProviderEntity>();
for (UserFederationProviderModel model : providers) { for (UserFederationProviderModel model : providers) {
UserFederationProviderEntity entity = new UserFederationProviderEntity(); UserFederationProviderEntity entity = new UserFederationProviderEntity();
if (model.getId() != null) if (model.getId() != null) entity.setId(model.getId());
entity.setId(model.getId()); else entity.setId(KeycloakModelUtils.generateId());
else
entity.setId(KeycloakModelUtils.generateId());
entity.setProviderName(model.getProviderName()); entity.setProviderName(model.getProviderName());
entity.setConfig(model.getConfig()); entity.setConfig(model.getConfig());
entity.setPriority(model.getPriority()); entity.setPriority(model.getPriority());
@ -1051,8 +1050,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public ApplicationModel getMasterAdminApp() { public ApplicationModel getMasterAdminApp() {
MongoApplicationEntity appData = getMongoStore().loadEntity(MongoApplicationEntity.class, realm.getAdminAppId(), MongoApplicationEntity appData = getMongoStore().loadEntity(MongoApplicationEntity.class, realm.getAdminAppId(), invocationContext);
invocationContext);
return appData != null ? new ApplicationAdapter(session, this, appData, invocationContext) : null; return appData != null ? new ApplicationAdapter(session, this, appData, invocationContext) : null;
} }
@ -1075,10 +1073,8 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) return true;
return true; if (o == null || !(o instanceof RealmModel)) return false;
if (o == null || !(o instanceof RealmModel))
return false;
RealmModel that = (RealmModel) o; RealmModel that = (RealmModel) o;
return that.getId().equals(getId()); return that.getId().equals(getId());
@ -1089,4 +1085,5 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
return getId().hashCode(); return getId().hashCode();
} }
} }

View file

@ -21,25 +21,6 @@
*/ */
package org.keycloak.services.resources; package org.keycloak.services.resources;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.ClientConnection; import org.keycloak.ClientConnection;
@ -75,6 +56,24 @@ import org.keycloak.services.resources.flows.Urls;
import org.keycloak.services.util.CookieHelper; import org.keycloak.services.util.CookieHelper;
import org.keycloak.services.validation.Validation; import org.keycloak.services.validation.Validation;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/** /**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/ */
@ -151,6 +150,7 @@ public class LoginActionsService {
} }
} }
private class Checks { private class Checks {
ClientSessionCode clientCode; ClientSessionCode clientCode;
Response response; Response response;
@ -253,6 +253,7 @@ public class LoginActionsService {
ClientSessionCode clientSessionCode = checks.clientCode; ClientSessionCode clientSessionCode = checks.clientCode;
ClientSessionModel clientSession = clientSessionCode.getClientSession(); ClientSessionModel clientSession = clientSessionCode.getClientSession();
authManager.expireIdentityCookie(realm, uriInfo, clientConnection); authManager.expireIdentityCookie(realm, uriInfo, clientConnection);
return Flows.forms(session, realm, clientSession.getClient(), uriInfo) return Flows.forms(session, realm, clientSession.getClient(), uriInfo)
@ -314,6 +315,7 @@ public class LoginActionsService {
event.detail(Details.REMEMBER_ME, "true"); event.detail(Details.REMEMBER_ME, "true");
} }
ClientModel client = clientSession.getClient(); ClientModel client = clientSession.getClient();
if (client == null) { if (client == null) {
event.error(Errors.CLIENT_NOT_FOUND); event.error(Errors.CLIENT_NOT_FOUND);
@ -455,6 +457,7 @@ public class LoginActionsService {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Login requester not enabled."); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Login requester not enabled.");
} }
List<String> requiredCredentialTypes = new LinkedList<String>(); List<String> requiredCredentialTypes = new LinkedList<String>();
for (RequiredCredentialModel m : realm.getRequiredCredentials()) { for (RequiredCredentialModel m : realm.getRequiredCredentials()) {
requiredCredentialTypes.add(m.getType()); requiredCredentialTypes.add(m.getType());
@ -547,6 +550,7 @@ public class LoginActionsService {
public Response processConsent(final MultivaluedMap<String, String> formData) { public Response processConsent(final MultivaluedMap<String, String> formData) {
event.event(EventType.LOGIN).detail(Details.RESPONSE_TYPE, "code"); event.event(EventType.LOGIN).detail(Details.RESPONSE_TYPE, "code");
if (!checkSsl()) { if (!checkSsl()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required"); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required");
} }
@ -597,6 +601,9 @@ public class LoginActionsService {
return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo, clientConnection); return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo, clientConnection);
} }
@Path("profile") @Path("profile")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ -701,7 +708,8 @@ public class LoginActionsService {
@Path("password") @Path("password")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updatePassword(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) { public Response updatePassword(@QueryParam("code") String code,
final MultivaluedMap<String, String> formData) {
event.event(EventType.UPDATE_PASSWORD); event.event(EventType.UPDATE_PASSWORD);
Checks checks = new Checks(); Checks checks = new Checks();
if (!checks.check(code, ClientSessionModel.Action.UPDATE_PASSWORD, ClientSessionModel.Action.RECOVER_PASSWORD)) { if (!checks.check(code, ClientSessionModel.Action.UPDATE_PASSWORD, ClientSessionModel.Action.RECOVER_PASSWORD)) {
@ -752,6 +760,7 @@ public class LoginActionsService {
return redirectOauth(user, accessCode, clientSession, userSession); return redirectOauth(user, accessCode, clientSession, userSession);
} }
@Path("email-verification") @Path("email-verification")
@GET @GET
public Response emailVerification(@QueryParam("code") String code, @QueryParam("key") String key) { public Response emailVerification(@QueryParam("code") String code, @QueryParam("key") String key) {
@ -822,7 +831,8 @@ public class LoginActionsService {
@Path("password-reset") @Path("password-reset")
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sendPasswordReset(@QueryParam("code") String code, final MultivaluedMap<String, String> formData) { public Response sendPasswordReset(@QueryParam("code") String code,
final MultivaluedMap<String, String> formData) {
event.event(EventType.SEND_RESET_PASSWORD); event.event(EventType.SEND_RESET_PASSWORD);
if (!checkSsl()) { if (!checkSsl()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required"); return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "HTTPS required");
@ -863,11 +873,12 @@ public class LoginActionsService {
if (user == null) { if (user == null) {
event.error(Errors.USER_NOT_FOUND); event.error(Errors.USER_NOT_FOUND);
} else if (!user.isEnabled()) { } else if(!user.isEnabled()) {
event.user(user).error(Errors.USER_DISABLED); event.user(user).error(Errors.USER_DISABLED);
} else if (user.getEmail() == null || user.getEmail().trim().length() == 0) { }
else if(user.getEmail() == null || user.getEmail().trim().length() == 0) {
event.user(user).error(Errors.INVALID_EMAIL); event.user(user).error(Errors.INVALID_EMAIL);
} else { } else{
event.user(user); event.user(user);
UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false); UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false);
@ -902,21 +913,16 @@ public class LoginActionsService {
private String getActionCookie() { private String getActionCookie() {
Cookie cookie = headers.getCookies().get(ACTION_COOKIE); Cookie cookie = headers.getCookies().get(ACTION_COOKIE);
AuthenticationManager.expireCookie(realm, ACTION_COOKIE, AuthenticationManager.getRealmCookiePath(realm, uriInfo), AuthenticationManager.expireCookie(realm, ACTION_COOKIE, AuthenticationManager.getRealmCookiePath(realm, uriInfo), realm.getSslRequired().isRequired(clientConnection), clientConnection);
realm.getSslRequired().isRequired(clientConnection), clientConnection);
return cookie != null ? cookie.getValue() : null; return cookie != null ? cookie.getValue() : null;
} }
public static void createActionCookie(RealmModel realm, UriInfo uriInfo, ClientConnection clientConnection, public static void createActionCookie(RealmModel realm, UriInfo uriInfo, ClientConnection clientConnection, String sessionId) {
String sessionId) { CookieHelper.addCookie(ACTION_COOKIE, sessionId, AuthenticationManager.getRealmCookiePath(realm, uriInfo), null, null, -1, realm.getSslRequired().isRequired(clientConnection), true);
CookieHelper.addCookie(ACTION_COOKIE, sessionId, AuthenticationManager.getRealmCookiePath(realm, uriInfo), null,
null, -1, realm.getSslRequired().isRequired(clientConnection), true);
} }
private Response redirectOauth(UserModel user, ClientSessionCode accessCode, ClientSessionModel clientSession, private Response redirectOauth(UserModel user, ClientSessionCode accessCode, ClientSessionModel clientSession, UserSessionModel userSession) {
UserSessionModel userSession) { return AuthenticationManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request, uriInfo, event);
return AuthenticationManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection,
request, uriInfo, event);
} }
private void initEvent(ClientSessionModel clientSession) { private void initEvent(ClientSessionModel clientSession) {

View file

@ -1,15 +1,14 @@
package org.keycloak.services.validation; package org.keycloak.services.validation;
import java.util.List;
import java.util.regex.Pattern;
import javax.ws.rs.core.MultivaluedMap;
import org.keycloak.models.PasswordPolicy; import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.messages.Messages; import org.keycloak.services.messages.Messages;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List;
import java.util.regex.Pattern;
public class Validation { public class Validation {
// Actually allow same emails like angular. See ValidationTest.testEmailValidation() // Actually allow same emails like angular. See ValidationTest.testEmailValidation()
@ -81,4 +80,5 @@ public class Validation {
return EMAIL_PATTERN.matcher(email).matches(); return EMAIL_PATTERN.matcher(email).matches();
} }
} }

View file

@ -21,21 +21,6 @@
*/ */
package org.keycloak.testsuite.admin; package org.keycloak.testsuite.admin;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.junit.Assert; import org.junit.Assert;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Test; import org.junit.Test;
@ -56,6 +41,20 @@ import org.keycloak.services.resources.admin.AdminRoot;
import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testutils.KeycloakServer; import org.keycloak.testutils.KeycloakServer;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** /**
* Tests Undertow Adapter * Tests Undertow Adapter
* *
@ -102,6 +101,7 @@ public class AdminAPITest {
String realmName = rep.getRealm(); String realmName = rep.getRealm();
WebTarget realmTarget = adminRealms.path(realmName); WebTarget realmTarget = adminRealms.path(realmName);
// create with just name, enabled, and id, just like admin console // create with just name, enabled, and id, just like admin console
RealmRepresentation newRep = new RealmRepresentation(); RealmRepresentation newRep = new RealmRepresentation();
newRep.setRealm(rep.getRealm()); newRep.setRealm(rep.getRealm());
@ -125,8 +125,7 @@ public class AdminAPITest {
WebTarget applicationsTarget = realmTarget.path("applications"); WebTarget applicationsTarget = realmTarget.path("applications");
for (ApplicationRepresentation appRep : rep.getApplications()) { for (ApplicationRepresentation appRep : rep.getApplications()) {
ApplicationRepresentation newApp = new ApplicationRepresentation(); ApplicationRepresentation newApp = new ApplicationRepresentation();
if (appRep.getId() != null) if (appRep.getId() != null) newApp.setId(appRep.getId());
newApp.setId(appRep.getId());
newApp.setName(appRep.getName()); newApp.setName(appRep.getName());
if (appRep.getSecret() != null) { if (appRep.getSecret() != null) {
newApp.setSecret(appRep.getSecret()); newApp.setSecret(appRep.getSecret());
@ -136,8 +135,7 @@ public class AdminAPITest {
appCreateResponse.close(); appCreateResponse.close();
WebTarget appTarget = applicationsTarget.path(appRep.getName()); WebTarget appTarget = applicationsTarget.path(appRep.getName());
CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class); CredentialRepresentation cred = appTarget.path("client-secret").request().get(CredentialRepresentation.class);
if (appRep.getSecret() != null) if (appRep.getSecret() != null) Assert.assertEquals(appRep.getSecret(), cred.getValue());
Assert.assertEquals(appRep.getSecret(), cred.getValue());
CredentialRepresentation newCred = appTarget.path("client-secret").request().post(null, CredentialRepresentation.class); CredentialRepresentation newCred = appTarget.path("client-secret").request().post(null, CredentialRepresentation.class);
Assert.assertNotEquals(newCred.getValue(), cred.getValue()); Assert.assertNotEquals(newCred.getValue(), cred.getValue());
@ -145,6 +143,7 @@ public class AdminAPITest {
Assert.assertEquals(204, appUpdateResponse.getStatus()); Assert.assertEquals(204, appUpdateResponse.getStatus());
appUpdateResponse.close(); appUpdateResponse.close();
ApplicationRepresentation storedApp = appTarget.request().get(ApplicationRepresentation.class); ApplicationRepresentation storedApp = appTarget.request().get(ApplicationRepresentation.class);
checkAppUpdate(appRep, storedApp); checkAppUpdate(appRep, storedApp);
@ -163,22 +162,14 @@ public class AdminAPITest {
} }
protected void checkAppUpdate(ApplicationRepresentation appRep, ApplicationRepresentation storedApp) { protected void checkAppUpdate(ApplicationRepresentation appRep, ApplicationRepresentation storedApp) {
if (appRep.getName() != null) if (appRep.getName() != null) Assert.assertEquals(appRep.getName(), storedApp.getName());
Assert.assertEquals(appRep.getName(), storedApp.getName()); if (appRep.isEnabled() != null) Assert.assertEquals(appRep.isEnabled(), storedApp.isEnabled());
if (appRep.isEnabled() != null) if (appRep.isBearerOnly() != null) Assert.assertEquals(appRep.isBearerOnly(), storedApp.isBearerOnly());
Assert.assertEquals(appRep.isEnabled(), storedApp.isEnabled()); if (appRep.isPublicClient() != null) Assert.assertEquals(appRep.isPublicClient(), storedApp.isPublicClient());
if (appRep.isBearerOnly() != null) if (appRep.isFullScopeAllowed() != null) Assert.assertEquals(appRep.isFullScopeAllowed(), storedApp.isFullScopeAllowed());
Assert.assertEquals(appRep.isBearerOnly(), storedApp.isBearerOnly()); if (appRep.getAdminUrl() != null) Assert.assertEquals(appRep.getAdminUrl(), storedApp.getAdminUrl());
if (appRep.isPublicClient() != null) if (appRep.getBaseUrl() != null) Assert.assertEquals(appRep.getBaseUrl(), storedApp.getBaseUrl());
Assert.assertEquals(appRep.isPublicClient(), storedApp.isPublicClient()); if (appRep.isSurrogateAuthRequired() != null) Assert.assertEquals(appRep.isSurrogateAuthRequired(), storedApp.isSurrogateAuthRequired());
if (appRep.isFullScopeAllowed() != null)
Assert.assertEquals(appRep.isFullScopeAllowed(), storedApp.isFullScopeAllowed());
if (appRep.getAdminUrl() != null)
Assert.assertEquals(appRep.getAdminUrl(), storedApp.getAdminUrl());
if (appRep.getBaseUrl() != null)
Assert.assertEquals(appRep.getBaseUrl(), storedApp.getBaseUrl());
if (appRep.isSurrogateAuthRequired() != null)
Assert.assertEquals(appRep.isSurrogateAuthRequired(), storedApp.isSurrogateAuthRequired());
if (appRep.getNotBefore() != null) { if (appRep.getNotBefore() != null) {
Assert.assertEquals(appRep.getNotBefore(), storedApp.getNotBefore()); Assert.assertEquals(appRep.getNotBefore(), storedApp.getNotBefore());
@ -232,65 +223,40 @@ public class AdminAPITest {
if (rep.getRealm() != null) { if (rep.getRealm() != null) {
Assert.assertEquals(rep.getRealm(), storedRealm.getRealm()); Assert.assertEquals(rep.getRealm(), storedRealm.getRealm());
} }
if (rep.isEnabled() != null) if (rep.isEnabled() != null) Assert.assertEquals(rep.isEnabled(), storedRealm.isEnabled());
Assert.assertEquals(rep.isEnabled(), storedRealm.isEnabled()); if (rep.isBruteForceProtected() != null) Assert.assertEquals(rep.isBruteForceProtected(), storedRealm.isBruteForceProtected());
if (rep.isBruteForceProtected() != null) if (rep.getMaxFailureWaitSeconds() != null) Assert.assertEquals(rep.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds());
Assert.assertEquals(rep.isBruteForceProtected(), storedRealm.isBruteForceProtected()); if (rep.getMinimumQuickLoginWaitSeconds() != null) Assert.assertEquals(rep.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds());
if (rep.getMaxFailureWaitSeconds() != null) if (rep.getWaitIncrementSeconds() != null) Assert.assertEquals(rep.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds());
Assert.assertEquals(rep.getMaxFailureWaitSeconds(), storedRealm.getMaxFailureWaitSeconds()); if (rep.getQuickLoginCheckMilliSeconds() != null) Assert.assertEquals(rep.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds());
if (rep.getMinimumQuickLoginWaitSeconds() != null) if (rep.getMaxDeltaTimeSeconds() != null) Assert.assertEquals(rep.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds());
Assert.assertEquals(rep.getMinimumQuickLoginWaitSeconds(), storedRealm.getMinimumQuickLoginWaitSeconds()); if (rep.getFailureFactor() != null) Assert.assertEquals(rep.getFailureFactor(), storedRealm.getFailureFactor());
if (rep.getWaitIncrementSeconds() != null) if (rep.isPasswordCredentialGrantAllowed() != null) Assert.assertEquals(rep.isPasswordCredentialGrantAllowed(), storedRealm.isPasswordCredentialGrantAllowed());
Assert.assertEquals(rep.getWaitIncrementSeconds(), storedRealm.getWaitIncrementSeconds()); if (rep.isRegistrationAllowed() != null) Assert.assertEquals(rep.isRegistrationAllowed(), storedRealm.isRegistrationAllowed());
if (rep.getQuickLoginCheckMilliSeconds() != null) if (rep.isRegistrationEmailAsUsername() != null) Assert.assertEquals(rep.isRegistrationEmailAsUsername(), storedRealm.isRegistrationEmailAsUsername());
Assert.assertEquals(rep.getQuickLoginCheckMilliSeconds(), storedRealm.getQuickLoginCheckMilliSeconds()); if (rep.isRememberMe() != null) Assert.assertEquals(rep.isRememberMe(), storedRealm.isRememberMe());
if (rep.getMaxDeltaTimeSeconds() != null) if (rep.isVerifyEmail() != null) Assert.assertEquals(rep.isVerifyEmail(), storedRealm.isVerifyEmail());
Assert.assertEquals(rep.getMaxDeltaTimeSeconds(), storedRealm.getMaxDeltaTimeSeconds()); if (rep.isResetPasswordAllowed() != null) Assert.assertEquals(rep.isResetPasswordAllowed(), storedRealm.isResetPasswordAllowed());
if (rep.getFailureFactor() != null) if (rep.getSslRequired() != null) Assert.assertEquals(rep.getSslRequired(), storedRealm.getSslRequired());
Assert.assertEquals(rep.getFailureFactor(), storedRealm.getFailureFactor()); if (rep.getAccessCodeLifespan() != null) Assert.assertEquals(rep.getAccessCodeLifespan(), storedRealm.getAccessCodeLifespan());
if (rep.isPasswordCredentialGrantAllowed() != null)
Assert.assertEquals(rep.isPasswordCredentialGrantAllowed(), storedRealm.isPasswordCredentialGrantAllowed());
if (rep.isRegistrationAllowed() != null)
Assert.assertEquals(rep.isRegistrationAllowed(), storedRealm.isRegistrationAllowed());
if (rep.isRegistrationEmailAsUsername() != null)
Assert.assertEquals(rep.isRegistrationEmailAsUsername(), storedRealm.isRegistrationEmailAsUsername());
if (rep.isRememberMe() != null)
Assert.assertEquals(rep.isRememberMe(), storedRealm.isRememberMe());
if (rep.isVerifyEmail() != null)
Assert.assertEquals(rep.isVerifyEmail(), storedRealm.isVerifyEmail());
if (rep.isResetPasswordAllowed() != null)
Assert.assertEquals(rep.isResetPasswordAllowed(), storedRealm.isResetPasswordAllowed());
if (rep.getSslRequired() != null)
Assert.assertEquals(rep.getSslRequired(), storedRealm.getSslRequired());
if (rep.getAccessCodeLifespan() != null)
Assert.assertEquals(rep.getAccessCodeLifespan(), storedRealm.getAccessCodeLifespan());
if (rep.getAccessCodeLifespanUserAction() != null) if (rep.getAccessCodeLifespanUserAction() != null)
Assert.assertEquals(rep.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction()); Assert.assertEquals(rep.getAccessCodeLifespanUserAction(), storedRealm.getAccessCodeLifespanUserAction());
if (rep.getNotBefore() != null) if (rep.getNotBefore() != null) Assert.assertEquals(rep.getNotBefore(), storedRealm.getNotBefore());
Assert.assertEquals(rep.getNotBefore(), storedRealm.getNotBefore()); if (rep.getAccessTokenLifespan() != null) Assert.assertEquals(rep.getAccessTokenLifespan(), storedRealm.getAccessTokenLifespan());
if (rep.getAccessTokenLifespan() != null) if (rep.getSsoSessionIdleTimeout() != null) Assert.assertEquals(rep.getSsoSessionIdleTimeout(), storedRealm.getSsoSessionIdleTimeout());
Assert.assertEquals(rep.getAccessTokenLifespan(), storedRealm.getAccessTokenLifespan()); if (rep.getSsoSessionMaxLifespan() != null) Assert.assertEquals(rep.getSsoSessionMaxLifespan(), storedRealm.getSsoSessionMaxLifespan());
if (rep.getSsoSessionIdleTimeout() != null)
Assert.assertEquals(rep.getSsoSessionIdleTimeout(), storedRealm.getSsoSessionIdleTimeout());
if (rep.getSsoSessionMaxLifespan() != null)
Assert.assertEquals(rep.getSsoSessionMaxLifespan(), storedRealm.getSsoSessionMaxLifespan());
if (rep.getRequiredCredentials() != null) { if (rep.getRequiredCredentials() != null) {
Assert.assertNotNull(storedRealm.getRequiredCredentials()); Assert.assertNotNull(storedRealm.getRequiredCredentials());
for (String cred : rep.getRequiredCredentials()) { for (String cred : rep.getRequiredCredentials()) {
Assert.assertTrue(storedRealm.getRequiredCredentials().contains(cred)); Assert.assertTrue(storedRealm.getRequiredCredentials().contains(cred));
} }
} }
if (rep.getLoginTheme() != null) if (rep.getLoginTheme() != null) Assert.assertEquals(rep.getLoginTheme(), storedRealm.getLoginTheme());
Assert.assertEquals(rep.getLoginTheme(), storedRealm.getLoginTheme()); if (rep.getAccountTheme() != null) Assert.assertEquals(rep.getAccountTheme(), storedRealm.getAccountTheme());
if (rep.getAccountTheme() != null) if (rep.getAdminTheme() != null) Assert.assertEquals(rep.getAdminTheme(), storedRealm.getAdminTheme());
Assert.assertEquals(rep.getAccountTheme(), storedRealm.getAccountTheme()); if (rep.getEmailTheme() != null) Assert.assertEquals(rep.getEmailTheme(), storedRealm.getEmailTheme());
if (rep.getAdminTheme() != null)
Assert.assertEquals(rep.getAdminTheme(), storedRealm.getAdminTheme());
if (rep.getEmailTheme() != null)
Assert.assertEquals(rep.getEmailTheme(), storedRealm.getEmailTheme());
if (rep.getPasswordPolicy() != null) if (rep.getPasswordPolicy() != null) Assert.assertEquals(rep.getPasswordPolicy(), storedRealm.getPasswordPolicy());
Assert.assertEquals(rep.getPasswordPolicy(), storedRealm.getPasswordPolicy());
if (rep.getDefaultRoles() != null) { if (rep.getDefaultRoles() != null) {
Assert.assertNotNull(storedRealm.getDefaultRoles()); Assert.assertNotNull(storedRealm.getDefaultRoles());

View file

@ -1,7 +1,5 @@
package org.keycloak.testsuite.model; package org.keycloak.testsuite.model;
import java.util.HashMap;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.keycloak.enums.SslRequired; import org.keycloak.enums.SslRequired;
@ -11,6 +9,8 @@ import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RealmRepresentation;
import java.util.HashMap;
public class ModelTest extends AbstractModelTest { public class ModelTest extends AbstractModelTest {
@Test @Test
@ -28,16 +28,16 @@ public class ModelTest extends AbstractModelTest {
KeycloakModelUtils.generateRealmKeys(realm); KeycloakModelUtils.generateRealmKeys(realm);
realm.addDefaultRole("default-role"); realm.addDefaultRole("default-role");
HashMap<String, String> smtp = new HashMap<String, String>(); HashMap<String, String> smtp = new HashMap<String,String>();
smtp.put("from", "auto@keycloak"); smtp.put("from", "auto@keycloak");
smtp.put("hostname", "localhost"); smtp.put("hostname", "localhost");
realm.setSmtpConfig(smtp); realm.setSmtpConfig(smtp);
HashMap<String, String> social = new HashMap<String, String>(); HashMap<String, String> social = new HashMap<String,String>();
social.put("google.key", "1234"); social.put("google.key", "1234");
social.put("google.secret", "5678"); social.put("google.secret", "5678");
// FIXME: KEYCLOAK-883 //FIXME: KEYCLOAK-883
// realm.setSocialConfig(social); // realm.setSocialConfig(social);
RealmModel persisted = realmManager.getRealm(realm.getId()); RealmModel persisted = realmManager.getRealm(realm.getId());
assertEquals(realm, persisted); assertEquals(realm, persisted);
@ -62,8 +62,8 @@ public class ModelTest extends AbstractModelTest {
Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles()); Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles());
Assert.assertEquals(expected.getSmtpConfig(), actual.getSmtpConfig()); Assert.assertEquals(expected.getSmtpConfig(), actual.getSmtpConfig());
// FIXME: KEYCLOAK-883 //FIXME: KEYCLOAK-883
// Assert.assertEquals(expected.getSocialConfig(), actual.getSocialConfig()); // Assert.assertEquals(expected.getSocialConfig(), actual.getSocialConfig());
} }
private RealmModel importExport(RealmModel src, String copyName) { private RealmModel importExport(RealmModel src, String copyName) {