Merge pull request #1137 from stianst/master

KEYCLOAK-1187
This commit is contained in:
Stian Thorgersen 2015-04-14 09:27:24 +02:00
commit d13acaa9ef
29 changed files with 211 additions and 185 deletions

View file

@ -48,5 +48,23 @@
</update>
<dropColumn tableName="CLIENT" columnName="DTYPE"/>
<renameColumn tableName="CLIENT" newColumnName="CLIENT_ID" oldColumnName="NAME"/>
<renameColumn tableName="REALM" newColumnName="MASTER_ADMIN_CLIENT" oldColumnName="MASTER_ADMIN_APP"/>
<renameTable oldTableName="REALM_APPLICATION" newTableName="REALM_CLIENT"/>
<renameColumn tableName="REALM_CLIENT" newColumnName="CLIENT_ID" oldColumnName="APPLICATION_ID"/>
<renameTable oldTableName="APPLICATION_DEFAULT_ROLES" newTableName="CLIENT_DEFAULT_ROLES"/>
<renameColumn tableName="CLIENT_DEFAULT_ROLES" newColumnName="CLIENT_ID" oldColumnName="APPLICATION_ID"/>
<renameTable oldTableName="APP_NODE_REGISTRATIONS" newTableName="CLIENT_NODE_REGISTRATIONS"/>
<renameColumn tableName="CLIENT_NODE_REGISTRATIONS" newColumnName="CLIENT_ID" oldColumnName="APPLICATION_ID"/>
<renameColumn tableName="KEYCLOAK_ROLE" newColumnName="CLIENT" oldColumnName="APPLICATION"/>
<renameColumn tableName="KEYCLOAK_ROLE" newColumnName="CLIENT_ROLE" oldColumnName="APPLICATION_ROLE"/>
<renameColumn tableName="KEYCLOAK_ROLE" newColumnName="CLIENT_REALM_CONSTRAINT" oldColumnName="APP_REALM_CONSTRAINT"/>
<dropUniqueConstraint tableName="KEYCLOAK_ROLE" constraintName="UK_J3RWUVD56ONTGSUHOGM184WW2"/>
<addUniqueConstraint columnNames="NAME,CLIENT_REALM_CONSTRAINT" constraintName="UK_J3RWUVD56ONTGSUHOGM184WW2-2" tableName="KEYCLOAK_ROLE"/>
</changeSet>
</databaseChangeLog>

View file

@ -19,6 +19,9 @@ public class Update1_2_0_RC1 extends Update {
public void update(KeycloakSession session) {
convertApplicationsToClients();
convertOAuthClientsToClients();
db.getCollection("realms").update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("adminAppId", "clientId")), false, true);
}
private void convertApplicationsToClients() {
@ -31,6 +34,10 @@ public class Update1_2_0_RC1 extends Update {
DBCollection roles = db.getCollection("roles");
roles.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("applicationId", "clientId")), false, true);
log.debugv("Renamed roles.applicationId to roles.clientId");
db.getCollection("clients").dropIndex("realmId_1_name_1");
ensureIndex("clients", new String[]{"realmId", "clientId"}, true, false);
}
private void convertOAuthClientsToClients() {

View file

@ -64,7 +64,7 @@ public class RealmEntity extends AbstractIdentifiableEntity {
private List<String> eventsListeners = new ArrayList<String>();
private List<String> enabledEventTypes = new ArrayList<String>();
private String adminAppId;
private String masterAdminClient;
private boolean internationalizationEnabled;
private List<String> supportedLocales = new ArrayList<String>();
@ -391,12 +391,12 @@ public class RealmEntity extends AbstractIdentifiableEntity {
this.enabledEventTypes = enabledEventTypes;
}
public String getAdminAppId() {
return adminAppId;
public String getMasterAdminClient() {
return masterAdminClient;
}
public void setAdminAppId(String adminAppId) {
this.adminAppId = adminAppId;
public void setMasterAdminClient(String masterAdminClient) {
this.masterAdminClient = masterAdminClient;
}
public List<UserFederationProviderEntity> getUserFederationProviders() {

View file

@ -966,14 +966,14 @@ public class RealmAdapter implements RealmModel {
@Override
public void setMasterAdminClient(ClientModel client) {
if (client == null) {
realm.setAdminAppId(null);
realm.setMasterAdminClient(null);
this.masterAdminApp = null;
} else {
String appId = client.getId();
if (appId == null) {
throw new IllegalStateException("Master Admin app not initialized.");
}
realm.setAdminAppId(appId);
realm.setMasterAdminClient(appId);
this.masterAdminApp = client;
}
}

View file

@ -3,7 +3,7 @@ package org.keycloak.models.cache.infinispan;
import org.infinispan.Cache;
import org.jboss.logging.Logger;
import org.keycloak.models.cache.RealmCache;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedClient;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
@ -77,19 +77,19 @@ public class InfinispanRealmCache implements RealmCache {
}
@Override
public CachedApplication getApplication(String id) {
public CachedClient getApplication(String id) {
if (!enabled) return null;
return get(id, CachedApplication.class);
return get(id, CachedClient.class);
}
@Override
public void invalidateApplication(CachedApplication app) {
public void invalidateApplication(CachedClient app) {
logger.tracev("Removing application {0}", app.getId());
cache.remove(app.getId());
}
@Override
public void addCachedApplication(CachedApplication app) {
public void addCachedClient(CachedClient app) {
if (!enabled) return;
logger.tracev("Adding application {0}", app.getId());
cache.put(app.getId(), app);

View file

@ -6,7 +6,7 @@ import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedClient;
import java.util.HashMap;
import java.util.HashSet;
@ -24,9 +24,9 @@ public class ClientAdapter implements ClientModel {
protected RealmCache cache;
protected ClientModel updated;
protected CachedApplication cached;
protected CachedClient cached;
public ClientAdapter(RealmModel cachedRealm, CachedApplication cached, CacheRealmProvider cacheSession, RealmCache cache) {
public ClientAdapter(RealmModel cachedRealm, CachedClient cached, CacheRealmProvider cacheSession, RealmCache cache) {
this.cachedRealm = cachedRealm;
this.cache = cache;
this.cacheSession = cacheSession;

View file

@ -6,8 +6,8 @@ import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RoleModel;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedApplicationRole;
import org.keycloak.models.cache.entities.CachedClient;
import org.keycloak.models.cache.entities.CachedClientRole;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRealmRole;
import org.keycloak.models.cache.entities.CachedRole;
@ -235,7 +235,7 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider {
if (model == null) return null;
if (roleInvalidations.contains(id)) return model;
if (model.getContainer() instanceof ClientModel) {
cached = new CachedApplicationRole(((ClientModel) model.getContainer()).getId(), model, realm);
cached = new CachedClientRole(((ClientModel) model.getContainer()).getId(), model, realm);
} else {
cached = new CachedRealmRole(model, realm);
}
@ -254,7 +254,7 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider {
@Override
public ClientModel getClientById(String id, RealmModel realm) {
if (!cache.isEnabled()) return getDelegate().getClientById(id, realm);
CachedApplication cached = cache.getApplication(id);
CachedClient cached = cache.getApplication(id);
if (cached != null && !cached.getRealm().equals(realm.getId())) {
cached = null;
}
@ -263,8 +263,8 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider {
ClientModel model = getDelegate().getClientById(id, realm);
if (model == null) return null;
if (appInvalidations.contains(id)) return model;
cached = new CachedApplication(cache, getDelegate(), realm, model);
cache.addCachedApplication(cached);
cached = new CachedClient(cache, getDelegate(), realm, model);
cache.addCachedClient(cached);
} else if (appInvalidations.contains(id)) {
return getDelegate().getClientById(id, realm);
} else if (managedApplications.containsKey(id)) {

View file

@ -1,6 +1,6 @@
package org.keycloak.models.cache;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedClient;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
@ -14,7 +14,7 @@ public class MemoryRealmCache implements RealmCache {
protected ConcurrentHashMap<String, CachedRealm> realmCache = new ConcurrentHashMap<String, CachedRealm>();
protected ConcurrentHashMap<String, CachedRealm> realmCacheByName = new ConcurrentHashMap<String, CachedRealm>();
protected ConcurrentHashMap<String, CachedApplication> applicationCache = new ConcurrentHashMap<String, CachedApplication>();
protected ConcurrentHashMap<String, CachedClient> applicationCache = new ConcurrentHashMap<String, CachedClient>();
protected ConcurrentHashMap<String, CachedRole> roleCache = new ConcurrentHashMap<String, CachedRole>();
protected volatile boolean enabled = true;
@ -72,18 +72,18 @@ public class MemoryRealmCache implements RealmCache {
}
@Override
public CachedApplication getApplication(String id) {
public CachedClient getApplication(String id) {
if (!enabled) return null;
return applicationCache.get(id);
}
@Override
public void invalidateApplication(CachedApplication app) {
public void invalidateApplication(CachedClient app) {
applicationCache.remove(app.getId());
}
@Override
public void addCachedApplication(CachedApplication app) {
public void addCachedClient(CachedClient app) {
if (!enabled) return;
applicationCache.put(app.getId(), app);
}

View file

@ -474,7 +474,7 @@ public class RealmAdapter implements RealmModel {
public Map<String, ClientModel> getClientNameMap() {
if (updated != null) return updated.getClientNameMap();
Map<String, ClientModel> map = new HashMap<String, ClientModel>();
for (String id : cached.getApplications().values()) {
for (String id : cached.getClients().values()) {
ClientModel model = cacheSession.getClientById(id, this);
if (model == null) {
throw new IllegalStateException("Cached application not found: " + id);
@ -488,7 +488,7 @@ public class RealmAdapter implements RealmModel {
public List<ClientModel> getClients() {
if (updated != null) return updated.getClients();
List<ClientModel> apps = new LinkedList<ClientModel>();
for (String id : cached.getApplications().values()) {
for (String id : cached.getClients().values()) {
ClientModel model = cacheSession.getClientById(id, this);
if (model == null) {
throw new IllegalStateException("Cached application not found: " + id);
@ -531,7 +531,7 @@ public class RealmAdapter implements RealmModel {
@Override
public ClientModel getClientByClientId(String clientId) {
if (updated != null) return updated.getClientByClientId(clientId);
String id = cached.getApplications().get(clientId);
String id = cached.getClients().get(clientId);
if (id == null) return null;
return getClientById(id);
}
@ -752,7 +752,7 @@ public class RealmAdapter implements RealmModel {
@Override
public ClientModel getMasterAdminClient() {
return cacheSession.getRealm(Config.getAdminRealm()).getClientById(cached.getMasterAdminApp());
return cacheSession.getRealm(Config.getAdminRealm()).getClientById(cached.getMasterAdminClient());
}
@Override

View file

@ -1,6 +1,6 @@
package org.keycloak.models.cache;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedClient;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
@ -21,11 +21,11 @@ public interface RealmCache {
void invalidateCachedRealmById(String id);
CachedApplication getApplication(String id);
CachedClient getApplication(String id);
void invalidateApplication(CachedApplication app);
void invalidateApplication(CachedClient app);
void addCachedApplication(CachedApplication app);
void addCachedClient(CachedClient app);
void invalidateCachedApplicationById(String id);

View file

@ -3,7 +3,7 @@ package org.keycloak.models.cache;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.cache.entities.CachedApplicationRole;
import org.keycloak.models.cache.entities.CachedClientRole;
import org.keycloak.models.cache.entities.CachedRealmRole;
import org.keycloak.models.cache.entities.CachedRole;
import org.keycloak.models.utils.KeycloakModelUtils;
@ -106,8 +106,8 @@ public class RoleAdapter implements RoleModel {
if (cached instanceof CachedRealmRole) {
return realm;
} else {
CachedApplicationRole appRole = (CachedApplicationRole)cached;
return realm.getClientById(appRole.getAppId());
CachedClientRole appRole = (CachedClientRole)cached;
return realm.getClientById(appRole.getIdClient());
}
}

View file

@ -1,22 +0,0 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedApplicationRole extends CachedRole {
private final String appId;
public CachedApplicationRole(String appId, RoleModel model, RealmModel realm) {
super(model, realm);
this.appId = appId;
}
public String getAppId() {
return appId;
}
}

View file

@ -21,7 +21,7 @@ import java.util.TreeMap;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedApplication {
public class CachedClient {
private String id;
private String name;
private String realm;
@ -49,7 +49,7 @@ public class CachedApplication {
private int nodeReRegistrationTimeout;
private Map<String, Integer> registeredNodes;
public CachedApplication(RealmCache cache, RealmProvider delegate, RealmModel realm, ClientModel model) {
public CachedClient(RealmCache cache, RealmProvider delegate, RealmModel realm, ClientModel model) {
id = model.getId();
secret = model.getSecret();
name = model.getClientId();
@ -79,7 +79,7 @@ public class CachedApplication {
consentRequired = model.isConsentRequired();
for (RoleModel role : model.getRoles()) {
roles.put(role.getName(), role.getId());
cache.addCachedRole(new CachedApplicationRole(id, role, realm));
cache.addCachedRole(new CachedClientRole(id, role, realm));
}
nodeReRegistrationTimeout = model.getNodeReRegistrationTimeout();

View file

@ -0,0 +1,22 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedClientRole extends CachedRole {
private final String idClient;
public CachedClientRole(String idClient, RoleModel model, RealmModel realm) {
super(model, realm);
this.idClient = idClient;
}
public String getIdClient() {
return idClient;
}
}

View file

@ -66,7 +66,7 @@ public class CachedRealm {
private String accountTheme;
private String adminTheme;
private String emailTheme;
private String masterAdminApp;
private String masterAdminClient;
private List<RequiredCredentialModel> requiredCredentials = new ArrayList<RequiredCredentialModel>();
private List<UserFederationProviderModel> userFederationProviders = new ArrayList<UserFederationProviderModel>();
@ -81,7 +81,6 @@ public class CachedRealm {
private Set<String> enabledEventTypes = new HashSet<String>();
private List<String> defaultRoles = new LinkedList<String>();
private Map<String, String> realmRoles = new HashMap<String, String>();
private Map<String, String> applications = new HashMap<String, String>();
private Map<String, String> clients = new HashMap<String, String>();
private boolean internationalizationEnabled;
private Set<String> supportedLocales = new HashSet<String>();
@ -155,7 +154,7 @@ public class CachedRealm {
eventsListeners.addAll(model.getEventsListeners());
enabledEventTypes.addAll(model.getEnabledEventTypes());
defaultRoles.addAll(model.getDefaultRoles());
masterAdminApp = model.getMasterAdminClient().getId();
masterAdminClient = model.getMasterAdminClient().getId();
for (RoleModel role : model.getRoles()) {
realmRoles.put(role.getName(), role.getId());
@ -163,10 +162,10 @@ public class CachedRealm {
cache.addCachedRole(cachedRole);
}
for (ClientModel app : model.getClients()) {
applications.put(app.getClientId(), app.getId());
CachedApplication cachedApp = new CachedApplication(cache, delegate, model, app);
cache.addCachedApplication(cachedApp);
for (ClientModel client : model.getClients()) {
clients.put(client.getClientId(), client.getId());
CachedClient cachedClient = new CachedClient(cache, delegate, model, client);
cache.addCachedClient(cachedClient);
}
internationalizationEnabled = model.isInternationalizationEnabled();
@ -180,8 +179,8 @@ public class CachedRealm {
return id;
}
public String getMasterAdminApp() {
return masterAdminApp;
public String getMasterAdminClient() {
return masterAdminClient;
}
public String getName() {
@ -196,10 +195,6 @@ public class CachedRealm {
return realmRoles;
}
public Map<String, String> getApplications() {
return applications;
}
public Map<String, String> getClients() {
return clients;
}

View file

@ -545,9 +545,9 @@ public class ClientAdapter implements ClientModel {
@Override
public RoleModel getRole(String name) {
TypedQuery<RoleEntity> query = em.createNamedQuery("getAppRoleByName", RoleEntity.class);
TypedQuery<RoleEntity> query = em.createNamedQuery("getClientRoleByName", RoleEntity.class);
query.setParameter("name", name);
query.setParameter("application", entity);
query.setParameter("client", entity);
List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null;
return new RoleAdapter(realm, em, roles.get(0));
@ -563,8 +563,8 @@ public class ClientAdapter implements ClientModel {
RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id);
roleEntity.setName(name);
roleEntity.setApplication(entity);
roleEntity.setApplicationRole(true);
roleEntity.setClient(entity);
roleEntity.setClientRole(true);
roleEntity.setRealmId(realm.getId());
em.persist(roleEntity);
entity.getRoles().add(roleEntity);
@ -581,13 +581,13 @@ public class ClientAdapter implements ClientModel {
session.users().preRemove(getRealm(), roleModel);
RoleEntity role = RoleAdapter.toRoleEntity(roleModel, em);
if (!role.isApplicationRole()) return false;
if (!role.isClientRole()) return false;
entity.getRoles().remove(role);
entity.getDefaultRoles().remove(role);
em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", role).executeUpdate();
em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", role).executeUpdate();
role.setApplication(null);
role.setClient(null);
em.flush();
em.remove(role);
em.flush();

View file

@ -91,7 +91,7 @@ public class JpaRealmProvider implements RealmProvider {
RealmAdapter adapter = new RealmAdapter(session, em, realm);
session.users().preRemove(adapter);
for (ClientEntity a : new LinkedList<>(realm.getApplications())) {
for (ClientEntity a : new LinkedList<>(realm.getClients())) {
adapter.removeClient(a.getId());
}

View file

@ -619,8 +619,8 @@ public class RealmAdapter implements RealmModel {
@Override
public List<ClientModel> getClients() {
List<ClientModel> list = new ArrayList<ClientModel>();
if (realm.getApplications() == null) return list;
for (ClientEntity entity : realm.getApplications()) {
if (realm.getClients() == null) return list;
for (ClientEntity entity : realm.getClients()) {
list.add(new ClientAdapter(this, em, session, entity));
}
return list;
@ -633,15 +633,15 @@ public class RealmAdapter implements RealmModel {
@Override
public ClientModel addClient(String id, String clientId) {
ClientEntity applicationData = new ClientEntity();
applicationData.setId(id);
applicationData.setClientId(clientId);
applicationData.setEnabled(true);
applicationData.setRealm(realm);
realm.getApplications().add(applicationData);
em.persist(applicationData);
ClientEntity entity = new ClientEntity();
entity.setId(id);
entity.setClientId(clientId);
entity.setEnabled(true);
entity.setRealm(realm);
realm.getClients().add(entity);
em.persist(entity);
em.flush();
final ClientModel resource = new ClientAdapter(this, em, session, applicationData);
final ClientModel resource = new ClientAdapter(this, em, session, entity);
em.flush();
session.getKeycloakSessionFactory().publish(new ClientCreationEvent() {
@Override
@ -655,15 +655,15 @@ public class RealmAdapter implements RealmModel {
@Override
public boolean removeClient(String id) {
if (id == null) return false;
ClientModel application = getClientById(id);
if (application == null) return false;
ClientModel client = getClientById(id);
if (client == null) return false;
for (RoleModel role : application.getRoles()) {
application.removeRole(role);
for (RoleModel role : client.getRoles()) {
client.removeRole(role);
}
ClientEntity clientEntity = null;
Iterator<ClientEntity> it = realm.getApplications().iterator();
Iterator<ClientEntity> it = realm.getClients().iterator();
while (it.hasNext()) {
ClientEntity ae = it.next();
if (ae.getId().equals(id)) {
@ -672,12 +672,12 @@ public class RealmAdapter implements RealmModel {
break;
}
}
for (ClientEntity a : realm.getApplications()) {
for (ClientEntity a : realm.getClients()) {
if (a.getId().equals(id)) {
clientEntity = a;
}
}
if (application == null) {
if (client == null) {
return false;
}
em.remove(clientEntity);
@ -1066,13 +1066,13 @@ public class RealmAdapter implements RealmModel {
@Override
public ClientModel getMasterAdminClient() {
return new ClientAdapter(this, em, session, realm.getMasterAdminApp());
return new ClientAdapter(this, em, session, realm.getMasterAdminClient());
}
@Override
public void setMasterAdminClient(ClientModel client) {
ClientEntity appEntity = client !=null ? em.getReference(ClientEntity.class, client.getId()) : null;
realm.setMasterAdminApp(appEntity);
realm.setMasterAdminClient(appEntity);
em.flush();
}

View file

@ -104,8 +104,8 @@ public class RoleAdapter implements RoleModel {
@Override
public RoleContainerModel getContainer() {
if (role.isApplicationRole()) {
return realm.getClientById(role.getApplication().getId());
if (role.isClientRole()) {
return realm.getClientById(role.getClient().getId());
} else {
return realm;

View file

@ -96,17 +96,17 @@ public class ClientEntity {
@Column(name="NODE_REREG_TIMEOUT")
private int nodeReRegistrationTimeout;
@OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application")
@OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "client")
Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="APPLICATION_DEFAULT_ROLES", joinColumns = { @JoinColumn(name="APPLICATION_ID")}, inverseJoinColumns = { @JoinColumn(name="ROLE_ID")})
@JoinTable(name="CLIENT_DEFAULT_ROLES", joinColumns = { @JoinColumn(name="CLIENT_ID")}, inverseJoinColumns = { @JoinColumn(name="ROLE_ID")})
Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>();
@ElementCollection
@MapKeyColumn(name="NAME")
@Column(name="VALUE")
@CollectionTable(name="APP_NODE_REGISTRATIONS", joinColumns={ @JoinColumn(name="APPLICATION_ID") })
@CollectionTable(name="CLIENT_NODE_REGISTRATIONS", joinColumns={ @JoinColumn(name="CLIENT_ID") })
Map<String, Integer> registeredNodes = new HashMap<String, Integer>();
public RealmEntity getRealm() {

View file

@ -104,8 +104,8 @@ public class RealmEntity {
List<UserFederationProviderEntity> userFederationProviders = new ArrayList<UserFederationProviderEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="REALM_APPLICATION", joinColumns={ @JoinColumn(name="REALM_ID") }, inverseJoinColumns={ @JoinColumn(name="APPLICATION_ID") })
Collection<ClientEntity> applications = new ArrayList<ClientEntity>();
@JoinTable(name="REALM_CLIENT", joinColumns={ @JoinColumn(name="REALM_ID") }, inverseJoinColumns={ @JoinColumn(name="CLIENT_ID") })
Collection<ClientEntity> clients = new ArrayList<>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@ -136,8 +136,8 @@ public class RealmEntity {
protected Set<String> enabledEventTypes = new HashSet<String>();
@OneToOne
@JoinColumn(name="MASTER_ADMIN_APP")
protected ClientEntity masterAdminApp;
@JoinColumn(name="MASTER_ADMIN_CLIENT")
protected ClientEntity masterAdminClient;
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
protected List<IdentityProviderEntity> identityProviders = new ArrayList<IdentityProviderEntity>();
@ -318,12 +318,12 @@ public class RealmEntity {
this.requiredCredentials = requiredCredentials;
}
public Collection<ClientEntity> getApplications() {
return applications;
public Collection<ClientEntity> getClients() {
return clients;
}
public void setApplications(Collection<ClientEntity> applications) {
this.applications = applications;
public void setClients(Collection<ClientEntity> clients) {
this.clients = clients;
}
public Collection<RoleEntity> getRoles() {
@ -437,12 +437,12 @@ public class RealmEntity {
this.enabledEventTypes = enabledEventTypes;
}
public ClientEntity getMasterAdminApp() {
return masterAdminApp;
public ClientEntity getMasterAdminClient() {
return masterAdminClient;
}
public void setMasterAdminApp(ClientEntity masterAdminApp) {
this.masterAdminApp = masterAdminApp;
public void setMasterAdminClient(ClientEntity masterAdminClient) {
this.masterAdminClient = masterAdminClient;
}
public List<UserFederationProviderEntity> getUserFederationProviders() {

View file

@ -21,11 +21,11 @@ import java.util.Collection;
*/
@Entity
@Table(name="KEYCLOAK_ROLE", uniqueConstraints = {
@UniqueConstraint(columnNames = { "NAME", "APP_REALM_CONSTRAINT" })
@UniqueConstraint(columnNames = { "NAME", "CLIENT_REALM_CONSTRAINT" })
})
@NamedQueries({
@NamedQuery(name="getAppRoleByName", query="select role from RoleEntity role where role.name = :name and role.application = :application"),
@NamedQuery(name="getRealmRoleByName", query="select role from RoleEntity role where role.applicationRole = false and role.name = :name and role.realm = :realm")
@NamedQuery(name="getClientRoleByName", query="select role from RoleEntity role where role.name = :name and role.client = :client"),
@NamedQuery(name="getRealmRoleByName", query="select role from RoleEntity role where role.clientRole = false and role.name = :name and role.realm = :realm")
})
public class RoleEntity {
@ -46,16 +46,16 @@ public class RoleEntity {
@JoinColumn(name = "REALM")
private RealmEntity realm;
@Column(name="APPLICATION_ROLE")
private boolean applicationRole;
@Column(name="CLIENT_ROLE")
private boolean clientRole;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "APPLICATION")
private ClientEntity application;
@JoinColumn(name = "CLIENT")
private ClientEntity client;
// Hack to ensure that either name+application or name+realm are unique. Needed due to MS-SQL as it don't allow multiple NULL values in the column, which is part of constraint
@Column(name="APP_REALM_CONSTRAINT", length = 36)
private String appRealmConstraint;
// Hack to ensure that either name+client or name+realm are unique. Needed due to MS-SQL as it don't allow multiple NULL values in the column, which is part of constraint
@Column(name="CLIENT_REALM_CONSTRAINT", length = 36)
private String clientRealmConstraint;
@ManyToMany(fetch = FetchType.LAZY, cascade = {})
@JoinTable(name = "COMPOSITE_ROLE", joinColumns = @JoinColumn(name = "COMPOSITE"), inverseJoinColumns = @JoinColumn(name = "CHILD_ROLE"))
@ -101,12 +101,12 @@ public class RoleEntity {
this.compositeRoles = compositeRoles;
}
public boolean isApplicationRole() {
return applicationRole;
public boolean isClientRole() {
return clientRole;
}
public void setApplicationRole(boolean applicationRole) {
this.applicationRole = applicationRole;
public void setClientRole(boolean clientRole) {
this.clientRole = clientRole;
}
public RealmEntity getRealm() {
@ -115,26 +115,26 @@ public class RoleEntity {
public void setRealm(RealmEntity realm) {
this.realm = realm;
this.appRealmConstraint = realm.getId();
this.clientRealmConstraint = realm.getId();
}
public ClientEntity getApplication() {
return application;
public ClientEntity getClient() {
return client;
}
public void setApplication(ClientEntity application) {
this.application = application;
if (application != null) {
this.appRealmConstraint = application.getId();
public void setClient(ClientEntity client) {
this.client = client;
if (client != null) {
this.clientRealmConstraint = client.getId();
}
}
public String getAppRealmConstraint() {
return appRealmConstraint;
public String getClientRealmConstraint() {
return clientRealmConstraint;
}
public void setAppRealmConstraint(String appRealmConstraint) {
this.appRealmConstraint = appRealmConstraint;
public void setClientRealmConstraint(String clientRealmConstraint) {
this.clientRealmConstraint = clientRealmConstraint;
}
@Override

View file

@ -91,7 +91,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override
public SslRequired getSslRequired() {
return SslRequired.valueOf(realm.getSslRequired());
return realm.getSslRequired() != null ? SslRequired.valueOf(realm.getSslRequired()) : null;
}
@Override
@ -604,11 +604,11 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
DBObject query = new QueryBuilder()
.and("realmId").is(getId())
.get();
List<MongoClientEntity> appDatas = getMongoStore().loadEntities(MongoClientEntity.class, query, invocationContext);
List<MongoClientEntity> clientEntities = getMongoStore().loadEntities(MongoClientEntity.class, query, invocationContext);
List<ClientModel> result = new ArrayList<ClientModel>();
for (MongoClientEntity appData : appDatas) {
result.add(new ClientAdapter(session, this, appData, invocationContext));
for (MongoClientEntity clientEntity : clientEntities) {
result.add(new ClientAdapter(session, this, clientEntity, invocationContext));
}
return result;
}
@ -620,14 +620,14 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override
public ClientModel addClient(String id, String clientId) {
MongoClientEntity appData = new MongoClientEntity();
appData.setId(id);
appData.setClientId(clientId);
appData.setRealmId(getId());
appData.setEnabled(true);
getMongoStore().insertEntity(appData, invocationContext);
MongoClientEntity clientEntity = new MongoClientEntity();
clientEntity.setId(id);
clientEntity.setClientId(clientId);
clientEntity.setRealmId(getId());
clientEntity.setEnabled(true);
getMongoStore().insertEntity(clientEntity, invocationContext);
final ClientModel model = new ClientAdapter(session, this, appData, invocationContext);
final ClientModel model = new ClientAdapter(session, this, clientEntity, invocationContext);
session.getKeycloakSessionFactory().publish(new ClientCreationEvent() {
@Override
public ClientModel getCreatedClient() {
@ -979,14 +979,14 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
@Override
public ClientModel getMasterAdminClient() {
MongoClientEntity appData = getMongoStore().loadEntity(MongoClientEntity.class, realm.getAdminAppId(), invocationContext);
MongoClientEntity appData = getMongoStore().loadEntity(MongoClientEntity.class, realm.getMasterAdminClient(), invocationContext);
return appData != null ? new ClientAdapter(session, this, appData, invocationContext) : null;
}
@Override
public void setMasterAdminClient(ClientModel client) {
String adminAppId = client != null ? client.getId() : null;
realm.setAdminAppId(adminAppId);
realm.setMasterAdminClient(adminAppId);
updateRealm();
}

View file

@ -51,6 +51,7 @@ import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.keycloak.testutils.KeycloakServer;
import org.keycloak.util.BasicAuthHelper;
import org.keycloak.util.Time;
import org.openqa.selenium.WebDriver;
import javax.ws.rs.client.Client;
@ -303,7 +304,7 @@ public class AdapterTestStrategy extends ExternalResource {
session.getTransaction().commit();
session.close();
Thread.sleep(2000);
Time.setOffset(2);
// test SSO
@ -315,6 +316,8 @@ public class AdapterTestStrategy extends ExternalResource {
realm.setSsoSessionIdleTimeout(originalIdle);
session.getTransaction().commit();
session.close();
Time.setOffset(0);
}
public void testLoginSSOIdleRemoveExpiredUserSessions() throws Exception {
@ -336,7 +339,7 @@ public class AdapterTestStrategy extends ExternalResource {
session.getTransaction().commit();
session.close();
Thread.sleep(2000);
Time.setOffset(2);
session = keycloakRule.startSession();
realm = session.realms().getRealmByName("demo");
@ -356,6 +359,8 @@ public class AdapterTestStrategy extends ExternalResource {
realm.setSsoSessionIdleTimeout(originalIdle);
session.getTransaction().commit();
session.close();
Time.setOffset(0);
}
public void testLoginSSOMax() throws Exception {
@ -377,7 +382,7 @@ public class AdapterTestStrategy extends ExternalResource {
session.getTransaction().commit();
session.close();
Thread.sleep(2000);
Time.setOffset(2);
// test SSO
@ -389,6 +394,8 @@ public class AdapterTestStrategy extends ExternalResource {
realm.setSsoSessionMaxLifespan(original);
session.getTransaction().commit();
session.close();
Time.setOffset(0);
}
/**
@ -541,7 +548,7 @@ public class AdapterTestStrategy extends ExternalResource {
driver.navigate().to(logoutUri);
// Wait until accessToken is expired
Thread.sleep(2000);
Time.setOffset(2);
// Assert that http session was invalidated
driver.navigate().to(APP_SERVER_BASE_URL + "/session-portal");
@ -563,6 +570,8 @@ public class AdapterTestStrategy extends ExternalResource {
}
}, "demo");
Time.setOffset(0);
}
/**

View file

@ -37,6 +37,7 @@ import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.MailUtil;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.Retry;
import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.AppPage.RequestType;
import org.keycloak.testsuite.pages.ErrorPage;
@ -253,8 +254,6 @@ public class ResetPasswordTest {
assertEquals("You should receive an email shortly with further instructions.", resetPasswordPage.getSuccessMessage());
Thread.sleep(1000);
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).user((String) null).session((String) null).detail(Details.USERNAME, "invalid").removeDetail(Details.EMAIL).removeDetail(Details.CODE_ID).error("user_not_found").assertEvent();
@ -318,8 +317,6 @@ public class ResetPasswordTest {
assertEquals("You should receive an email shortly with further instructions.", resetPasswordPage.getSuccessMessage());
Thread.sleep(1000);
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("user_disabled").assertEvent();
@ -358,8 +355,6 @@ public class ResetPasswordTest {
assertEquals("You should receive an email shortly with further instructions.", resetPasswordPage.getSuccessMessage());
Thread.sleep(1000);
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD_ERROR).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("invalid_email").assertEvent();
@ -396,8 +391,6 @@ public class ResetPasswordTest {
assertEquals("Failed to send email, please try again later.", errorPage.getError());
Thread.sleep(1000);
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD_ERROR).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error(Errors.EMAIL_SEND_FAILED).assertEvent();

View file

@ -18,6 +18,7 @@ import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationManager.AuthenticationStatus;
import org.keycloak.services.managers.BruteForceProtector;
import org.keycloak.util.Time;
import javax.ws.rs.core.MultivaluedMap;
import java.util.UUID;
@ -238,10 +239,12 @@ public class AuthenticationManagerTest extends AbstractModelTest {
String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), "invalid")).rsa256(realm.getPrivateKey());
formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);
Thread.sleep(2000);
Time.setOffset(2);
AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
Time.setOffset(0);
} finally {
realm.setAccessCodeLifespanUserAction(lifespan);
}

View file

@ -55,6 +55,7 @@ import org.keycloak.testsuite.rule.KeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.keycloak.util.BasicAuthHelper;
import org.keycloak.util.Time;
import org.openqa.selenium.WebDriver;
import javax.ws.rs.client.Client;
@ -211,10 +212,7 @@ public class AccessTokenTest {
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
Time.setOffset(2);
OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
Assert.assertEquals(400, response.getStatusCode());
@ -231,6 +229,8 @@ public class AccessTokenTest {
appRealm.setAccessCodeLifespan(60);
}
});
Time.setOffset(0);
}
@Test

View file

@ -143,7 +143,7 @@ public class RefreshTokenTest {
Assert.assertEquals(sessionId, refreshToken.getSessionState());
Thread.sleep(2000);
Time.setOffset(2);
AccessTokenResponse response = oauth.doRefreshTokenRequest(refreshTokenString, "password");
AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
@ -157,8 +157,8 @@ public class RefreshTokenTest {
Assert.assertThat(response.getExpiresIn(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
Assert.assertThat(refreshedToken.getExpiration() - Time.currentTime(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
Assert.assertThat(refreshedToken.getExpiration() - token.getExpiration(), allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(5)));
Assert.assertThat(refreshedRefreshToken.getExpiration() - refreshToken.getExpiration(), allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(5)));
Assert.assertThat(refreshedToken.getExpiration() - token.getExpiration(), allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));
Assert.assertThat(refreshedRefreshToken.getExpiration() - refreshToken.getExpiration(), allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));
Assert.assertNotEquals(token.getId(), refreshedToken.getId());
Assert.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId());
@ -177,6 +177,8 @@ public class RefreshTokenTest {
Event refreshEvent = events.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).assertEvent();
Assert.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID));
Assert.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID));
Time.setOffset(0);
}
PrivateKey privateKey;
@ -277,7 +279,7 @@ public class RefreshTokenTest {
session.getTransaction().commit();
session.close();
Thread.sleep(2000);
Time.setOffset(2);
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");
@ -302,7 +304,7 @@ public class RefreshTokenTest {
session.getTransaction().commit();
session.close();
Thread.sleep(2000);
Time.setOffset(4);
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");
session = keycloakRule.startSession();
@ -323,7 +325,7 @@ public class RefreshTokenTest {
session.close();
events.clear();
Thread.sleep(2000);
Time.setOffset(6);
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");
// test idle timeout
@ -341,6 +343,8 @@ public class RefreshTokenTest {
session.close();
events.clear();
Time.setOffset(0);
}
@Test
@ -365,7 +369,7 @@ public class RefreshTokenTest {
session.getTransaction().commit();
session.close();
Thread.sleep(1000);
Time.setOffset(1);
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");
@ -383,6 +387,8 @@ public class RefreshTokenTest {
events.expectRefresh(refreshId, sessionId).error(Errors.INVALID_TOKEN);
events.clear();
Time.setOffset(0);
}
@Test

View file

@ -126,11 +126,6 @@ public class SamlBindingTest {
@WebResource
protected LoginPage loginPage;
//@Test
public void runit() throws Exception {
Thread.sleep(10000000);
}
protected void checkLoggedOut(String mainUrl) {
String pageSource = driver.getPageSource();
System.out.println("*** logout pagesouce ***");