model refactor for caching

This commit is contained in:
Bill Burke 2014-06-10 18:50:08 -04:00
parent 2f3c8bf079
commit 0dd06e3343
65 changed files with 1508 additions and 741 deletions

View file

@ -247,7 +247,7 @@ public class ModelExporter {
userEntity.setAttributes(userModel.getAttributes()); userEntity.setAttributes(userModel.getAttributes());
// roleIds // roleIds
Set<RoleModel> roles = realm.getRoleMappings(userModel); Set<RoleModel> roles = userModel.getRoleMappings();
List<String> roleIds = new ArrayList<String>(); List<String> roleIds = new ArrayList<String>();
for (RoleModel role : roles) { for (RoleModel role : roles) {
roleIds.add(role.getId()); roleIds.add(role.getId());
@ -298,7 +298,7 @@ public class ModelExporter {
} }
private List<String> getScopeIds(ClientModel clientModel) { private List<String> getScopeIds(ClientModel clientModel) {
Set<RoleModel> allScopes = clientModel.getRealm().getScopeMappings(clientModel); Set<RoleModel> allScopes = clientModel.getScopeMappings();
List<String> scopeIds = new ArrayList<String>(); List<String> scopeIds = new ArrayList<String>();
for (RoleModel role : allScopes) { for (RoleModel role : allScopes) {
scopeIds.add(role.getId()); scopeIds.add(role.getId());

View file

@ -207,7 +207,7 @@ public class ModelImporter {
private void addScopes(RealmModel realm, ClientModel client, ClientEntity clientEntity) { private void addScopes(RealmModel realm, ClientModel client, ClientEntity clientEntity) {
for (String scopeId : clientEntity.getScopeIds()) { for (String scopeId : clientEntity.getScopeIds()) {
RoleModel scope = realm.getRoleById(scopeId); RoleModel scope = realm.getRoleById(scopeId);
realm.addScopeMapping(client, scope); client.addScopeMapping(scope);
} }
} }
@ -246,8 +246,8 @@ public class ModelImporter {
UserModel user = realm.addUser(userEntity.getId(), userEntity.getLoginName()); UserModel user = realm.addUser(userEntity.getId(), userEntity.getLoginName());
// We need to remove defaultRoles here as realm.addUser is automatically adding them. We may add them later during roles mapping processing // We need to remove defaultRoles here as realm.addUser is automatically adding them. We may add them later during roles mapping processing
for (RoleModel role : realm.getRoleMappings(user)) { for (RoleModel role : user.getRoleMappings()) {
realm.deleteRoleMapping(user, role); user.deleteRoleMapping(role);
} }
this.propertiesManager.setBasicPropertiesToModel(user, userEntity); this.propertiesManager.setBasicPropertiesToModel(user, userEntity);
@ -291,7 +291,7 @@ public class ModelImporter {
if (userEntity.getRoleIds() != null) { if (userEntity.getRoleIds() != null) {
for (String roleId : userEntity.getRoleIds()) { for (String roleId : userEntity.getRoleIds()) {
RoleModel role = realm.getRoleById(roleId); RoleModel role = realm.getRoleById(roleId);
realm.grantRole(user, role); user.grantRole(role);
} }
} }

View file

@ -32,8 +32,6 @@ public interface ApplicationModel extends RoleContainerModel, ClientModel {
void updateDefaultRoles(String[] defaultRoles); void updateDefaultRoles(String[] defaultRoles);
Set<RoleModel> getApplicationRoleMappings(UserModel user);
Set<RoleModel> getApplicationScopeMappings(ClientModel client); Set<RoleModel> getApplicationScopeMappings(ClientModel client);
boolean isBearerOnly(); boolean isBearerOnly();

View file

@ -57,6 +57,13 @@ public interface ClientModel {
boolean isDirectGrantsOnly(); boolean isDirectGrantsOnly();
void setDirectGrantsOnly(boolean flag); void setDirectGrantsOnly(boolean flag);
Set<RoleModel> getScopeMappings();
void addScopeMapping(RoleModel role);
void deleteScopeMapping(RoleModel role);
Set<RoleModel> getRealmScopeMappings();
boolean hasScope(RoleModel role);
RealmModel getRealm(); RealmModel getRealm();
/** /**

View file

@ -3,6 +3,8 @@ package org.keycloak.models;
import org.keycloak.provider.Provider; import org.keycloak.provider.Provider;
import java.util.List; 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>
@ -15,9 +17,24 @@ public interface KeycloakSession extends Provider {
RealmModel createRealm(String id, String name); RealmModel createRealm(String id, String name);
RealmModel getRealm(String id); RealmModel getRealm(String id);
RealmModel getRealmByName(String name); RealmModel getRealmByName(String name);
UserModel getUserById(String id, String realmId);
UserModel getUserByUsername(String username, String realmId); UserModel getUserById(String id, RealmModel realm);
UserModel getUserByEmail(String email, String realmId); UserModel getUserByUsername(String username, RealmModel realm);
UserModel getUserByEmail(String email, RealmModel realm);
UserModel getUserBySocialLink(SocialLinkModel socialLink, RealmModel realm);
List<UserModel> getUsers(RealmModel realm);
List<UserModel> searchForUser(String search, RealmModel realm);
List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm);
Set<RoleModel> getRealmRoleMappings(UserModel user, RealmModel realm);
Set<SocialLinkModel> getSocialLinks(UserModel user, RealmModel realm);
SocialLinkModel getSocialLink(UserModel user, String socialProvider, RealmModel realm);
AuthenticationLinkModel getAuthenticationLink(UserModel user, RealmModel realm);
RoleModel getRoleById(String id, RealmModel realm);
ApplicationModel getApplicationById(String id, RealmModel realm);
OAuthClientModel getOAuthClientById(String id, RealmModel realm);
List<RealmModel> getRealms(); List<RealmModel> getRealms();
boolean removeRealm(String id); boolean removeRealm(String id);

View file

@ -10,7 +10,7 @@ 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 $
*/ */
public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMapperModel { public interface RealmModel extends RoleContainerModel {
String getId(); String getId();
@ -205,10 +205,6 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
void setAuthenticationProviders(List<AuthenticationProviderModel> authenticationProviders); void setAuthenticationProviders(List<AuthenticationProviderModel> authenticationProviders);
Set<RoleModel> getRealmRoleMappings(UserModel user);
Set<RoleModel> getRealmScopeMappings(ClientModel client);
String getLoginTheme(); String getLoginTheme();
void setLoginTheme(String name); void setLoginTheme(String name);
@ -225,7 +221,6 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
void setEmailTheme(String name); void setEmailTheme(String name);
boolean hasScope(ClientModel client, RoleModel role);
/** /**
* Time in seconds since epoc * Time in seconds since epoc

View file

@ -1,15 +0,0 @@
package org.keycloak.models;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface RoleMapperModel {
boolean hasRole(UserModel user, RoleModel role);
void grantRole(UserModel user, RoleModel role);
Set<RoleModel> getRoleMappings(UserModel user);
void deleteRoleMapping(UserModel user, RoleModel role);
}

View file

@ -8,7 +8,5 @@ import java.util.Set;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
public interface ScopeMapperModel { public interface ScopeMapperModel {
Set<RoleModel> getScopeMappings(ClientModel client);
void addScopeMapping(ClientModel client, RoleModel role);
void deleteScopeMapping(ClientModel client, RoleModel role);
} }

View file

@ -67,6 +67,14 @@ public interface UserModel {
void updateCredentialDirectly(UserCredentialValueModel cred); void updateCredentialDirectly(UserCredentialValueModel cred);
Set<RoleModel> getRealmRoleMappings();
Set<RoleModel> getApplicationRoleMappings(ApplicationModel app);
boolean hasRole(RoleModel role);
void grantRole(RoleModel role);
Set<RoleModel> getRoleMappings();
void deleteRoleMapping(RoleModel role);

View file

@ -1,14 +1,21 @@
package org.keycloak.models.cache; package org.keycloak.models.cache;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction; import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SocialLinkModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.cache.entities.CachedRealm; import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
import org.keycloak.provider.ProviderSession; import org.keycloak.provider.ProviderSession;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
@ -116,7 +123,7 @@ public class CacheKeycloakSession implements KeycloakSession {
if (cached == null) { if (cached == null) {
RealmModel model = getDelegate().getRealm(id); RealmModel model = getDelegate().getRealm(id);
if (model == null) return null; if (model == null) return null;
cached = new CachedRealm(model); cached = new CachedRealm(cache, this, model);
} }
return new RealmAdapter(cached, this); return new RealmAdapter(cached, this);
} }
@ -127,23 +134,23 @@ public class CacheKeycloakSession implements KeycloakSession {
if (cached == null) { if (cached == null) {
RealmModel model = getDelegate().getRealmByName(name); RealmModel model = getDelegate().getRealmByName(name);
if (model == null) return null; if (model == null) return null;
cached = new CachedRealm(model); cached = new CachedRealm(cache, this, model);
} }
return new RealmAdapter(cached, this); return new RealmAdapter(cached, this);
} }
@Override @Override
public UserModel getUserById(String id, String realmId) { public UserModel getUserById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public UserModel getUserByUsername(String username, String realmId) { public UserModel getUserByUsername(String username, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public UserModel getUserByEmail(String email, String realmId) { public UserModel getUserByEmail(String email, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@ -173,4 +180,59 @@ public class CacheKeycloakSession implements KeycloakSession {
public void close() { public void close() {
if (sessionDelegate != null) sessionDelegate.close(); if (sessionDelegate != null) sessionDelegate.close();
} }
@Override
public UserModel getUserBySocialLink(SocialLinkModel socialLink, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> getUsers(RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<RoleModel> getRealmRoleMappings(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<SocialLinkModel> getSocialLinks(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public SocialLinkModel getSocialLink(UserModel user, String socialProvider, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public AuthenticationLinkModel getAuthenticationLink(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public RoleModel getRoleById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ApplicationModel getApplicationById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public OAuthClientModel getOAuthClientById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
} }

View file

@ -1,12 +1,17 @@
package org.keycloak.models.cache; package org.keycloak.models.cache;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedOAuthClient;
import org.keycloak.models.cache.entities.CachedRealm; import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
/** /**
* @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 $
*/ */
public interface KeycloakCache { public interface KeycloakCache {
void clear();
CachedRealm getCachedRealm(String id); CachedRealm getCachedRealm(String id);
void invalidateCachedRealm(CachedRealm realm); void invalidateCachedRealm(CachedRealm realm);
@ -15,7 +20,31 @@ public interface KeycloakCache {
CachedRealm getCachedRealmByName(String name); CachedRealm getCachedRealmByName(String name);
void clear();
void invalidateCachedRealmById(String id); void invalidateCachedRealmById(String id);
CachedApplication getApplication(String id);
void invalidateApplication(CachedApplication app);
void addCachedApplication(CachedApplication app);
void invalidateCachedApplicationById(String id);
CachedOAuthClient getOAuthClient(String id);
void invalidateOAuthClient(CachedOAuthClient client);
void addCachedOAuthClient(CachedOAuthClient client);
void invalidateCachedOAuthClientById(String id);
CachedRole getRole(String id);
void invalidateRole(CachedRole role);
void addCachedRole(CachedRole role);
void invalidateCachedRoleById(String id);
} }

View file

@ -15,12 +15,18 @@ import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UsernameLoginFailureModel; import org.keycloak.models.UsernameLoginFailureModel;
import org.keycloak.models.cache.entities.CachedApplicationRole;
import org.keycloak.models.cache.entities.CachedRealm; import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRealmRole;
import org.keycloak.models.cache.entities.CachedRole;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import org.keycloak.models.utils.TimeBasedOTP;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -34,6 +40,7 @@ public class RealmAdapter implements RealmModel {
protected CachedRealm cached; protected CachedRealm cached;
protected CacheKeycloakSession cacheSession; protected CacheKeycloakSession cacheSession;
protected RealmModel updated; protected RealmModel updated;
protected KeycloakCache cache;
protected volatile transient PublicKey publicKey; protected volatile transient PublicKey publicKey;
protected volatile transient PrivateKey privateKey; protected volatile transient PrivateKey privateKey;
@ -62,7 +69,7 @@ public class RealmAdapter implements RealmModel {
protected void getDelegateForUpdate() { protected void getDelegateForUpdate() {
if (updated == null) { if (updated == null) {
updated = cacheSession.getRealm(getId()); updated = cacheSession.getDelegate().getRealm(getId());
if (updated == null) throw new IllegalStateException("Not found in database"); if (updated == null) throw new IllegalStateException("Not found in database");
} }
} }
@ -376,272 +383,352 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public boolean validatePassword(UserModel user, String password) { public boolean validatePassword(UserModel user, String password) {
return false; //To change body of implemented methods use File | Settings | File Templates. for (UserCredentialValueModel cred : user.getCredentialsDirectly()) {
if (cred.getType().equals(UserCredentialModel.PASSWORD)) {
return new Pbkdf2PasswordEncoder(cred.getSalt()).verify(password, cred.getValue());
}
}
return false;
} }
@Override @Override
public boolean validateTOTP(UserModel user, String password, String token) { public boolean validateTOTP(UserModel user, String password, String token) {
return false; //To change body of implemented methods use File | Settings | File Templates. if (!validatePassword(user, password)) return false;
for (UserCredentialValueModel cred : user.getCredentialsDirectly()) {
if (cred.getType().equals(UserCredentialModel.TOTP)) {
return new TimeBasedOTP().validate(token, cred.getValue().getBytes());
}
}
return false;
} }
@Override @Override
public UserModel getUser(String name) { public UserModel getUser(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. return cacheSession.getUserByUsername(name, this);
} }
@Override @Override
public UserModel getUserByEmail(String email) { public UserModel getUserByEmail(String email) {
return null; //To change body of implemented methods use File | Settings | File Templates. return cacheSession.getUserByEmail(email, this);
} }
@Override @Override
public UserModel getUserById(String name) { public UserModel getUserById(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates. return cacheSession.getUserById(id, this);
} }
@Override @Override
public UserModel addUser(String id, String username) { public UserModel addUser(String id, String username) {
return null; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.addUser(id, username);
} }
@Override @Override
public UserModel addUser(String username) { public UserModel addUser(String username) {
return null; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.addUser(username);
} }
@Override @Override
public boolean removeUser(String name) { public boolean removeUser(String name) {
return false; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.removeUser(name);
} }
@Override @Override
public RoleModel getRoleById(String id) { public RoleModel getRoleById(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getRoleById(id);
if (!cached.getRolesById().contains(id)) return null;
CachedRole cachedRole = cache.getRole(id);
if (cachedRole == null) {
RoleModel roleModel = cacheSession.getDelegate().getRoleById(id, this);
if (roleModel == null) return null;
if (roleModel.getContainer() instanceof ApplicationModel) {
cachedRole = new CachedApplicationRole(((ApplicationModel) roleModel.getContainer()).getId(), roleModel);
cache.addCachedRole(cachedRole);
} else {
cachedRole = new CachedRealmRole(roleModel);
}
}
return new RoleAdapter(cachedRole, cache, cacheSession, this);
} }
@Override @Override
public List<String> getDefaultRoles() { public List<String> getDefaultRoles() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getDefaultRoles();
return cached.getDefaultRoles();
} }
@Override @Override
public void addDefaultRole(String name) { public void addDefaultRole(String name) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.addDefaultRole(name);
} }
@Override @Override
public void updateDefaultRoles(String[] defaultRoles) { public void updateDefaultRoles(String[] defaultRoles) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.updateDefaultRoles(defaultRoles);
} }
@Override @Override
public ClientModel findClient(String clientId) { public ClientModel findClient(String clientId) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.findClient(clientId);
String appId = cached.getApplications().get(clientId);
if (appId != null) {
return cacheSession.getApplicationById(appId, this);
}
String oauth = cached.getClients().get(clientId);
if (oauth != null) {
return cacheSession.getOAuthClientById(oauth, this);
}
return null;
} }
@Override @Override
public Map<String, ApplicationModel> getApplicationNameMap() { public Map<String, ApplicationModel> getApplicationNameMap() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getApplicationNameMap();
Map<String, ApplicationModel> map = new HashMap<String, ApplicationModel>();
for (String id : cached.getApplications().values()) {
ApplicationModel model = cacheSession.getApplicationById(id, this);
if (model == null) {
throw new IllegalStateException("Cached application not found: " + id);
}
map.put(model.getName(), model);
}
return map;
} }
@Override @Override
public List<ApplicationModel> getApplications() { public List<ApplicationModel> getApplications() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getApplications();
List<ApplicationModel> apps = new LinkedList<ApplicationModel>();
for (String id : cached.getApplications().values()) {
ApplicationModel model = cacheSession.getApplicationById(id, this);
if (model == null) {
throw new IllegalStateException("Cached application not found: " + id);
}
apps.add(model);
}
return apps;
} }
@Override @Override
public ApplicationModel addApplication(String name) { public ApplicationModel addApplication(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.addApplication(name);
} }
@Override @Override
public ApplicationModel addApplication(String id, String name) { public ApplicationModel addApplication(String id, String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.addApplication(id, name);
} }
@Override @Override
public boolean removeApplication(String id) { public boolean removeApplication(String id) {
return false; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.removeApplication(id);
} }
@Override @Override
public ApplicationModel getApplicationById(String id) { public ApplicationModel getApplicationById(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getApplicationById(id);
return cacheSession.getApplicationById(id, this);
} }
@Override @Override
public ApplicationModel getApplicationByName(String name) { public ApplicationModel getApplicationByName(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getApplicationByName(name);
String id = cached.getApplications().get(name);
if (id == null) return null;
return getApplicationById(id);
} }
@Override @Override
public void updateRequiredCredentials(Set<String> creds) { public void updateRequiredCredentials(Set<String> creds) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.updateRequiredCredentials(creds);
} }
@Override @Override
public UserModel getUserBySocialLink(SocialLinkModel socialLink) { public UserModel getUserBySocialLink(SocialLinkModel socialLink) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getUserBySocialLink(socialLink);
return cacheSession.getUserBySocialLink(socialLink, this);
} }
@Override @Override
public Set<SocialLinkModel> getSocialLinks(UserModel user) { public Set<SocialLinkModel> getSocialLinks(UserModel user) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getSocialLinks(user);
return cacheSession.getSocialLinks(user, this);
} }
@Override @Override
public SocialLinkModel getSocialLink(UserModel user, String socialProvider) { public SocialLinkModel getSocialLink(UserModel user, String socialProvider) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getSocialLink(user, socialProvider);
return cacheSession.getSocialLink(user, socialProvider, this);
} }
@Override @Override
public void addSocialLink(UserModel user, SocialLinkModel socialLink) { public void addSocialLink(UserModel user, SocialLinkModel socialLink) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.addSocialLink(user, socialLink);
} }
@Override @Override
public boolean removeSocialLink(UserModel user, String socialProvider) { public boolean removeSocialLink(UserModel user, String socialProvider) {
return false; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.removeSocialLink(user, socialProvider);
} }
@Override @Override
public AuthenticationLinkModel getAuthenticationLink(UserModel user) { public AuthenticationLinkModel getAuthenticationLink(UserModel user) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getAuthenticationLink(user);
return cacheSession.getAuthenticationLink(user, this);
} }
@Override @Override
public void setAuthenticationLink(UserModel user, AuthenticationLinkModel authenticationLink) { public void setAuthenticationLink(UserModel user, AuthenticationLinkModel authenticationLink) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.setAuthenticationLink(user, authenticationLink);
} }
@Override @Override
public boolean isSocial() { public boolean isSocial() {
return false; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.isSocial();
return cached.isSocial();
} }
@Override @Override
public void setSocial(boolean social) { public void setSocial(boolean social) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.setSocial(social);
} }
@Override @Override
public boolean isUpdateProfileOnInitialSocialLogin() { public boolean isUpdateProfileOnInitialSocialLogin() {
return false; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.isUpdateProfileOnInitialSocialLogin();
return cached.isUpdateProfileOnInitialSocialLogin();
} }
@Override @Override
public void setUpdateProfileOnInitialSocialLogin(boolean updateProfileOnInitialSocialLogin) { public void setUpdateProfileOnInitialSocialLogin(boolean updateProfileOnInitialSocialLogin) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
} updated.setUpdateProfileOnInitialSocialLogin(updateProfileOnInitialSocialLogin);
@Override
public UsernameLoginFailureModel getUserLoginFailure(String username) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public UsernameLoginFailureModel addUserLoginFailure(String username) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UsernameLoginFailureModel> getAllUserLoginFailures() {
return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public List<UserModel> getUsers() { public List<UserModel> getUsers() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getUsers();
return cacheSession.getUsers(this);
} }
@Override @Override
public List<UserModel> searchForUser(String search) { public List<UserModel> searchForUser(String search) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.searchForUser(search);
return cacheSession.searchForUser(search, this);
} }
@Override @Override
public List<UserModel> searchForUserByAttributes(Map<String, String> attributes) { public List<UserModel> searchForUserByAttributes(Map<String, String> attributes) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.searchForUserByAttributes(attributes);
return cacheSession.searchForUserByAttributes(attributes, this);
} }
@Override @Override
public OAuthClientModel addOAuthClient(String name) { public OAuthClientModel addOAuthClient(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.addOAuthClient(name);
} }
@Override @Override
public OAuthClientModel addOAuthClient(String id, String name) { public OAuthClientModel addOAuthClient(String id, String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.addOAuthClient(id, name);
} }
@Override @Override
public OAuthClientModel getOAuthClient(String name) { public OAuthClientModel getOAuthClient(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getOAuthClient(name);
String id = cached.getClients().get(name);
if (id == null) return null;
return getOAuthClientById(id);
} }
@Override @Override
public OAuthClientModel getOAuthClientById(String id) { public OAuthClientModel getOAuthClientById(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getOAuthClientById(id);
return cacheSession.getOAuthClientById(id, this);
} }
@Override @Override
public boolean removeOAuthClient(String id) { public boolean removeOAuthClient(String id) {
return false; //To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
return updated.removeOAuthClient(id);
} }
@Override @Override
public List<OAuthClientModel> getOAuthClients() { public List<OAuthClientModel> getOAuthClients() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getOAuthClients();
List<OAuthClientModel> clients = new LinkedList<OAuthClientModel>();
for (String id : cached.getClients().values()) {
OAuthClientModel model = cacheSession.getOAuthClientById(id, this);
if (model == null) {
throw new IllegalStateException("Cached oauth client not found: " + id);
}
clients.add(model);
}
return clients;
} }
@Override @Override
public Map<String, String> getSmtpConfig() { public Map<String, String> getSmtpConfig() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getSmtpConfig();
return cached.getSmtpConfig();
} }
@Override @Override
public void setSmtpConfig(Map<String, String> smtpConfig) { public void setSmtpConfig(Map<String, String> smtpConfig) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.setSmtpConfig(smtpConfig);
} }
@Override @Override
public Map<String, String> getSocialConfig() { public Map<String, String> getSocialConfig() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getSocialConfig();
return cached.getSocialConfig();
} }
@Override @Override
public void setSocialConfig(Map<String, String> socialConfig) { public void setSocialConfig(Map<String, String> socialConfig) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.setSocialConfig(socialConfig);
} }
@Override @Override
public Map<String, String> getLdapServerConfig() { public Map<String, String> getLdapServerConfig() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getLdapServerConfig();
return cached.getLdapServerConfig();
} }
@Override @Override
public void setLdapServerConfig(Map<String, String> ldapServerConfig) { public void setLdapServerConfig(Map<String, String> ldapServerConfig) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
updated.setLdapServerConfig(ldapServerConfig);
} }
@Override @Override
public List<AuthenticationProviderModel> getAuthenticationProviders() { public List<AuthenticationProviderModel> getAuthenticationProviders() {
return null; //To change body of implemented methods use File | Settings | File Templates. if (updated != null) return updated.getAuthenticationProviders();
return cached.getAuthenticationProviders();
} }
@Override @Override
public void setAuthenticationProviders(List<AuthenticationProviderModel> authenticationProviders) { public void setAuthenticationProviders(List<AuthenticationProviderModel> authenticationProviders) {
//To change body of implemented methods use File | Settings | File Templates. getDelegateForUpdate();
} updated.setAuthenticationProviders(authenticationProviders);
@Override
public Set<RoleModel> getRealmRoleMappings(UserModel user) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<RoleModel> getRealmScopeMappings(ClientModel client) {
return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
@ -684,11 +771,6 @@ public class RealmAdapter implements RealmModel {
//To change body of implemented methods use File | Settings | File Templates. //To change body of implemented methods use File | Settings | File Templates.
} }
@Override
public boolean hasScope(ClientModel client, RoleModel role) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override @Override
public int getNotBefore() { public int getNotBefore() {
return 0; //To change body of implemented methods use File | Settings | File Templates. return 0; //To change body of implemented methods use File | Settings | File Templates.
@ -744,6 +826,21 @@ public class RealmAdapter implements RealmModel {
//To change body of implemented methods use File | Settings | File Templates. //To change body of implemented methods use File | Settings | File Templates.
} }
@Override
public UsernameLoginFailureModel getUserLoginFailure(String username) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public UsernameLoginFailureModel addUserLoginFailure(String username) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UsernameLoginFailureModel> getAllUserLoginFailures() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override @Override
public UserSessionModel createUserSession(UserModel user, String ipAddress) { public UserSessionModel createUserSession(UserModel user, String ipAddress) {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
@ -809,38 +906,4 @@ public class RealmAdapter implements RealmModel {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override
public boolean hasRole(UserModel user, RoleModel role) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void grantRole(UserModel user, RoleModel role) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<RoleModel> getRoleMappings(UserModel user) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void deleteRoleMapping(UserModel user, RoleModel role) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<RoleModel> getScopeMappings(ClientModel client) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void addScopeMapping(ClientModel client, RoleModel role) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void deleteScopeMapping(ClientModel client, RoleModel role) {
//To change body of implemented methods use File | Settings | File Templates.
}
} }

View file

@ -0,0 +1,121 @@
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.CachedRealmRole;
import org.keycloak.models.cache.entities.CachedRole;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.HashSet;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RoleAdapter implements RoleModel {
protected RoleModel updated;
protected CachedRole cached;
protected KeycloakCache cache;
protected CacheKeycloakSession cacheSession;
protected RealmModel realm;
public RoleAdapter(CachedRole cached, KeycloakCache cache, CacheKeycloakSession session, RealmModel realm) {
this.cached = cached;
this.cache = cache;
this.cacheSession = session;
this.realm = realm;
}
protected void getDelegateForUpdate() {
if (updated == null) {
updated = cacheSession.getDelegate().getRoleById(getId(), realm);
if (updated == null) throw new IllegalStateException("Not found in database");
}
}
@Override
public String getName() {
if (updated != null) return updated.getName();
return cached.getName();
}
@Override
public String getDescription() {
if (updated != null) return updated.getDescription();
return cached.getDescription();
}
@Override
public void setDescription(String description) {
getDelegateForUpdate();
updated.setDescription(description);
}
@Override
public String getId() {
if (updated != null) return updated.getId();
return cached.getId();
}
@Override
public void setName(String name) {
getDelegateForUpdate();
updated.setName(name);
}
@Override
public boolean isComposite() {
if (updated != null) return updated.isComposite();
return cached.isComposite();
}
@Override
public void addCompositeRole(RoleModel role) {
getDelegateForUpdate();
updated.addCompositeRole(role);
}
@Override
public void removeCompositeRole(RoleModel role) {
getDelegateForUpdate();
updated.removeCompositeRole(role);
}
@Override
public Set<RoleModel> getComposites() {
if (updated != null) return updated.getComposites();
Set<RoleModel> set = new HashSet<RoleModel>();
for (String id : cached.getComposites()) {
RoleModel role = realm.getRoleById(id);
if (role == null) {
throw new IllegalStateException("Could not find composite: " + id);
}
set.add(role);
}
return set;
}
@Override
public RoleContainerModel getContainer() {
if (cached instanceof CachedRealmRole) {
return realm;
} else {
CachedApplicationRole appRole = (CachedApplicationRole)cached;
return realm.getApplicationById(appRole.getAppId());
}
}
@Override
public boolean hasRole(RoleModel role) {
if (this.equals(role)) return true;
if (!isComposite()) return false;
Set<RoleModel> visited = new HashSet<RoleModel>();
return KeycloakModelUtils.searchFor(role, this, visited);
}
}

View file

@ -5,7 +5,10 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.KeycloakTransaction; import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.cache.entities.CachedApplication;
import org.keycloak.models.cache.entities.CachedOAuthClient;
import org.keycloak.models.cache.entities.CachedRealm; import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
import org.keycloak.provider.ProviderSession; import org.keycloak.provider.ProviderSession;
import org.keycloak.provider.ProviderSessionFactory; import org.keycloak.provider.ProviderSessionFactory;
@ -56,4 +59,64 @@ public class SimpleCache implements KeycloakCache {
public CachedRealm getCachedRealmByName(String name) { public CachedRealm getCachedRealmByName(String name) {
return realmCacheByName.get(name); return realmCacheByName.get(name);
} }
@Override
public CachedApplication getApplication(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateApplication(CachedApplication app) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void addCachedApplication(CachedApplication app) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateCachedApplicationById(String id) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public CachedOAuthClient getOAuthClient(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateOAuthClient(CachedOAuthClient client) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void addCachedOAuthClient(CachedOAuthClient client) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateCachedOAuthClientById(String id) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public CachedRole getRole(String id) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateRole(CachedRole role) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void addCachedRole(CachedRole role) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateCachedRoleById(String id) {
//To change body of implemented methods use File | Settings | File Templates.
}
} }

View file

@ -0,0 +1,70 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.cache.KeycloakCache;
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>
* @version $Revision: 1 $
*/
public class CachedApplication extends CachedClient {
private boolean surrogateAuthRequired;
private String managementUrl;
private String baseUrl;
private List<String> defaultRoles = new LinkedList<String>();
private boolean bearerOnly;
private Map<String, String> roles = new HashMap<String, String>();
public CachedApplication(KeycloakCache cache, KeycloakSession delegate, RealmModel realm, ApplicationModel model) {
super(cache, delegate, realm, model);
surrogateAuthRequired = model.isSurrogateAuthRequired();
managementUrl = model.getManagementUrl();
baseUrl = model.getBaseUrl();
defaultRoles.addAll(model.getDefaultRoles());
bearerOnly = model.isBearerOnly();
for (RoleModel role : model.getRoles()) {
roles.put(role.getName(), role.getId());
cache.addCachedRole(new CachedApplicationRole(id, role));
}
}
public boolean isSurrogateAuthRequired() {
return surrogateAuthRequired;
}
public String getManagementUrl() {
return managementUrl;
}
public String getBaseUrl() {
return baseUrl;
}
public List<String> getDefaultRoles() {
return defaultRoles;
}
public boolean isBearerOnly() {
return bearerOnly;
}
public Map<String, String> getRoles() {
return roles;
}
}

View file

@ -0,0 +1,21 @@
package org.keycloak.models.cache.entities;
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) {
super(model);
this.appId = appId;
}
public String getAppId() {
return appId;
}
}

View file

@ -0,0 +1,90 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.cache.KeycloakCache;
import java.util.HashSet;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedClient {
protected String id;
protected String name;
protected long allowedClaimsMask;
protected Set<String> redirectUris = new HashSet<String>();
protected boolean enabled;
protected String secret;
protected boolean publicClient;
protected boolean directGrantsOnly;
protected int notBefore;
protected Set<String> scope = new HashSet<String>();
protected Set<String> webOrigins = new HashSet<String>();
public CachedClient(KeycloakCache cache, KeycloakSession delegate, RealmModel realm, ClientModel model) {
id = model.getId();
secret = model.getSecret();
name = model.getClientId();
enabled = model.isEnabled();
notBefore = model.getNotBefore();
directGrantsOnly = model.isDirectGrantsOnly();
publicClient = model.isPublicClient();
allowedClaimsMask = model.getAllowedClaimsMask();
redirectUris.addAll(model.getRedirectUris());
webOrigins.addAll(model.getWebOrigins());
for (RoleModel role : model.getScopeMappings()) {
scope.add(role.getId());
}
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public long getAllowedClaimsMask() {
return allowedClaimsMask;
}
public Set<String> getRedirectUris() {
return redirectUris;
}
public boolean isEnabled() {
return enabled;
}
public String getSecret() {
return secret;
}
public boolean isPublicClient() {
return publicClient;
}
public boolean isDirectGrantsOnly() {
return directGrantsOnly;
}
public int getNotBefore() {
return notBefore;
}
public Set<String> getScope() {
return scope;
}
public Set<String> getWebOrigins() {
return webOrigins;
}
}

View file

@ -0,0 +1,17 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.cache.KeycloakCache;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedOAuthClient extends CachedClient {
public CachedOAuthClient(KeycloakCache cache, KeycloakSession delegate, RealmModel realm, OAuthClientModel model) {
super(cache, delegate, realm, model);
}
}

View file

@ -1,29 +1,19 @@
package org.keycloak.models.cache.entities; package org.keycloak.models.cache.entities;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.AuthenticationProviderModel; import org.keycloak.models.AuthenticationProviderModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OAuthClientModel; import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy; import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel; import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.SocialLinkModel; import org.keycloak.models.cache.KeycloakCache;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UsernameLoginFailureModel;
import org.keycloak.models.entities.AuthenticationProviderEntity;
import org.keycloak.models.entities.RequiredCredentialEntity;
import java.io.Serializable;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
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;
@ -81,11 +71,16 @@ public class CachedRealm {
private boolean auditEnabled; private boolean auditEnabled;
private long auditExpiration; private long auditExpiration;
private Set<String> auditListeners = new HashSet<String>(); private Set<String> auditListeners = new HashSet<String>();
private List<String> defaultRoles = new LinkedList<String>();
private Map<String, String> realmRoles = new HashMap<String, String>();
private Set<String> rolesById = new HashSet<String>();
private Map<String, String> applications = new HashMap<String, String>();
private Map<String, String> clients = new HashMap<String, String>();
public CachedRealm() { public CachedRealm() {
} }
public CachedRealm(RealmModel model) { public CachedRealm(KeycloakCache cache, KeycloakSession delegate, RealmModel model) {
id = model.getId(); id = model.getId();
name = model.getName(); name = model.getName();
enabled = model.isEnabled(); enabled = model.isEnabled();
@ -133,6 +128,30 @@ public class CachedRealm {
auditEnabled = model.isAuditEnabled(); auditEnabled = model.isAuditEnabled();
auditExpiration = model.getAuditExpiration(); auditExpiration = model.getAuditExpiration();
auditListeners.addAll(model.getAuditListeners()); auditListeners.addAll(model.getAuditListeners());
defaultRoles.addAll(model.getDefaultRoles());
for (RoleModel role : model.getRoles()) {
realmRoles.put(role.getName(), role.getId());
rolesById.add(role.getId());
CachedRole cachedRole = new CachedRealmRole(role);
cache.addCachedRole(cachedRole);
}
for (ApplicationModel app : model.getApplications()) {
applications.put(app.getName(), app.getId());
CachedApplication cachedApp = new CachedApplication(cache, delegate, model, app);
cache.addCachedApplication(cachedApp);
for (String roleId : cachedApp.getRoles().values()) {
rolesById.add(roleId);
}
}
for (OAuthClientModel client : model.getOAuthClients()) {
clients.put(client.getClientId(), client.getId());
CachedOAuthClient cachedApp = new CachedOAuthClient(cache, delegate, model, client);
cache.addCachedOAuthClient(cachedApp);
}
} }
@ -144,6 +163,26 @@ public class CachedRealm {
return name; return name;
} }
public List<String> getDefaultRoles() {
return defaultRoles;
}
public Map<String, String> getRealmRoles() {
return realmRoles;
}
public Set<String> getRolesById() {
return rolesById;
}
public Map<String, String> getApplications() {
return applications;
}
public Map<String, String> getClients() {
return clients;
}
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return enabled;
} }

View file

@ -0,0 +1,20 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.RoleModel;
import java.util.HashSet;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedRealmRole extends CachedRole {
public CachedRealmRole(RoleModel model) {
super(model);
}
}

View file

@ -0,0 +1,51 @@
package org.keycloak.models.cache.entities;
import org.keycloak.models.RoleModel;
import java.util.HashSet;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CachedRole {
final protected String id;
final protected String name;
final protected String description;
final protected boolean composite;
final protected Set<String> composites = new HashSet<String>();
public CachedRole(RoleModel model) {
composite = model.isComposite();
description = model.getDescription();
id = model.getId();
name = model.getName();
if (composite) {
for (RoleModel child : model.getComposites()) {
composites.add(child.getId());
}
}
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public boolean isComposite() {
return composite;
}
public Set<String> getComposites() {
return composites;
}
}

View file

@ -2,6 +2,7 @@ package org.keycloak.models.jpa;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
@ -100,10 +101,10 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
@Override @Override
public RoleModel getRole(String name) { public RoleModel getRole(String name) {
TypedQuery<ApplicationRoleEntity> query = em.createNamedQuery("getAppRoleByName", ApplicationRoleEntity.class); TypedQuery<RoleEntity> query = em.createNamedQuery("getAppRoleByName", RoleEntity.class);
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("application", entity); query.setParameter("application", entity);
List<ApplicationRoleEntity> roles = query.getResultList(); List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null; if (roles.size() == 0) return null;
return new RoleAdapter(realm, em, roles.get(0)); return new RoleAdapter(realm, em, roles.get(0));
} }
@ -115,10 +116,12 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
@Override @Override
public RoleModel addRole(String id, String name) { public RoleModel addRole(String id, String name) {
ApplicationRoleEntity roleEntity = new ApplicationRoleEntity(); RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id); roleEntity.setId(id);
roleEntity.setName(name); roleEntity.setName(name);
roleEntity.setApplication(applicationEntity); roleEntity.setApplication(applicationEntity);
roleEntity.setApplicationRole(true);
roleEntity.setRealmId(realm.getId());
em.persist(roleEntity); em.persist(roleEntity);
applicationEntity.getRoles().add(roleEntity); applicationEntity.getRoles().add(roleEntity);
em.flush(); em.flush();
@ -133,9 +136,9 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
} }
if (!roleAdapter.getContainer().equals(this)) return false; if (!roleAdapter.getContainer().equals(this)) return false;
if (!(roleAdapter.getRole() instanceof ApplicationRoleEntity)) return false; if (!roleAdapter.getRole().isApplicationRole()) return false;
ApplicationRoleEntity role = (ApplicationRoleEntity)roleAdapter.getRole(); RoleEntity role = roleAdapter.getRole();
applicationEntity.getRoles().remove(role); applicationEntity.getRoles().remove(role);
applicationEntity.getDefaultRoles().remove(role); applicationEntity.getDefaultRoles().remove(role);
@ -153,7 +156,7 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>(); Set<RoleModel> list = new HashSet<RoleModel>();
Collection<ApplicationRoleEntity> roles = applicationEntity.getRoles(); Collection<RoleEntity> roles = applicationEntity.getRoles();
if (roles == null) return list; if (roles == null) return list;
for (RoleEntity entity : roles) { for (RoleEntity entity : roles) {
list.add(new RoleAdapter(realm, em, entity)); list.add(new RoleAdapter(realm, em, entity));
@ -161,28 +164,9 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
return list; return list;
} }
@Override
public Set<RoleModel> getApplicationRoleMappings(UserModel user) {
Set<RoleModel> roleMappings = realm.getRoleMappings(user);
Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof RealmModel) {
} else {
ApplicationModel app = (ApplicationModel)container;
if (app.getId().equals(getId())) {
appRoles.add(role);
}
}
}
return appRoles;
}
@Override @Override
public Set<RoleModel> getApplicationScopeMappings(ClientModel client) { public Set<RoleModel> getApplicationScopeMappings(ClientModel client) {
Set<RoleModel> roleMappings = realm.getScopeMappings(client); Set<RoleModel> roleMappings = client.getScopeMappings();
Set<RoleModel> appRoles = new HashSet<RoleModel>(); Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) { for (RoleModel role : roleMappings) {

View file

@ -2,9 +2,12 @@ package org.keycloak.models.jpa;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.jpa.entities.ClientEntity; import org.keycloak.models.jpa.entities.ClientEntity;
import org.keycloak.models.jpa.entities.ClientUserSessionAssociationEntity; import org.keycloak.models.jpa.entities.ClientUserSessionAssociationEntity;
import org.keycloak.models.jpa.entities.ScopeMappingEntity;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.Query; import javax.persistence.Query;
@ -174,6 +177,74 @@ public abstract class ClientAdapter implements ClientModel {
em.createNamedQuery("removeClientUserSessionByClient").setParameter("clientId", getId()).executeUpdate(); em.createNamedQuery("removeClientUserSessionByClient").setParameter("clientId", getId()).executeUpdate();
} }
@Override
public Set<RoleModel> getRealmScopeMappings() {
Set<RoleModel> roleMappings = getScopeMappings();
Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof RealmModel) {
if (((RealmModel) container).getId().equals(realm.getId())) {
appRoles.add(role);
}
}
}
return appRoles;
}
@Override
public Set<RoleModel> getScopeMappings() {
TypedQuery<ScopeMappingEntity> query = em.createNamedQuery("clientScopeMappings", ScopeMappingEntity.class);
query.setParameter("client", getEntity());
List<ScopeMappingEntity> entities = query.getResultList();
Set<RoleModel> roles = new HashSet<RoleModel>();
for (ScopeMappingEntity entity : entities) {
roles.add(new RoleAdapter(realm, em, entity.getRole()));
}
return roles;
}
@Override
public void addScopeMapping(RoleModel role) {
if (hasScope(role)) return;
ScopeMappingEntity entity = new ScopeMappingEntity();
entity.setClient(getEntity());
entity.setRole(((RoleAdapter) role).getRole());
em.persist(entity);
}
@Override
public void deleteScopeMapping(RoleModel role) {
TypedQuery<ScopeMappingEntity> query = getRealmScopeMappingQuery((RoleAdapter) role);
List<ScopeMappingEntity> results = query.getResultList();
if (results.size() == 0) return;
for (ScopeMappingEntity entity : results) {
em.remove(entity);
}
}
protected TypedQuery<ScopeMappingEntity> getRealmScopeMappingQuery(RoleAdapter role) {
TypedQuery<ScopeMappingEntity> query = em.createNamedQuery("hasScope", ScopeMappingEntity.class);
query.setParameter("client", getEntity());
query.setParameter("role", ((RoleAdapter) role).getRole());
return query;
}
@Override
public boolean hasScope(RoleModel role) {
Set<RoleModel> roles = getScopeMappings();
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;

View file

@ -10,6 +10,8 @@ import java.lang.reflect.Proxy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; 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>
@ -73,35 +75,35 @@ public class JpaKeycloakSession implements KeycloakSession {
} }
@Override @Override
public UserModel getUserById(String id, String realmId) { public UserModel getUserById(String id, RealmModel realmModel) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserById", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserById", UserEntity.class);
query.setParameter("id", id); query.setParameter("id", id);
RealmEntity realm = em.getReference(RealmEntity.class, realmId); RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId());
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<UserEntity> entities = query.getResultList(); List<UserEntity> entities = query.getResultList();
if (entities.size() == 0) return null; if (entities.size() == 0) return null;
return new UserAdapter(em, entities.get(0)); return new UserAdapter(realmModel, em, entities.get(0));
} }
@Override @Override
public UserModel getUserByUsername(String username, String realmId) { public UserModel getUserByUsername(String username, RealmModel realmModel) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByLoginName", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByLoginName", UserEntity.class);
query.setParameter("loginName", username); query.setParameter("loginName", username);
RealmEntity realm = em.getReference(RealmEntity.class, realmId); RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId());
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
if (results.size() == 0) return null; if (results.size() == 0) return null;
return new UserAdapter(em, results.get(0)); return new UserAdapter(realmModel, em, results.get(0));
} }
@Override @Override
public UserModel getUserByEmail(String email, String realmId) { public UserModel getUserByEmail(String email, RealmModel realmModel) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class);
query.setParameter("email", email); query.setParameter("email", email);
RealmEntity realm = em.getReference(RealmEntity.class, realmId); RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId());
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
return results.isEmpty() ? null : new UserAdapter(em, results.get(0)); return results.isEmpty() ? null : new UserAdapter(realmModel, em, results.get(0));
} }
@Override @Override
@ -144,4 +146,59 @@ public class JpaKeycloakSession implements KeycloakSession {
removeRealm(realm.getId()); removeRealm(realm.getId());
} }
} }
@Override
public UserModel getUserBySocialLink(SocialLinkModel socialLink, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> getUsers(RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<RoleModel> getRealmRoleMappings(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<SocialLinkModel> getSocialLinks(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public SocialLinkModel getSocialLink(UserModel user, String socialProvider, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public AuthenticationLinkModel getAuthenticationLink(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public RoleModel getRoleById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ApplicationModel getApplicationById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public OAuthClientModel getOAuthClientById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
} }

View file

@ -3,18 +3,16 @@ package org.keycloak.models.jpa;
import org.keycloak.models.AuthenticationLinkModel; import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.AuthenticationProviderModel; import org.keycloak.models.AuthenticationProviderModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UsernameLoginFailureModel; import org.keycloak.models.UsernameLoginFailureModel;
import org.keycloak.models.jpa.entities.ApplicationEntity; import org.keycloak.models.jpa.entities.ApplicationEntity;
import org.keycloak.models.jpa.entities.ApplicationRoleEntity;
import org.keycloak.models.jpa.entities.AuthenticationLinkEntity; import org.keycloak.models.jpa.entities.AuthenticationLinkEntity;
import org.keycloak.models.jpa.entities.AuthenticationProviderEntity; import org.keycloak.models.jpa.entities.AuthenticationProviderEntity;
import org.keycloak.models.jpa.entities.CredentialEntity;
import org.keycloak.models.jpa.entities.OAuthClientEntity; import org.keycloak.models.jpa.entities.OAuthClientEntity;
import org.keycloak.models.jpa.entities.RealmEntity; import org.keycloak.models.jpa.entities.RealmEntity;
import org.keycloak.models.jpa.entities.RealmRoleEntity;
import org.keycloak.models.jpa.entities.RequiredCredentialEntity; import org.keycloak.models.jpa.entities.RequiredCredentialEntity;
import org.keycloak.models.jpa.entities.RoleEntity; import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.jpa.entities.ScopeMappingEntity; import org.keycloak.models.jpa.entities.ScopeMappingEntity;
@ -429,7 +427,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
if (results.size() == 0) return null; if (results.size() == 0) return null;
return new UserAdapter(em, results.get(0)); return new UserAdapter(this, em, results.get(0));
} }
@Override @Override
@ -470,7 +468,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("email", email); query.setParameter("email", email);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
return results.isEmpty() ? null : new UserAdapter(em, results.get(0)); return results.isEmpty() ? null : new UserAdapter(this, em, results.get(0));
} }
@Override @Override
@ -479,7 +477,7 @@ public class RealmAdapter implements RealmModel {
// Check if user belongs to this realm // Check if user belongs to this realm
if (entity == null || !this.realm.equals(entity.getRealm())) return null; if (entity == null || !this.realm.equals(entity.getRealm())) return null;
return new UserAdapter(em, entity); return new UserAdapter(this, em, entity);
} }
@Override @Override
@ -495,15 +493,15 @@ public class RealmAdapter implements RealmModel {
entity.setRealm(realm); entity.setRealm(realm);
em.persist(entity); em.persist(entity);
em.flush(); em.flush();
UserModel userModel = new UserAdapter(em, entity); UserModel userModel = new UserAdapter(this, em, entity);
for (String r : getDefaultRoles()) { for (String r : getDefaultRoles()) {
grantRole(userModel, getRole(r)); userModel.grantRole(getRole(r));
} }
for (ApplicationModel application : getApplications()) { for (ApplicationModel application : getApplications()) {
for (String r : application.getDefaultRoles()) { for (String r : application.getDefaultRoles()) {
grantRole(userModel, application.getRole(r)); userModel.grantRole(application.getRole(r));
} }
} }
@ -706,7 +704,7 @@ public class RealmAdapter implements RealmModel {
", socialUserId=" + socialLink.getSocialUserId() + ", results=" + results); ", socialUserId=" + socialLink.getSocialUserId() + ", results=" + results);
} else { } else {
UserEntity user = results.get(0); UserEntity user = results.get(0);
return new UserAdapter(em, user); return new UserAdapter(this, em, user);
} }
} }
@ -808,7 +806,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
List<UserModel> users = new ArrayList<UserModel>(); List<UserModel> users = new ArrayList<UserModel>();
for (UserEntity entity : results) users.add(new UserAdapter(em, entity)); for (UserEntity entity : results) users.add(new UserAdapter(this, em, entity));
return users; return users;
} }
@ -819,7 +817,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("search", "%" + search.toLowerCase() + "%"); query.setParameter("search", "%" + search.toLowerCase() + "%");
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
List<UserModel> users = new ArrayList<UserModel>(); List<UserModel> users = new ArrayList<UserModel>();
for (UserEntity entity : results) users.add(new UserAdapter(em, entity)); for (UserEntity entity : results) users.add(new UserAdapter(this, em, entity));
return users; return users;
} }
@ -851,7 +849,7 @@ public class RealmAdapter implements RealmModel {
TypedQuery<UserEntity> query = em.createQuery(q, UserEntity.class); TypedQuery<UserEntity> query = em.createQuery(q, UserEntity.class);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
List<UserModel> users = new ArrayList<UserModel>(); List<UserModel> users = new ArrayList<UserModel>();
for (UserEntity entity : results) users.add(new UserAdapter(em, entity)); for (UserEntity entity : results) users.add(new UserAdapter(this, em, entity));
return users; return users;
} }
@ -1003,10 +1001,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel getRole(String name) { public RoleModel getRole(String name) {
TypedQuery<RealmRoleEntity> query = em.createNamedQuery("getRealmRoleByName", RealmRoleEntity.class); TypedQuery<RoleEntity> query = em.createNamedQuery("getRealmRoleByName", RoleEntity.class);
query.setParameter("name", name); query.setParameter("name", name);
query.setParameter("realm", realm); query.setParameter("realm", realm);
List<RealmRoleEntity> roles = query.getResultList(); List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null; if (roles.size() == 0) return null;
return new RoleAdapter(this, em, roles.get(0)); return new RoleAdapter(this, em, roles.get(0));
} }
@ -1018,10 +1016,11 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel addRole(String id, String name) { public RoleModel addRole(String id, String name) {
RealmRoleEntity entity = new RealmRoleEntity(); RoleEntity entity = new RoleEntity();
entity.setId(id); entity.setId(id);
entity.setName(name); entity.setName(name);
entity.setRealm(realm); entity.setRealm(realm);
entity.setRealmId(realm.getId());
realm.getRoles().add(entity); realm.getRoles().add(entity);
em.persist(entity); em.persist(entity);
em.flush(); em.flush();
@ -1051,7 +1050,7 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public Set<RoleModel> getRoles() { public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>(); Set<RoleModel> list = new HashSet<RoleModel>();
Collection<RealmRoleEntity> roles = realm.getRoles(); Collection<RoleEntity> roles = realm.getRoles();
if (roles == null) return list; if (roles == null) return list;
for (RoleEntity entity : roles) { for (RoleEntity entity : roles) {
list.add(new RoleAdapter(this, em, entity)); list.add(new RoleAdapter(this, em, entity));
@ -1061,15 +1060,10 @@ public class RealmAdapter implements RealmModel {
@Override @Override
public RoleModel getRoleById(String id) { public RoleModel getRoleById(String id) {
RoleEntity entity = em.find(RoleEntity.class, id); RoleEntity entity = null;
entity = em.find(RoleEntity.class, id);
if (entity == null) return null; if (entity == null) return null;
if (entity instanceof RealmRoleEntity) { if (!getId().equals(entity.getRealmId())) return null;
RealmRoleEntity roleEntity = (RealmRoleEntity) entity;
if (!roleEntity.getRealm().getId().equals(getId())) return null;
} else {
ApplicationRoleEntity roleEntity = (ApplicationRoleEntity) entity;
if (!roleEntity.getApplication().getRealm().getId().equals(getId())) return null;
}
return new RoleAdapter(this, em, entity); return new RoleAdapter(this, em, entity);
} }
@ -1080,141 +1074,9 @@ public class RealmAdapter implements RealmModel {
return role.getContainer().removeRole(role); return role.getContainer().removeRole(role);
} }
@Override
public boolean hasRole(UserModel user, RoleModel role) {
Set<RoleModel> roles = getRoleMappings(user);
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override
public boolean hasScope(ClientModel client, RoleModel role) {
Set<RoleModel> roles = getScopeMappings(client);
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
protected TypedQuery<UserRoleMappingEntity> getUserRoleMappingEntityTypedQuery(UserAdapter user, RoleAdapter role) {
TypedQuery<UserRoleMappingEntity> query = em.createNamedQuery("userHasRole", UserRoleMappingEntity.class);
query.setParameter("user", user.getUser());
query.setParameter("role", role.getRole());
return query;
}
@Override
public void grantRole(UserModel user, RoleModel role) {
if (hasRole(user, role)) return;
UserRoleMappingEntity entity = new UserRoleMappingEntity();
entity.setUser(((UserAdapter) user).getUser());
entity.setRole(((RoleAdapter) role).getRole());
em.persist(entity);
em.flush();
}
@Override
public Set<RoleModel> getRealmRoleMappings(UserModel user) {
Set<RoleModel> roleMappings = getRoleMappings(user);
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof RealmModel) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public Set<RoleModel> getRoleMappings(UserModel user) {
TypedQuery<UserRoleMappingEntity> query = em.createNamedQuery("userRoleMappings", UserRoleMappingEntity.class);
query.setParameter("user", ((UserAdapter) user).getUser());
List<UserRoleMappingEntity> entities = query.getResultList();
Set<RoleModel> roles = new HashSet<RoleModel>();
for (UserRoleMappingEntity entity : entities) {
roles.add(new RoleAdapter(this, em, entity.getRole()));
}
return roles;
}
@Override
public void deleteRoleMapping(UserModel user, RoleModel role) {
if (user == null || role == null) return;
TypedQuery<UserRoleMappingEntity> query = getUserRoleMappingEntityTypedQuery((UserAdapter) user, (RoleAdapter) role);
List<UserRoleMappingEntity> results = query.getResultList();
if (results.size() == 0) return;
for (UserRoleMappingEntity entity : results) {
em.remove(entity);
}
em.flush();
}
@Override
public Set<RoleModel> getRealmScopeMappings(ClientModel client) {
Set<RoleModel> roleMappings = getScopeMappings(client);
Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof RealmModel) {
if (((RealmModel) container).getId().equals(getId())) {
appRoles.add(role);
}
}
}
return appRoles;
}
@Override
public Set<RoleModel> getScopeMappings(ClientModel client) {
TypedQuery<ScopeMappingEntity> query = em.createNamedQuery("clientScopeMappings", ScopeMappingEntity.class);
query.setParameter("client", ((ClientAdapter) client).getEntity());
List<ScopeMappingEntity> entities = query.getResultList();
Set<RoleModel> roles = new HashSet<RoleModel>();
for (ScopeMappingEntity entity : entities) {
roles.add(new RoleAdapter(this, em, entity.getRole()));
}
return roles;
}
@Override
public void addScopeMapping(ClientModel client, RoleModel role) {
if (hasScope(client, role)) return;
ScopeMappingEntity entity = new ScopeMappingEntity();
entity.setClient(((ClientAdapter) client).getEntity());
entity.setRole(((RoleAdapter) role).getRole());
em.persist(entity);
}
@Override
public void deleteScopeMapping(ClientModel client, RoleModel role) {
TypedQuery<ScopeMappingEntity> query = getRealmScopeMappingQuery((ClientAdapter) client, (RoleAdapter) role);
List<ScopeMappingEntity> results = query.getResultList();
if (results.size() == 0) return;
for (ScopeMappingEntity entity : results) {
em.remove(entity);
}
}
protected TypedQuery<ScopeMappingEntity> getRealmScopeMappingQuery(ClientAdapter client, RoleAdapter role) {
TypedQuery<ScopeMappingEntity> query = em.createNamedQuery("hasScope", ScopeMappingEntity.class);
query.setParameter("client", client.getEntity());
query.setParameter("role", ((RoleAdapter) role).getRole());
return query;
}
@Override @Override
public boolean validatePassword(UserModel user, String password) { public boolean validatePassword(UserModel user, String password) {

View file

@ -3,8 +3,6 @@ package org.keycloak.models.jpa;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.jpa.entities.ApplicationRoleEntity;
import org.keycloak.models.jpa.entities.RealmRoleEntity;
import org.keycloak.models.jpa.entities.RoleEntity; import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
@ -106,15 +104,12 @@ public class RoleAdapter implements RoleModel {
@Override @Override
public RoleContainerModel getContainer() { public RoleContainerModel getContainer() {
if (role instanceof ApplicationRoleEntity) { if (role.isApplicationRole()) {
ApplicationRoleEntity entity = (ApplicationRoleEntity)role; return realm.getApplicationById(role.getApplication().getId());
return new ApplicationAdapter(realm, em, entity.getApplication());
} else if (role instanceof RealmRoleEntity) {
RealmRoleEntity entity = (RealmRoleEntity)role;
return new RealmAdapter(em, entity.getRealm());
} else {
return realm;
} }
throw new IllegalStateException("Unknown role entity type");
} }
@Override @Override

View file

@ -1,13 +1,20 @@
package org.keycloak.models.jpa; package org.keycloak.models.jpa;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.jpa.entities.CredentialEntity; import org.keycloak.models.jpa.entities.CredentialEntity;
import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.jpa.entities.UserEntity; import org.keycloak.models.jpa.entities.UserEntity;
import org.keycloak.models.jpa.entities.UserRoleMappingEntity;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder; import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -25,10 +32,12 @@ public class UserAdapter implements UserModel {
protected UserEntity user; protected UserEntity user;
protected EntityManager em; protected EntityManager em;
protected RealmModel realm;
public UserAdapter(EntityManager em, UserEntity user) { public UserAdapter(RealmModel realm, EntityManager em, UserEntity user) {
this.em = em; this.em = em;
this.user = user; this.user = user;
this.realm = realm;
} }
public UserEntity getUser() { public UserEntity getUser() {
@ -243,6 +252,90 @@ public class UserAdapter implements UserModel {
em.flush(); em.flush();
} }
@Override
public boolean hasRole(RoleModel role) {
Set<RoleModel> roles = getRoleMappings();
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
protected TypedQuery<UserRoleMappingEntity> getUserRoleMappingEntityTypedQuery(RoleModel role) {
TypedQuery<UserRoleMappingEntity> query = em.createNamedQuery("userHasRole", UserRoleMappingEntity.class);
query.setParameter("user", getUser());
RoleEntity roleEntity = em.getReference(RoleEntity.class, role.getId());
query.setParameter("role", roleEntity);
return query;
}
@Override
public void grantRole(RoleModel role) {
if (hasRole(role)) return;
UserRoleMappingEntity entity = new UserRoleMappingEntity();
entity.setUser(getUser());
RoleEntity roleEntity = em.getReference(RoleEntity.class, role.getId());
entity.setRole(roleEntity);
em.persist(entity);
em.flush();
}
@Override
public Set<RoleModel> getRealmRoleMappings() {
Set<RoleModel> roleMappings = getRoleMappings();
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof RealmModel) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public Set<RoleModel> getRoleMappings() {
TypedQuery<UserRoleMappingEntity> query = em.createNamedQuery("userRoleMappings", UserRoleMappingEntity.class);
query.setParameter("user", getUser());
List<UserRoleMappingEntity> entities = query.getResultList();
Set<RoleModel> roles = new HashSet<RoleModel>();
for (UserRoleMappingEntity entity : entities) {
roles.add(realm.getRoleById(entity.getRole().getId()));
}
return roles;
}
@Override
public void deleteRoleMapping(RoleModel role) {
if (user == null || role == null) return;
TypedQuery<UserRoleMappingEntity> query = getUserRoleMappingEntityTypedQuery(role);
List<UserRoleMappingEntity> results = query.getResultList();
if (results.size() == 0) return;
for (UserRoleMappingEntity entity : results) {
em.remove(entity);
}
em.flush();
}
@Override
public Set<RoleModel> getApplicationRoleMappings(ApplicationModel app) {
Set<RoleModel> roleMappings = getRoleMappings();
Set<RoleModel> roles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof ApplicationModel) {
ApplicationModel appModel = (ApplicationModel)container;
if (appModel.getId().equals(app.getId())) {
roles.add(role);
}
}
}
return roles;
}
} }

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
@ -17,9 +18,9 @@ public class AbstractRoleMappingEntity {
@GenericGenerator(name="keycloak_generator", strategy="org.keycloak.models.jpa.utils.JpaIdGenerator") @GenericGenerator(name="keycloak_generator", strategy="org.keycloak.models.jpa.utils.JpaIdGenerator")
@GeneratedValue(generator = "keycloak_generator") @GeneratedValue(generator = "keycloak_generator")
protected String id; protected String id;
@ManyToOne @ManyToOne(fetch= FetchType.LAZY)
protected UserEntity user; protected UserEntity user;
@ManyToOne @ManyToOne(fetch= FetchType.LAZY)
protected RoleEntity role; protected RoleEntity role;
public String getId() { public String getId() {

View file

@ -34,7 +34,7 @@ public class ApplicationEntity extends ClientEntity {
private boolean bearerOnly; private boolean bearerOnly;
@OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application") @OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application")
Collection<ApplicationRoleEntity> roles = new ArrayList<ApplicationRoleEntity>(); Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="ApplicationDefaultRoles") @JoinTable(name="ApplicationDefaultRoles")
@ -64,11 +64,11 @@ public class ApplicationEntity extends ClientEntity {
this.managementUrl = managementUrl; this.managementUrl = managementUrl;
} }
public Collection<ApplicationRoleEntity> getRoles() { public Collection<RoleEntity> getRoles() {
return roles; return roles;
} }
public void setRoles(Collection<ApplicationRoleEntity> roles) { public void setRoles(Collection<RoleEntity> roles) {
this.roles = roles; this.roles = roles;
} }

View file

@ -1,45 +0,0 @@
package org.keycloak.models.jpa.entities;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@NamedQueries({
@NamedQuery(name="getAppRoleByName", query="select role from ApplicationRoleEntity role where role.name = :name and role.application = :application")
})
@Entity
public class ApplicationRoleEntity extends RoleEntity {
private String name;
@ManyToOne
@JoinColumn(name = "application")
private ApplicationEntity application;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ApplicationEntity getApplication() {
return application;
}
public void setApplication(ApplicationEntity application) {
this.application = application;
}
}

View file

@ -91,7 +91,7 @@ public class RealmEntity {
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<RealmRoleEntity> roles = new ArrayList<RealmRoleEntity>(); Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@ElementCollection @ElementCollection
@MapKeyColumn(name="name") @MapKeyColumn(name="name")
@ -292,17 +292,17 @@ public class RealmEntity {
this.applications = applications; this.applications = applications;
} }
public Collection<RealmRoleEntity> getRoles() { public Collection<RoleEntity> getRoles() {
return roles; return roles;
} }
public void setRoles(Collection<RealmRoleEntity> roles) { public void setRoles(Collection<RoleEntity> roles) {
this.roles = roles; this.roles = roles;
} }
public void addRole(RealmRoleEntity role) { public void addRole(RoleEntity role) {
if (roles == null) { if (roles == null) {
roles = new ArrayList<RealmRoleEntity>(); roles = new ArrayList<RoleEntity>();
} }
roles.add(role); roles.add(role);
} }

View file

@ -1,42 +0,0 @@
package org.keycloak.models.jpa.entities;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@NamedQueries({
@NamedQuery(name="getRealmRoleByName", query="select role from RealmRoleEntity role where role.name = :name and role.realm = :realm")
})
@Entity
public class RealmRoleEntity extends RoleEntity {
private String name;
@ManyToOne
@JoinColumn(name = "realm")
private RealmEntity realm;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public RealmEntity getRealm() {
return realm;
}
public void setRealm(RealmEntity realm) {
this.realm = realm;
}
}

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -9,6 +10,9 @@ import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.JoinTable; import javax.persistence.JoinTable;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.UniqueConstraint; import javax.persistence.UniqueConstraint;
import java.util.ArrayList; import java.util.ArrayList;
@ -21,16 +25,38 @@ import org.hibernate.annotations.GenericGenerator;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Entity @Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(uniqueConstraints = { @Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "name", "application" }), @UniqueConstraint(columnNames = { "name", "application"}),
@UniqueConstraint(columnNames = { "name", "realm" }) @UniqueConstraint(columnNames = { "name", "realm" })
}) })
public abstract class RoleEntity { @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")
})
public class RoleEntity {
@Id @Id
@Column(name="id")
private String id; private String id;
private String name;
private String description; private String description;
// hax! couldn't get constraint to work properly
private String realmId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "realm")
private RealmEntity realm;
@Column(name="applicationRole")
private boolean applicationRole;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "application")
private ApplicationEntity application;
@ManyToMany(fetch = FetchType.LAZY, cascade = {}) @ManyToMany(fetch = FetchType.LAZY, cascade = {})
@JoinTable(name = "CompositeRole", joinColumns = @JoinColumn(name = "composite"), inverseJoinColumns = @JoinColumn(name = "role")) @JoinTable(name = "CompositeRole", joinColumns = @JoinColumn(name = "composite"), inverseJoinColumns = @JoinColumn(name = "role"))
private Collection<RoleEntity> compositeRoles = new ArrayList<RoleEntity>(); private Collection<RoleEntity> compositeRoles = new ArrayList<RoleEntity>();
@ -43,9 +69,21 @@ public abstract class RoleEntity {
this.id = id; this.id = id;
} }
public abstract String getName(); public String getRealmId() {
return realmId;
}
public abstract void setName(String name); public void setRealmId(String realmId) {
this.realmId = realmId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() { public String getDescription() {
return description; return description;
@ -63,6 +101,30 @@ public abstract class RoleEntity {
this.compositeRoles = compositeRoles; this.compositeRoles = compositeRoles;
} }
public boolean isApplicationRole() {
return applicationRole;
}
public void setApplicationRole(boolean applicationRole) {
this.applicationRole = applicationRole;
}
public RealmEntity getRealm() {
return realm;
}
public void setRealm(RealmEntity realm) {
this.realm = realm;
}
public ApplicationEntity getApplication() {
return application;
}
public void setApplication(ApplicationEntity application) {
this.application = application;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;

View file

@ -11,8 +11,7 @@
<class>org.keycloak.models.jpa.entities.RealmEntity</class> <class>org.keycloak.models.jpa.entities.RealmEntity</class>
<class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class> <class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class> <class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class> <class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class> <class>org.keycloak.models.jpa.entities.UserEntity</class>

View file

@ -22,7 +22,7 @@ import java.util.Set;
*/ */
public class ApplicationAdapter extends ClientAdapter<MongoApplicationEntity> implements ApplicationModel { public class ApplicationAdapter extends ClientAdapter<MongoApplicationEntity> implements ApplicationModel {
public ApplicationAdapter(RealmAdapter realm, MongoApplicationEntity applicationEntity, MongoStoreInvocationContext invContext) { public ApplicationAdapter(RealmModel realm, MongoApplicationEntity applicationEntity, MongoStoreInvocationContext invContext) {
super(realm, applicationEntity, invContext); super(realm, applicationEntity, invContext);
} }
@ -159,19 +159,6 @@ public class ApplicationAdapter extends ClientAdapter<MongoApplicationEntity> im
return result; return result;
} }
@Override
public Set<RoleModel> getApplicationRoleMappings(UserModel user) {
Set<RoleModel> result = new HashSet<RoleModel>();
List<MongoRoleEntity> roles = MongoModelUtils.getAllRolesOfUser(user, invocationContext);
for (MongoRoleEntity role : roles) {
if (getId().equals(role.getApplicationId())) {
result.add(new RoleAdapter(getRealm(), role, this, invocationContext));
}
}
return result;
}
@Override @Override
public Set<RoleModel> getApplicationScopeMappings(ClientModel client) { public Set<RoleModel> getApplicationScopeMappings(ClientModel client) {
Set<RoleModel> result = new HashSet<RoleModel>(); Set<RoleModel> result = new HashSet<RoleModel>();

View file

@ -9,11 +9,14 @@ import com.mongodb.DBObject;
import com.mongodb.QueryBuilder; import com.mongodb.QueryBuilder;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.entities.ClientEntity; import org.keycloak.models.entities.ClientEntity;
import org.keycloak.models.mongo.api.MongoIdentifiableEntity; import org.keycloak.models.mongo.api.MongoIdentifiableEntity;
import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoUserSessionEntity; import org.keycloak.models.mongo.keycloak.entities.MongoUserSessionEntity;
import org.keycloak.models.mongo.utils.MongoModelUtils;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
@ -21,9 +24,9 @@ import org.keycloak.models.mongo.keycloak.entities.MongoUserSessionEntity;
public abstract class ClientAdapter<T extends MongoIdentifiableEntity> extends AbstractMongoAdapter<T> implements ClientModel { public abstract class ClientAdapter<T extends MongoIdentifiableEntity> extends AbstractMongoAdapter<T> implements ClientModel {
protected final T clientEntity; protected final T clientEntity;
private final RealmAdapter realm; private final RealmModel realm;
public ClientAdapter(RealmAdapter realm, T clientEntity, MongoStoreInvocationContext invContext) { public ClientAdapter(RealmModel realm, T clientEntity, MongoStoreInvocationContext invContext) {
super(invContext); super(invContext);
this.clientEntity = clientEntity; this.clientEntity = clientEntity;
this.realm = realm; this.realm = realm;
@ -153,7 +156,7 @@ public abstract class ClientAdapter<T extends MongoIdentifiableEntity> extends A
} }
@Override @Override
public RealmAdapter getRealm() { public RealmModel getRealm() {
return realm; return realm;
} }
@ -188,4 +191,59 @@ public abstract class ClientAdapter<T extends MongoIdentifiableEntity> extends A
// todo, something more efficient like COUNT in JPAQL? // todo, something more efficient like COUNT in JPAQL?
return getUserSessions().size(); return getUserSessions().size();
} }
@Override
public Set<RoleModel> getScopeMappings() {
Set<RoleModel> result = new HashSet<RoleModel>();
List<MongoRoleEntity> roles = MongoModelUtils.getAllScopesOfClient(this, invocationContext);
for (MongoRoleEntity role : roles) {
if (realm.getId().equals(role.getRealmId())) {
result.add(new RoleAdapter(realm, role, realm, invocationContext));
} else {
// Likely applicationRole, but we don't have this application yet
result.add(new RoleAdapter(realm, role, invocationContext));
}
}
return result;
}
@Override
public Set<RoleModel> getRealmScopeMappings() {
Set<RoleModel> allScopes = getScopeMappings();
// Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user?
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allScopes) {
MongoRoleEntity roleEntity = ((RoleAdapter) role).getRole();
if (realm.getId().equals(roleEntity.getRealmId())) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public boolean hasScope(RoleModel role) {
Set<RoleModel> roles = getScopeMappings();
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override
public void addScopeMapping(RoleModel role) {
getMongoStore().pushItemToList(this.getMongoEntity(), "scopeIds", role.getId(), true, invocationContext);
}
@Override
public void deleteScopeMapping(RoleModel role) {
getMongoStore().pullItemFromList(this.getMongoEntity(), "scopeIds", role.getId(), invocationContext);
}
} }

View file

@ -3,9 +3,14 @@ package org.keycloak.models.mongo.keycloak.adapters;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.QueryBuilder; import com.mongodb.QueryBuilder;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction; import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SocialLinkModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.mongo.api.MongoStore; import org.keycloak.models.mongo.api.MongoStore;
import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext;
@ -16,6 +21,8 @@ import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; 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>
@ -92,44 +99,44 @@ public class MongoKeycloakSession implements KeycloakSession {
} }
@Override @Override
public UserModel getUserById(String id, String realmId) { public UserModel getUserById(String id, RealmModel realm) {
MongoUserEntity user = getMongoStore().loadEntity(MongoUserEntity.class, id, invocationContext); MongoUserEntity user = getMongoStore().loadEntity(MongoUserEntity.class, id, invocationContext);
// Check that it's user from this realm // Check that it's user from this realm
if (user == null || !realmId.equals(user.getRealmId())) { if (user == null || !realm.getId().equals(user.getRealmId())) {
return null; return null;
} else { } else {
return new UserAdapter(user, invocationContext); return new UserAdapter(realm, user, invocationContext);
} }
} }
@Override @Override
public UserModel getUserByUsername(String username, String realmId) { public UserModel getUserByUsername(String username, RealmModel realm) {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder()
.and("loginName").is(username) .and("loginName").is(username)
.and("realmId").is(realmId) .and("realmId").is(realm.getId())
.get(); .get();
MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext); MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext);
if (user == null) { if (user == null) {
return null; return null;
} else { } else {
return new UserAdapter(user, invocationContext); return new UserAdapter(realm, user, invocationContext);
} }
} }
@Override @Override
public UserModel getUserByEmail(String email, String realmId) { public UserModel getUserByEmail(String email, RealmModel realm) {
DBObject query = new QueryBuilder() DBObject query = new QueryBuilder()
.and("email").is(email) .and("email").is(email)
.and("realmId").is(realmId) .and("realmId").is(realm.getId())
.get(); .get();
MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext); MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext);
if (user == null) { if (user == null) {
return null; return null;
} else { } else {
return new UserAdapter(user, invocationContext); return new UserAdapter(realm, user, invocationContext);
} }
} }
@ -141,4 +148,59 @@ public class MongoKeycloakSession implements KeycloakSession {
protected MongoStore getMongoStore() { protected MongoStore getMongoStore() {
return invocationContext.getMongoStore(); return invocationContext.getMongoStore();
} }
@Override
public UserModel getUserBySocialLink(SocialLinkModel socialLink, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> getUsers(RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<RoleModel> getRealmRoleMappings(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Set<SocialLinkModel> getSocialLinks(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public SocialLinkModel getSocialLink(UserModel user, String socialProvider, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public AuthenticationLinkModel getAuthenticationLink(UserModel user, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public RoleModel getRoleById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ApplicationModel getApplicationById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public OAuthClientModel getOAuthClientById(String id, RealmModel realm) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
} }

View file

@ -455,7 +455,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
if (user == null) { if (user == null) {
return null; return null;
} else { } else {
return new UserAdapter(user, invocationContext); return new UserAdapter(this, user, invocationContext);
} }
} }
@ -517,7 +517,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
if (user == null) { if (user == null) {
return null; return null;
} else { } else {
return new UserAdapter(user, invocationContext); return new UserAdapter(this, user, invocationContext);
} }
} }
@ -529,7 +529,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
if (user == null || !getId().equals(user.getRealmId())) { if (user == null || !getId().equals(user.getRealmId())) {
return null; return null;
} else { } else {
return new UserAdapter(user, invocationContext); return new UserAdapter(this, user, invocationContext);
} }
} }
@ -543,12 +543,12 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
UserAdapter userModel = addUserEntity(id, username); UserAdapter userModel = addUserEntity(id, username);
for (String r : getDefaultRoles()) { for (String r : getDefaultRoles()) {
grantRole(userModel, getRole(r)); userModel.grantRole(getRole(r));
} }
for (ApplicationModel application : getApplications()) { for (ApplicationModel application : getApplications()) {
for (String r : application.getDefaultRoles()) { for (String r : application.getDefaultRoles()) {
grantRole(userModel, application.getRole(r)); userModel.grantRole(application.getRole(r));
} }
} }
@ -564,7 +564,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
userEntity.setRealmId(getId()); userEntity.setRealmId(getId());
getMongoStore().insertEntity(userEntity, invocationContext); getMongoStore().insertEntity(userEntity, invocationContext);
return new UserAdapter(userEntity, invocationContext); return new UserAdapter(this, userEntity, invocationContext);
} }
@Override @Override
@ -761,117 +761,6 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
return getMongoStore().removeEntity(MongoApplicationEntity.class, id, invocationContext); return getMongoStore().removeEntity(MongoApplicationEntity.class, id, invocationContext);
} }
@Override
public boolean hasRole(UserModel user, RoleModel role) {
Set<RoleModel> roles = getRoleMappings(user);
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override
public void grantRole(UserModel user, RoleModel role) {
MongoUserEntity userEntity = ((UserAdapter) user).getUser();
getMongoStore().pushItemToList(userEntity, "roleIds", role.getId(), true, invocationContext);
}
@Override
public Set<RoleModel> getRoleMappings(UserModel user) {
Set<RoleModel> result = new HashSet<RoleModel>();
List<MongoRoleEntity> roles = MongoModelUtils.getAllRolesOfUser(user, invocationContext);
for (MongoRoleEntity role : roles) {
if (getId().equals(role.getRealmId())) {
result.add(new RoleAdapter(this, role, this, invocationContext));
} else {
// Likely applicationRole, but we don't have this application yet
result.add(new RoleAdapter(this, role, invocationContext));
}
}
return result;
}
@Override
public Set<RoleModel> getRealmRoleMappings(UserModel user) {
Set<RoleModel> allRoles = getRoleMappings(user);
// Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user?
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allRoles) {
MongoRoleEntity roleEntity = ((RoleAdapter) role).getRole();
if (getId().equals(roleEntity.getRealmId())) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public void deleteRoleMapping(UserModel user, RoleModel role) {
if (user == null || role == null) return;
MongoUserEntity userEntity = ((UserAdapter) user).getUser();
getMongoStore().pullItemFromList(userEntity, "roleIds", role.getId(), invocationContext);
}
@Override
public Set<RoleModel> getScopeMappings(ClientModel client) {
Set<RoleModel> result = new HashSet<RoleModel>();
List<MongoRoleEntity> roles = MongoModelUtils.getAllScopesOfClient(client, invocationContext);
for (MongoRoleEntity role : roles) {
if (getId().equals(role.getRealmId())) {
result.add(new RoleAdapter(this, role, this, invocationContext));
} else {
// Likely applicationRole, but we don't have this application yet
result.add(new RoleAdapter(this, role, invocationContext));
}
}
return result;
}
@Override
public Set<RoleModel> getRealmScopeMappings(ClientModel client) {
Set<RoleModel> allScopes = getScopeMappings(client);
// Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user?
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allScopes) {
MongoRoleEntity roleEntity = ((RoleAdapter) role).getRole();
if (getId().equals(roleEntity.getRealmId())) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public boolean hasScope(ClientModel client, RoleModel role) {
Set<RoleModel> roles = getScopeMappings(client);
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override
public void addScopeMapping(ClientModel client, RoleModel role) {
getMongoStore().pushItemToList(((AbstractMongoAdapter) client).getMongoEntity(), "scopeIds", role.getId(), true, invocationContext);
}
@Override
public void deleteScopeMapping(ClientModel client, RoleModel role) {
getMongoStore().pullItemFromList(((AbstractMongoAdapter) client).getMongoEntity(), "scopeIds", role.getId(), invocationContext);
}
@Override @Override
public OAuthClientModel addOAuthClient(String name) { public OAuthClientModel addOAuthClient(String name) {
return this.addOAuthClient(null, name); return this.addOAuthClient(null, name);
@ -1024,7 +913,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
.and("realmId").is(getId()) .and("realmId").is(getId())
.get(); .get();
MongoUserEntity userEntity = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext); MongoUserEntity userEntity = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext);
return userEntity == null ? null : new UserAdapter(userEntity, invocationContext); return userEntity == null ? null : new UserAdapter(this, userEntity, invocationContext);
} }
@Override @Override
@ -1196,7 +1085,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
protected List<UserModel> convertUserEntities(List<MongoUserEntity> userEntities) { protected List<UserModel> convertUserEntities(List<MongoUserEntity> userEntities) {
List<UserModel> userModels = new ArrayList<UserModel>(); List<UserModel> userModels = new ArrayList<UserModel>();
for (MongoUserEntity user : userEntities) { for (MongoUserEntity user : userEntities) {
userModels.add(new UserAdapter(user, invocationContext)); userModels.add(new UserAdapter(this, user, invocationContext));
} }
return userModels; return userModels;
} }

View file

@ -7,6 +7,7 @@ import java.util.Set;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.QueryBuilder; import com.mongodb.QueryBuilder;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext;
@ -24,13 +25,13 @@ public class RoleAdapter extends AbstractMongoAdapter<MongoRoleEntity> implement
private final MongoRoleEntity role; private final MongoRoleEntity role;
private RoleContainerModel roleContainer; private RoleContainerModel roleContainer;
private RealmAdapter realm; private RealmModel realm;
public RoleAdapter(RealmAdapter realm, MongoRoleEntity roleEntity, MongoStoreInvocationContext invContext) { public RoleAdapter(RealmModel realm, MongoRoleEntity roleEntity, MongoStoreInvocationContext invContext) {
this(realm, roleEntity, null, invContext); this(realm, roleEntity, null, invContext);
} }
public RoleAdapter(RealmAdapter realm, MongoRoleEntity roleEntity, RoleContainerModel roleContainer, MongoStoreInvocationContext invContext) { public RoleAdapter(RealmModel realm, MongoRoleEntity roleEntity, RoleContainerModel roleContainer, MongoStoreInvocationContext invContext) {
super(invContext); super(invContext);
this.role = roleEntity; this.role = roleEntity;
this.roleContainer = roleContainer; this.roleContainer = roleContainer;

View file

@ -1,11 +1,17 @@
package org.keycloak.models.mongo.keycloak.adapters; package org.keycloak.models.mongo.keycloak.adapters;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.entities.CredentialEntity; import org.keycloak.models.entities.CredentialEntity;
import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoUserEntity; import org.keycloak.models.mongo.keycloak.entities.MongoUserEntity;
import org.keycloak.models.mongo.utils.MongoModelUtils;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder; import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import java.util.ArrayList; import java.util.ArrayList;
@ -24,10 +30,12 @@ import java.util.Set;
public class UserAdapter extends AbstractMongoAdapter<MongoUserEntity> implements UserModel { public class UserAdapter extends AbstractMongoAdapter<MongoUserEntity> implements UserModel {
private final MongoUserEntity user; private final MongoUserEntity user;
private final RealmModel realm;
public UserAdapter(MongoUserEntity userEntity, MongoStoreInvocationContext invContext) { public UserAdapter(RealmModel realm, MongoUserEntity userEntity, MongoStoreInvocationContext invContext) {
super(invContext); super(invContext);
this.user = userEntity; this.user = userEntity;
this.realm = realm;
} }
@Override @Override
@ -249,6 +257,80 @@ public class UserAdapter extends AbstractMongoAdapter<MongoUserEntity> implement
return user; return user;
} }
@Override
public boolean hasRole(RoleModel role) {
Set<RoleModel> roles = getRoleMappings();
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override
public void grantRole(RoleModel role) {
getMongoStore().pushItemToList(getUser(), "roleIds", role.getId(), true, invocationContext);
}
@Override
public Set<RoleModel> getRoleMappings() {
Set<RoleModel> result = new HashSet<RoleModel>();
List<MongoRoleEntity> roles = MongoModelUtils.getAllRolesOfUser(this, invocationContext);
for (MongoRoleEntity role : roles) {
if (realm.getId().equals(role.getRealmId())) {
result.add(new RoleAdapter(realm, role, realm, invocationContext));
} else {
// Likely applicationRole, but we don't have this application yet
result.add(new RoleAdapter(realm, role, invocationContext));
}
}
return result;
}
@Override
public Set<RoleModel> getRealmRoleMappings() {
Set<RoleModel> allRoles = getRoleMappings();
// Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user?
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allRoles) {
MongoRoleEntity roleEntity = ((RoleAdapter) role).getRole();
if (realm.getId().equals(roleEntity.getRealmId())) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public void deleteRoleMapping(RoleModel role) {
if (user == null || role == null) return;
getMongoStore().pullItemFromList(getUser(), "roleIds", role.getId(), invocationContext);
}
@Override
public Set<RoleModel> getApplicationRoleMappings(ApplicationModel app) {
Set<RoleModel> result = new HashSet<RoleModel>();
List<MongoRoleEntity> roles = MongoModelUtils.getAllRolesOfUser(this, invocationContext);
for (MongoRoleEntity role : roles) {
if (app.getId().equals(role.getApplicationId())) {
result.add(new RoleAdapter(realm, role, app, invocationContext));
}
}
return result;
}
} }

View file

@ -5,6 +5,7 @@ import com.mongodb.QueryBuilder;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.models.ApplicationModel; import org.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.models.entities.ClientEntity; import org.keycloak.models.entities.ClientEntity;
@ -24,9 +25,9 @@ public class UserSessionAdapter extends AbstractMongoAdapter<MongoUserSessionEnt
private static final Logger logger = Logger.getLogger(RealmAdapter.class); private static final Logger logger = Logger.getLogger(RealmAdapter.class);
private MongoUserSessionEntity entity; private MongoUserSessionEntity entity;
private RealmAdapter realm; private RealmModel realm;
public UserSessionAdapter(MongoUserSessionEntity entity, RealmAdapter realm, MongoStoreInvocationContext invContext) public UserSessionAdapter(MongoUserSessionEntity entity, RealmModel realm, MongoStoreInvocationContext invContext)
{ {
super(invContext); super(invContext);
this.entity = entity; this.entity = entity;

View file

@ -154,11 +154,11 @@ public class AdapterTest extends AbstractModelTest {
user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
RoleModel testRole = realmModel.addRole("test"); RoleModel testRole = realmModel.addRole("test");
realmModel.grantRole(user, testRole); user.grantRole(testRole);
ApplicationModel app = realmModel.addApplication("test-app"); ApplicationModel app = realmModel.addApplication("test-app");
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); user.grantRole(appRole);
SocialLinkModel socialLink = new SocialLinkModel("google", "google1", user.getLoginName()); SocialLinkModel socialLink = new SocialLinkModel("google", "google1", user.getLoginName());
realmModel.addSocialLink(user, socialLink); realmModel.addSocialLink(user, socialLink);
@ -187,11 +187,11 @@ public class AdapterTest extends AbstractModelTest {
ApplicationModel app = realmModel.addApplication("test-app"); ApplicationModel app = realmModel.addApplication("test-app");
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); user.grantRole(appRole);
realmModel.addScopeMapping(client, appRole); client.addScopeMapping(appRole);
RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole = realmModel.addRole("test");
realmModel.addScopeMapping(app, realmRole); app.addScopeMapping(realmRole);
Assert.assertTrue(realmModel.removeApplication(app.getId())); Assert.assertTrue(realmModel.removeApplication(app.getId()));
Assert.assertFalse(realmModel.removeApplication(app.getId())); Assert.assertFalse(realmModel.removeApplication(app.getId()));
@ -215,15 +215,15 @@ public class AdapterTest extends AbstractModelTest {
ApplicationModel app = realmModel.addApplication("test-app"); ApplicationModel app = realmModel.addApplication("test-app");
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); user.grantRole(appRole);
realmModel.addScopeMapping(client, appRole); client.addScopeMapping(appRole);
RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole = realmModel.addRole("test");
RoleModel realmRole2 = realmModel.addRole("test2"); RoleModel realmRole2 = realmModel.addRole("test2");
realmRole.addCompositeRole(realmRole2); realmRole.addCompositeRole(realmRole2);
realmRole.addCompositeRole(appRole); realmRole.addCompositeRole(appRole);
realmModel.addScopeMapping(app, realmRole); app.addScopeMapping(realmRole);
commit(); commit();
realmModel = identitySession.getRealm("JUGGLER"); realmModel = identitySession.getRealm("JUGGLER");
@ -245,11 +245,11 @@ public class AdapterTest extends AbstractModelTest {
ApplicationModel app = realmModel.addApplication("test-app"); ApplicationModel app = realmModel.addApplication("test-app");
RoleModel appRole = app.addRole("test"); RoleModel appRole = app.addRole("test");
realmModel.grantRole(user, appRole); user.grantRole(appRole);
realmModel.addScopeMapping(client, appRole); client.addScopeMapping(appRole);
RoleModel realmRole = realmModel.addRole("test"); RoleModel realmRole = realmModel.addRole("test");
realmModel.addScopeMapping(app, realmRole); app.addScopeMapping(realmRole);
commit(); commit();
realmModel = identitySession.getRealm("JUGGLER"); realmModel = identitySession.getRealm("JUGGLER");
@ -436,8 +436,8 @@ public class AdapterTest extends AbstractModelTest {
Assert.assertEquals(3, roles.size()); Assert.assertEquals(3, roles.size());
UserModel user = realmModel.addUser("bburke"); UserModel user = realmModel.addUser("bburke");
RoleModel realmUserRole = realmModel.getRole("user"); RoleModel realmUserRole = realmModel.getRole("user");
realmModel.grantRole(user, realmUserRole); user.grantRole(realmUserRole);
Assert.assertTrue(realmModel.hasRole(user, realmUserRole)); Assert.assertTrue(user.hasRole(realmUserRole));
RoleModel found = realmModel.getRoleById(realmUserRole.getId()); RoleModel found = realmModel.getRoleById(realmUserRole.getId());
assertNotNull(found); assertNotNull(found);
assertRolesEquals(found, realmUserRole); assertRolesEquals(found, realmUserRole);
@ -455,35 +455,35 @@ public class AdapterTest extends AbstractModelTest {
assertNotNull(found); assertNotNull(found);
assertRolesEquals(found, appBarRole); assertRolesEquals(found, appBarRole);
realmModel.grantRole(user, appBarRole); user.grantRole(appBarRole);
realmModel.grantRole(user, application.getRole("user")); user.grantRole(application.getRole("user"));
roles = realmModel.getRealmRoleMappings(user); roles = user.getRealmRoleMappings();
Assert.assertEquals(roles.size(), 2); Assert.assertEquals(roles.size(), 2);
assertRolesContains(realmUserRole, roles); assertRolesContains(realmUserRole, roles);
Assert.assertTrue(realmModel.hasRole(user, realmUserRole)); Assert.assertTrue(user.hasRole(realmUserRole));
// Role "foo" is default realm role // Role "foo" is default realm role
Assert.assertTrue(realmModel.hasRole(user, realmModel.getRole("foo"))); Assert.assertTrue(user.hasRole(realmModel.getRole("foo")));
roles = application.getApplicationRoleMappings(user); roles = user.getApplicationRoleMappings(application);
Assert.assertEquals(roles.size(), 2); Assert.assertEquals(roles.size(), 2);
assertRolesContains(application.getRole("user"), roles); assertRolesContains(application.getRole("user"), roles);
assertRolesContains(appBarRole, roles); assertRolesContains(appBarRole, roles);
Assert.assertTrue(realmModel.hasRole(user, appBarRole)); Assert.assertTrue(user.hasRole(appBarRole));
// Test that application role 'user' don't clash with realm role 'user' // Test that application role 'user' don't clash with realm role 'user'
Assert.assertNotEquals(realmModel.getRole("user").getId(), application.getRole("user").getId()); Assert.assertNotEquals(realmModel.getRole("user").getId(), application.getRole("user").getId());
Assert.assertEquals(6, realmModel.getRoleMappings(user).size()); Assert.assertEquals(6, user.getRoleMappings().size());
// Revoke some roles // Revoke some roles
realmModel.deleteRoleMapping(user, realmModel.getRole("foo")); user.deleteRoleMapping(realmModel.getRole("foo"));
realmModel.deleteRoleMapping(user, appBarRole); user.deleteRoleMapping(appBarRole);
roles = realmModel.getRoleMappings(user); roles = user.getRoleMappings();
Assert.assertEquals(4, roles.size()); Assert.assertEquals(4, roles.size());
assertRolesContains(realmUserRole, roles); assertRolesContains(realmUserRole, roles);
assertRolesContains(application.getRole("user"), roles); assertRolesContains(application.getRole("user"), roles);
Assert.assertFalse(realmModel.hasRole(user, appBarRole)); Assert.assertFalse(user.hasRole(appBarRole));
} }
@Test @Test
@ -495,12 +495,12 @@ public class AdapterTest extends AbstractModelTest {
RoleModel appRole = app1.addRole("app"); RoleModel appRole = app1.addRole("app");
ApplicationModel app2 = realmModel.addApplication("app2"); ApplicationModel app2 = realmModel.addApplication("app2");
realmModel.addScopeMapping(app2, realmRole); app2.addScopeMapping(realmRole);
realmModel.addScopeMapping(app2, appRole); app2.addScopeMapping(appRole);
OAuthClientModel client = realmModel.addOAuthClient("client"); OAuthClientModel client = realmModel.addOAuthClient("client");
realmModel.addScopeMapping(client, realmRole); client.addScopeMapping(realmRole);
realmModel.addScopeMapping(client, appRole); client.addScopeMapping(appRole);
commit(); commit();
@ -509,12 +509,12 @@ public class AdapterTest extends AbstractModelTest {
app2 = realmModel.getApplicationByName("app2"); app2 = realmModel.getApplicationByName("app2");
client = realmModel.getOAuthClient("client"); client = realmModel.getOAuthClient("client");
Set<RoleModel> scopeMappings = realmModel.getScopeMappings(app2); Set<RoleModel> scopeMappings = app2.getScopeMappings();
Assert.assertEquals(2, scopeMappings.size()); Assert.assertEquals(2, scopeMappings.size());
Assert.assertTrue(scopeMappings.contains(realmModel.getRole("realm"))); Assert.assertTrue(scopeMappings.contains(realmModel.getRole("realm")));
Assert.assertTrue(scopeMappings.contains(app1.getRole("app"))); Assert.assertTrue(scopeMappings.contains(app1.getRole("app")));
scopeMappings = realmModel.getScopeMappings(client); scopeMappings = client.getScopeMappings();
Assert.assertEquals(2, scopeMappings.size()); Assert.assertEquals(2, scopeMappings.size());
Assert.assertTrue(scopeMappings.contains(realmModel.getRole("realm"))); Assert.assertTrue(scopeMappings.contains(realmModel.getRole("realm")));
Assert.assertTrue(scopeMappings.contains(app1.getRole("app"))); Assert.assertTrue(scopeMappings.contains(app1.getRole("app")));

View file

@ -60,8 +60,8 @@ public class CompositeRolesModelTest extends AbstractModelTest {
UserModel user = realm.getUser(username); UserModel user = realm.getUser(username);
ApplicationModel application = realm.getApplicationByName(applicationName); ApplicationModel application = realm.getApplicationByName(applicationName);
Set<RoleModel> roleMappings = realm.getRoleMappings(user); Set<RoleModel> roleMappings = user.getRoleMappings();
Set<RoleModel> scopeMappings = realm.getScopeMappings(application); Set<RoleModel> scopeMappings = application.getScopeMappings();
Set<RoleModel> appRoles = application.getRoles(); Set<RoleModel> appRoles = application.getRoles();
if (appRoles != null) scopeMappings.addAll(appRoles); if (appRoles != null) scopeMappings.addAll(appRoles);

View file

@ -104,7 +104,7 @@ public class ImportTest extends AbstractModelTest {
// Test role mappings // Test role mappings
UserModel admin = realm.getUser("admin"); UserModel admin = realm.getUser("admin");
Set<RoleModel> allRoles = realm.getRoleMappings(admin); Set<RoleModel> allRoles = admin.getRoleMappings();
Assert.assertEquals(5, allRoles.size()); Assert.assertEquals(5, allRoles.size());
Assert.assertTrue(allRoles.contains(realm.getRole("admin"))); Assert.assertTrue(allRoles.contains(realm.getRole("admin")));
Assert.assertTrue(allRoles.contains(application.getRole("app-admin"))); Assert.assertTrue(allRoles.contains(application.getRole("app-admin")));
@ -113,19 +113,19 @@ public class ImportTest extends AbstractModelTest {
Assert.assertTrue(allRoles.contains(accountApp.getRole(AccountRoles.MANAGE_ACCOUNT))); Assert.assertTrue(allRoles.contains(accountApp.getRole(AccountRoles.MANAGE_ACCOUNT)));
UserModel wburke = realm.getUser("wburke"); UserModel wburke = realm.getUser("wburke");
allRoles = realm.getRoleMappings(wburke); allRoles = wburke.getRoleMappings();
Assert.assertEquals(4, allRoles.size()); Assert.assertEquals(4, allRoles.size());
Assert.assertFalse(allRoles.contains(realm.getRole("admin"))); Assert.assertFalse(allRoles.contains(realm.getRole("admin")));
Assert.assertTrue(allRoles.contains(application.getRole("app-user"))); Assert.assertTrue(allRoles.contains(application.getRole("app-user")));
Assert.assertTrue(allRoles.contains(otherApp.getRole("otherapp-user"))); Assert.assertTrue(allRoles.contains(otherApp.getRole("otherapp-user")));
Assert.assertEquals(0, realm.getRealmRoleMappings(wburke).size()); Assert.assertEquals(0, wburke.getRealmRoleMappings().size());
Set<RoleModel> realmRoles = realm.getRealmRoleMappings(admin); Set<RoleModel> realmRoles = admin.getRealmRoleMappings();
Assert.assertEquals(1, realmRoles.size()); Assert.assertEquals(1, realmRoles.size());
Assert.assertEquals("admin", realmRoles.iterator().next().getName()); Assert.assertEquals("admin", realmRoles.iterator().next().getName());
Set<RoleModel> appRoles = application.getApplicationRoleMappings(admin); Set<RoleModel> appRoles = admin.getApplicationRoleMappings(application);
Assert.assertEquals(1, appRoles.size()); Assert.assertEquals(1, appRoles.size());
Assert.assertEquals("app-admin", appRoles.iterator().next().getName()); Assert.assertEquals("app-admin", appRoles.iterator().next().getName());
@ -136,12 +136,12 @@ public class ImportTest extends AbstractModelTest {
Assert.assertNotNull(oauthClient); Assert.assertNotNull(oauthClient);
// Test scope relationship // Test scope relationship
Set<RoleModel> allScopes = realm.getScopeMappings(oauthClient); Set<RoleModel> allScopes = oauthClient.getScopeMappings();
Assert.assertEquals(2, allScopes.size()); Assert.assertEquals(2, allScopes.size());
Assert.assertTrue(allScopes.contains(realm.getRole("admin"))); Assert.assertTrue(allScopes.contains(realm.getRole("admin")));
Assert.assertTrue(allScopes.contains(application.getRole("app-user"))); Assert.assertTrue(allScopes.contains(application.getRole("app-user")));
Set<RoleModel> realmScopes = realm.getRealmScopeMappings(oauthClient); Set<RoleModel> realmScopes = oauthClient.getRealmScopeMappings();
Assert.assertTrue(realmScopes.contains(realm.getRole("admin"))); Assert.assertTrue(realmScopes.contains(realm.getRole("admin")));
Set<RoleModel> appScopes = application.getApplicationScopeMappings(oauthClient); Set<RoleModel> appScopes = application.getApplicationScopeMappings(oauthClient);

View file

@ -97,7 +97,7 @@ public class MultipleRealmsTest extends AbstractModelTest {
realm.addRole("role2"); realm.addRole("role2");
app1.addRole("app1Role1"); app1.addRole("app1Role1");
realm.addScopeMapping(app1, realm.getRole("role1")); app1.addScopeMapping(realm.getRole("role1"));
realm.addOAuthClient("cl1"); realm.addOAuthClient("cl1");
} }

View file

@ -10,8 +10,7 @@
<class>org.keycloak.models.jpa.entities.RealmEntity</class> <class>org.keycloak.models.jpa.entities.RealmEntity</class>
<class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class> <class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class> <class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class> <class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class> <class>org.keycloak.models.jpa.entities.UserEntity</class>

View file

@ -10,8 +10,7 @@
<class>org.keycloak.models.jpa.entities.RealmEntity</class> <class>org.keycloak.models.jpa.entities.RealmEntity</class>
<class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class> <class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class> <class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class> <class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class> <class>org.keycloak.models.jpa.entities.UserEntity</class>

View file

@ -75,11 +75,11 @@ public class ApplianceBootstrap {
adminUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); adminUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
RoleModel adminRole = realm.getRole(AdminRoles.ADMIN); RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
realm.grantRole(adminUser, adminRole); adminUser.grantRole(adminRole);
ApplicationModel accountApp = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APP); ApplicationModel accountApp = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APP);
for (String r : accountApp.getDefaultRoles()) { for (String r : accountApp.getDefaultRoles()) {
realm.grantRole(adminUser, accountApp.getRole(r)); adminUser.grantRole(accountApp.getRole(r));
} }
} }

View file

@ -126,7 +126,7 @@ public class ApplicationManager {
if (role == null) { if (role == null) {
role = applicationModel.addRole(roleString.trim()); role = applicationModel.addRole(roleString.trim());
} }
realm.grantRole(user, role); user.grantRole(role);
} }
} }
} }
@ -139,7 +139,7 @@ public class ApplicationManager {
role = applicationModel.addRole(roleString.trim()); role = applicationModel.addRole(roleString.trim());
} }
ClientModel client = realm.findClient(mapping.getClient()); ClientModel client = realm.findClient(mapping.getClient());
realm.addScopeMapping(client, role); client.addScopeMapping(role);
} }
} }
} }

View file

@ -48,7 +48,7 @@ public class Auth {
public boolean hasRealmRole(String role) { public boolean hasRealmRole(String role) {
if (cookie) { if (cookie) {
return realm.hasRole(user, realm.getRole(role)); return user.hasRole(realm.getRole(role));
} else { } else {
AccessToken.Access access = token.getRealmAccess(); AccessToken.Access access = token.getRealmAccess();
return access != null && access.isUserInRole(role); return access != null && access.isUserInRole(role);
@ -66,7 +66,7 @@ public class Auth {
public boolean hasAppRole(ApplicationModel app, String role) { public boolean hasAppRole(ApplicationModel app, String role) {
if (cookie) { if (cookie) {
return realm.hasRole(user, app.getRole(role)); return user.hasRole(app.getRole(role));
} else { } else {
AccessToken.Access access = token.getResourceAccess(app.getName()); AccessToken.Access access = token.getResourceAccess(app.getName());
return access != null && access.isUserInRole(role); return access != null && access.isUserInRole(role);

View file

@ -119,7 +119,7 @@ public class RealmManager {
ApplicationModel realmAdminApp = realm.getApplicationByName(realmAdminApplicationName); ApplicationModel realmAdminApp = realm.getApplicationByName(realmAdminApplicationName);
adminRole = realmAdminApp.getRole(AdminRoles.REALM_ADMIN); adminRole = realmAdminApp.getRole(AdminRoles.REALM_ADMIN);
} }
realm.addScopeMapping(adminConsole, adminRole); adminConsole.addScopeMapping(adminRole);
} }
public String getMasterRealmAdminApplicationName(RealmModel realm) { public String getMasterRealmAdminApplicationName(RealmModel realm) {
@ -463,7 +463,7 @@ public class RealmManager {
if (role == null) { if (role == null) {
role = newRealm.addRole(roleString.trim()); role = newRealm.addRole(roleString.trim());
} }
newRealm.grantRole(user, role); user.grantRole(role);
} }
} }
} }
@ -476,7 +476,7 @@ public class RealmManager {
role = newRealm.addRole(roleString.trim()); role = newRealm.addRole(roleString.trim());
} }
ClientModel client = newRealm.findClient(scope.getClient()); ClientModel client = newRealm.findClient(scope.getClient());
newRealm.addScopeMapping(client, role); client.addScopeMapping(role);
} }
} }

View file

@ -161,10 +161,10 @@ public class TokenManager {
if (role == null) { if (role == null) {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid realm role " + roleName); throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid realm role " + roleName);
} }
if (!realm.hasRole(user, role)) { if (!user.hasRole(role)) {
throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for realm role: " + roleName); throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for realm role: " + roleName);
} }
if (!realm.hasScope(client, role)) { if (!client.hasScope(role)) {
throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has realm scope: " + roleName); throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has realm scope: " + roleName);
} }
} }
@ -180,10 +180,10 @@ public class TokenManager {
if (role == null) { if (role == null) {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown application role: " + roleName); throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown application role: " + roleName);
} }
if (!realm.hasRole(user, role)) { if (!user.hasRole(role)) {
throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for application role " + roleName); throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "User no long has permission for application role " + roleName);
} }
if (clientApp != null && !clientApp.equals(app) && !realm.hasScope(client, role)) { if (clientApp != null && !clientApp.equals(app) && !client.hasScope(role)) {
throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has application scope" + roleName); throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has application scope" + roleName);
} }
} }
@ -210,8 +210,8 @@ public class TokenManager {
public AccessToken createClientAccessToken(String scopeParam, RealmModel realm, ClientModel client, UserModel user, UserSessionModel session, List<RoleModel> realmRolesRequested, MultivaluedMap<String, RoleModel> resourceRolesRequested) { public AccessToken createClientAccessToken(String scopeParam, RealmModel realm, ClientModel client, UserModel user, UserSessionModel session, List<RoleModel> realmRolesRequested, MultivaluedMap<String, RoleModel> resourceRolesRequested) {
// todo scopeParam is ignored until we figure out a scheme that fits with openid connect // todo scopeParam is ignored until we figure out a scheme that fits with openid connect
Set<RoleModel> roleMappings = realm.getRoleMappings(user); Set<RoleModel> roleMappings = user.getRoleMappings();
Set<RoleModel> scopeMappings = realm.getScopeMappings(client); Set<RoleModel> scopeMappings = client.getScopeMappings();
ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null; ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null;
Set<RoleModel> clientAppRoles = clientApp == null ? null : clientApp.getRoles(); Set<RoleModel> clientAppRoles = clientApp == null ? null : clientApp.getRoles();
if (clientAppRoles != null) scopeMappings.addAll(clientAppRoles); if (clientAppRoles != null) scopeMappings.addAll(clientAppRoles);

View file

@ -210,7 +210,7 @@ public class SocialResource {
return oauth.forwardToSecurityFailure("User is disabled"); return oauth.forwardToSecurityFailure("User is disabled");
} }
if (!realm.hasRole(authenticatedUser, realm.getApplicationByName(Constants.ACCOUNT_MANAGEMENT_APP).getRole(AccountRoles.MANAGE_ACCOUNT))) { if (!authenticatedUser.hasRole(realm.getApplicationByName(Constants.ACCOUNT_MANAGEMENT_APP).getRole(AccountRoles.MANAGE_ACCOUNT))) {
audit.error(Errors.NOT_ALLOWED); audit.error(Errors.NOT_ALLOWED);
return oauth.forwardToSecurityFailure("Insufficient permissions to link social account"); return oauth.forwardToSecurityFailure("Insufficient permissions to link social account");
} }

View file

@ -45,7 +45,7 @@ public class AdminAuth {
public boolean hasRealmRole(String role) { public boolean hasRealmRole(String role) {
if (client instanceof ApplicationModel) { if (client instanceof ApplicationModel) {
RoleModel roleModel = realm.getRole(role); RoleModel roleModel = realm.getRole(role);
return realm.hasRole(user, roleModel) && realm.hasScope(client, roleModel); return user.hasRole(roleModel) && client.hasScope(roleModel);
} else { } else {
AccessToken.Access access = token.getRealmAccess(); AccessToken.Access access = token.getRealmAccess();
return access != null && access.isUserInRole(role); return access != null && access.isUserInRole(role);
@ -64,7 +64,7 @@ public class AdminAuth {
public boolean hasAppRole(ApplicationModel app, String role) { public boolean hasAppRole(ApplicationModel app, String role) {
if (client instanceof ApplicationModel) { if (client instanceof ApplicationModel) {
RoleModel roleModel = app.getRole(role); RoleModel roleModel = app.getRole(role);
return realm.hasRole(user, roleModel) && realm.hasScope(client, roleModel); return user.hasRole(roleModel) && client.hasScope(roleModel);
} else { } else {
AccessToken.Access access = token.getResourceAccess(app.getName()); AccessToken.Access access = token.getResourceAccess(app.getName());
return access != null && access.isUserInRole(role); return access != null && access.isUserInRole(role);

View file

@ -200,7 +200,7 @@ public class AdminConsole {
boolean createRealm = false; boolean createRealm = false;
if (realm.equals(masterRealm)) { if (realm.equals(masterRealm)) {
logger.info("setting up realm access for a master realm user"); logger.info("setting up realm access for a master realm user");
createRealm = masterRealm.hasRole(user, masterRealm.getRole(AdminRoles.CREATE_REALM)); createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM));
addMasterRealmAccess(realm, user, realmAccess); addMasterRealmAccess(realm, user, realmAccess);
} else { } else {
logger.info("setting up realm access for a realm user"); logger.info("setting up realm access for a realm user");
@ -219,7 +219,7 @@ public class AdminConsole {
ApplicationModel realmAdminApp = realm.getApplicationByName(realmManager.getRealmAdminApplicationName(realm)); ApplicationModel realmAdminApp = realm.getApplicationByName(realmManager.getRealmAdminApplicationName(realm));
Set<RoleModel> roles = realmAdminApp.getRoles(); Set<RoleModel> roles = realmAdminApp.getRoles();
for (RoleModel role : roles) { for (RoleModel role : roles) {
if (!realm.hasRole(user, role)) continue; if (!user.hasRole(role)) continue;
if (!realmAdminAccess.containsKey(realm.getName())) { if (!realmAdminAccess.containsKey(realm.getName())) {
realmAdminAccess.put(realm.getName(), new HashSet<String>()); realmAdminAccess.put(realm.getName(), new HashSet<String>());
} }
@ -234,7 +234,7 @@ public class AdminConsole {
ApplicationModel realmAdminApp = realm.getMasterAdminApp(); ApplicationModel realmAdminApp = realm.getMasterAdminApp();
Set<RoleModel> roles = realmAdminApp.getRoles(); Set<RoleModel> roles = realmAdminApp.getRoles();
for (RoleModel role : roles) { for (RoleModel role : roles) {
if (!masterRealm.hasRole(user, role)) continue; if (!user.hasRole(role)) continue;
if (!realmAdminAccess.containsKey(realm.getName())) { if (!realmAdminAccess.containsKey(realm.getName())) {
realmAdminAccess.put(realm.getName(), new HashSet<String>()); realmAdminAccess.put(realm.getName(), new HashSet<String>());
} }

View file

@ -198,7 +198,7 @@ public class RealmsAdminResource {
ApplicationModel realmAdminApp = realm.getMasterAdminApp(); ApplicationModel realmAdminApp = realm.getMasterAdminApp();
for (String r : AdminRoles.ALL_REALM_ROLES) { for (String r : AdminRoles.ALL_REALM_ROLES) {
RoleModel role = realmAdminApp.getRole(r); RoleModel role = realmAdminApp.getRole(r);
adminRealm.grantRole(auth.getUser(), role); auth.getUser().grantRole(role);
} }
} }

View file

@ -58,7 +58,7 @@ public class ScopeMappedResource {
auth.requireView(); auth.requireView();
MappingsRepresentation all = new MappingsRepresentation(); MappingsRepresentation all = new MappingsRepresentation();
Set<RoleModel> realmMappings = realm.getRealmScopeMappings(client); Set<RoleModel> realmMappings = client.getRealmScopeMappings();
if (realmMappings.size() > 0) { if (realmMappings.size() > 0) {
List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : realmMappings) { for (RoleModel roleModel : realmMappings) {
@ -101,7 +101,7 @@ public class ScopeMappedResource {
public List<RoleRepresentation> getRealmScopeMappings() { public List<RoleRepresentation> getRealmScopeMappings() {
auth.requireView(); auth.requireView();
Set<RoleModel> realmMappings = realm.getRealmScopeMappings(client); Set<RoleModel> realmMappings = client.getRealmScopeMappings();
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : realmMappings) { for (RoleModel roleModel : realmMappings) {
realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel)); realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -128,7 +128,7 @@ public class ScopeMappedResource {
private List<RoleRepresentation> getAvailable(Set<RoleModel> roles) { private List<RoleRepresentation> getAvailable(Set<RoleModel> roles) {
List<RoleRepresentation> available = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> available = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : roles) { for (RoleModel roleModel : roles) {
if (realm.hasScope(client, roleModel)) continue; if (client.hasScope(roleModel)) continue;
available.add(ModelToRepresentation.toRepresentation(roleModel)); available.add(ModelToRepresentation.toRepresentation(roleModel));
} }
return available; return available;
@ -155,7 +155,7 @@ public class ScopeMappedResource {
private List<RoleRepresentation> getComposite(Set<RoleModel> roles) { private List<RoleRepresentation> getComposite(Set<RoleModel> roles) {
List<RoleRepresentation> composite = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> composite = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : roles) { for (RoleModel roleModel : roles) {
if (realm.hasScope(client, roleModel)) composite.add(ModelToRepresentation.toRepresentation(roleModel)); if (client.hasScope(roleModel)) composite.add(ModelToRepresentation.toRepresentation(roleModel));
} }
return composite; return composite;
} }
@ -176,7 +176,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.addScopeMapping(client, roleModel); client.addScopeMapping(roleModel);
} }
@ -194,9 +194,9 @@ public class ScopeMappedResource {
auth.requireManage(); auth.requireManage();
if (roles == null) { if (roles == null) {
Set<RoleModel> roleModels = realm.getRealmScopeMappings(client); Set<RoleModel> roleModels = client.getRealmScopeMappings();
for (RoleModel roleModel : roleModels) { for (RoleModel roleModel : roleModels) {
realm.deleteScopeMapping(client, roleModel); client.deleteScopeMapping(roleModel);
} }
} else { } else {
@ -205,7 +205,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.deleteScopeMapping(client, roleModel); client.deleteScopeMapping(roleModel);
} }
} }
} }
@ -306,7 +306,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.addScopeMapping(client, roleModel); client.addScopeMapping(roleModel);
} }
} }
@ -332,7 +332,7 @@ public class ScopeMappedResource {
if (roles == null) { if (roles == null) {
Set<RoleModel> roleModels = app.getApplicationScopeMappings(client); Set<RoleModel> roleModels = app.getApplicationScopeMappings(client);
for (RoleModel roleModel : roleModels) { for (RoleModel roleModel : roleModels) {
realm.deleteScopeMapping(client, roleModel); client.deleteScopeMapping(roleModel);
} }
} else { } else {
@ -341,7 +341,7 @@ public class ScopeMappedResource {
if (roleModel == null) { if (roleModel == null) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.deleteScopeMapping(client, roleModel); client.deleteScopeMapping(roleModel);
} }
} }
} }

View file

@ -376,7 +376,7 @@ public class UsersResource {
} }
MappingsRepresentation all = new MappingsRepresentation(); MappingsRepresentation all = new MappingsRepresentation();
Set<RoleModel> realmMappings = realm.getRoleMappings(user); Set<RoleModel> realmMappings = user.getRoleMappings();
RealmManager manager = new RealmManager(session); RealmManager manager = new RealmManager(session);
if (realmMappings.size() > 0) { if (realmMappings.size() > 0) {
List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>();
@ -390,7 +390,7 @@ public class UsersResource {
if (applications.size() > 0) { if (applications.size() > 0) {
Map<String, ApplicationMappingsRepresentation> appMappings = new HashMap<String, ApplicationMappingsRepresentation>(); Map<String, ApplicationMappingsRepresentation> appMappings = new HashMap<String, ApplicationMappingsRepresentation>();
for (ApplicationModel application : applications) { for (ApplicationModel application : applications) {
Set<RoleModel> roleMappings = application.getApplicationRoleMappings(user); Set<RoleModel> roleMappings = user.getApplicationRoleMappings(application);
if (roleMappings.size() > 0) { if (roleMappings.size() > 0) {
ApplicationMappingsRepresentation mappings = new ApplicationMappingsRepresentation(); ApplicationMappingsRepresentation mappings = new ApplicationMappingsRepresentation();
mappings.setApplicationId(application.getId()); mappings.setApplicationId(application.getId());
@ -426,7 +426,7 @@ public class UsersResource {
throw new NotFoundException("User not found"); throw new NotFoundException("User not found");
} }
Set<RoleModel> realmMappings = realm.getRealmRoleMappings(user); Set<RoleModel> realmMappings = user.getRealmRoleMappings();
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : realmMappings) { for (RoleModel roleModel : realmMappings) {
realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel)); realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -455,7 +455,7 @@ public class UsersResource {
Set<RoleModel> roles = realm.getRoles(); Set<RoleModel> roles = realm.getRoles();
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : roles) { for (RoleModel roleModel : roles) {
if (realm.hasRole(user, roleModel)) { if (user.hasRole(roleModel)) {
realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel)); realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel));
} }
} }
@ -507,7 +507,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) { if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.grantRole(user, roleModel); user.grantRole(roleModel);
} }
@ -532,9 +532,9 @@ public class UsersResource {
} }
if (roles == null) { if (roles == null) {
Set<RoleModel> roleModels = realm.getRealmRoleMappings(user); Set<RoleModel> roleModels = user.getRealmRoleMappings();
for (RoleModel roleModel : roleModels) { for (RoleModel roleModel : roleModels) {
realm.deleteRoleMapping(user, roleModel); user.deleteRoleMapping(roleModel);
} }
} else { } else {
@ -543,7 +543,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) { if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.deleteRoleMapping(user, roleModel); user.deleteRoleMapping(roleModel);
} }
} }
} }
@ -575,7 +575,7 @@ public class UsersResource {
throw new NotFoundException("Application not found"); throw new NotFoundException("Application not found");
} }
Set<RoleModel> mappings = application.getApplicationRoleMappings(user); Set<RoleModel> mappings = user.getApplicationRoleMappings(application);
List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : mappings) { for (RoleModel roleModel : mappings) {
mapRep.add(ModelToRepresentation.toRepresentation(roleModel)); mapRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -614,7 +614,7 @@ public class UsersResource {
Set<RoleModel> roles = application.getRoles(); Set<RoleModel> roles = application.getRoles();
List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>(); List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : roles) { for (RoleModel roleModel : roles) {
if (realm.hasRole(user, roleModel)) mapRep.add(ModelToRepresentation.toRepresentation(roleModel)); if (user.hasRole(roleModel)) mapRep.add(ModelToRepresentation.toRepresentation(roleModel));
} }
logger.debugv("getCompositeApplicationRoleMappings.size() = {0}", mapRep.size()); logger.debugv("getCompositeApplicationRoleMappings.size() = {0}", mapRep.size());
return mapRep; return mapRep;
@ -653,7 +653,7 @@ public class UsersResource {
protected List<RoleRepresentation> getAvailableRoles(UserModel user, Set<RoleModel> available) { protected List<RoleRepresentation> getAvailableRoles(UserModel user, Set<RoleModel> available) {
Set<RoleModel> roles = new HashSet<RoleModel>(); Set<RoleModel> roles = new HashSet<RoleModel>();
for (RoleModel roleModel : available) { for (RoleModel roleModel : available) {
if (realm.hasRole(user, roleModel)) continue; if (user.hasRole(roleModel)) continue;
roles.add(roleModel); roles.add(roleModel);
} }
@ -694,7 +694,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) { if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.grantRole(user, roleModel); user.grantRole(roleModel);
} }
} }
@ -724,13 +724,13 @@ public class UsersResource {
} }
if (roles == null) { if (roles == null) {
Set<RoleModel> roleModels = application.getApplicationRoleMappings(user); Set<RoleModel> roleModels = user.getApplicationRoleMappings(application);
for (RoleModel roleModel : roleModels) { for (RoleModel roleModel : roleModels) {
if (!(roleModel.getContainer() instanceof ApplicationModel)) { if (!(roleModel.getContainer() instanceof ApplicationModel)) {
ApplicationModel app = (ApplicationModel) roleModel.getContainer(); ApplicationModel app = (ApplicationModel) roleModel.getContainer();
if (!app.getId().equals(application.getId())) continue; if (!app.getId().equals(application.getId())) continue;
} }
realm.deleteRoleMapping(user, roleModel); user.deleteRoleMapping(roleModel);
} }
} else { } else {
@ -739,7 +739,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) { if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found"); throw new NotFoundException("Role not found");
} }
realm.deleteRoleMapping(user, roleModel); user.deleteRoleMapping(roleModel);
} }
} }
} }

View file

@ -11,8 +11,7 @@
<class>org.keycloak.models.jpa.entities.RealmEntity</class> <class>org.keycloak.models.jpa.entities.RealmEntity</class>
<class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class> <class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class> <class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class> <class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class> <class>org.keycloak.models.jpa.entities.UserEntity</class>

View file

@ -82,7 +82,7 @@ public class AccountTest {
UserModel user2 = appRealm.addUser("test-user-no-access@localhost"); UserModel user2 = appRealm.addUser("test-user-no-access@localhost");
user2.setEnabled(true); user2.setEnabled(true);
for (String r : accountApp.getDefaultRoles()) { for (String r : accountApp.getDefaultRoles()) {
appRealm.deleteRoleMapping(user2, accountApp.getRole(r)); user2.deleteRoleMapping(accountApp.getRole(r));
} }
UserCredentialModel creds = new UserCredentialModel(); UserCredentialModel creds = new UserCredentialModel();
creds.setType(CredentialRepresentation.PASSWORD); creds.setType(CredentialRepresentation.PASSWORD);

View file

@ -59,7 +59,7 @@ public class ProfileTest {
UserModel user2 = appRealm.addUser("test-user-no-access@localhost"); UserModel user2 = appRealm.addUser("test-user-no-access@localhost");
user2.setEnabled(true); user2.setEnabled(true);
for (String r : accountApp.getDefaultRoles()) { for (String r : accountApp.getDefaultRoles()) {
appRealm.deleteRoleMapping(user2, accountApp.getRole(r)); user2.deleteRoleMapping(accountApp.getRole(r));
} }
UserCredentialModel creds = new UserCredentialModel(); UserCredentialModel creds = new UserCredentialModel();
creds.setType(CredentialRepresentation.PASSWORD); creds.setType(CredentialRepresentation.PASSWORD);
@ -67,12 +67,12 @@ public class ProfileTest {
user2.updateCredential(creds); user2.updateCredential(creds);
ApplicationModel app = appRealm.getApplicationNameMap().get("test-app"); ApplicationModel app = appRealm.getApplicationNameMap().get("test-app");
appRealm.addScopeMapping(app, accountApp.getRole(AccountRoles.VIEW_PROFILE)); app.addScopeMapping(accountApp.getRole(AccountRoles.VIEW_PROFILE));
app.addRedirectUri("http://localhost:8081/app/*"); app.addRedirectUri("http://localhost:8081/app/*");
app.addWebOrigin("http://localtest.me:8081"); app.addWebOrigin("http://localtest.me:8081");
ClientModel thirdParty = appRealm.findClient("third-party"); ClientModel thirdParty = appRealm.findClient("third-party");
appRealm.addScopeMapping(thirdParty, accountApp.getRole(AccountRoles.VIEW_PROFILE)); thirdParty.addScopeMapping(accountApp.getRole(AccountRoles.VIEW_PROFILE));
} }
}); });

View file

@ -78,16 +78,16 @@ public class CompositeRoleTest {
final UserModel realmComposite1User = realm.addUser("REALM_COMPOSITE_1_USER"); final UserModel realmComposite1User = realm.addUser("REALM_COMPOSITE_1_USER");
realmComposite1User.setEnabled(true); realmComposite1User.setEnabled(true);
realmComposite1User.updateCredential(UserCredentialModel.password("password")); realmComposite1User.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmComposite1User, realmComposite1); realmComposite1User.grantRole(realmComposite1);
final UserModel realmRole1User = realm.addUser("REALM_ROLE_1_USER"); final UserModel realmRole1User = realm.addUser("REALM_ROLE_1_USER");
realmRole1User.setEnabled(true); realmRole1User.setEnabled(true);
realmRole1User.updateCredential(UserCredentialModel.password("password")); realmRole1User.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmRole1User, realmRole1); realmRole1User.grantRole(realmRole1);
final ApplicationModel realmComposite1Application = new ApplicationManager(manager).createApplication(realm, "REALM_COMPOSITE_1_APPLICATION"); final ApplicationModel realmComposite1Application = new ApplicationManager(manager).createApplication(realm, "REALM_COMPOSITE_1_APPLICATION");
realmComposite1Application.setEnabled(true); realmComposite1Application.setEnabled(true);
realm.addScopeMapping(realmComposite1Application, realmComposite1); realmComposite1Application.addScopeMapping(realmComposite1);
realmComposite1Application.addRedirectUri("http://localhost:8081/app/*"); realmComposite1Application.addRedirectUri("http://localhost:8081/app/*");
realmComposite1Application.setBaseUrl("http://localhost:8081/app"); realmComposite1Application.setBaseUrl("http://localhost:8081/app");
realmComposite1Application.setManagementUrl("http://localhost:8081/app/logout"); realmComposite1Application.setManagementUrl("http://localhost:8081/app/logout");
@ -95,7 +95,7 @@ public class CompositeRoleTest {
final ApplicationModel realmRole1Application = new ApplicationManager(manager).createApplication(realm, "REALM_ROLE_1_APPLICATION"); final ApplicationModel realmRole1Application = new ApplicationManager(manager).createApplication(realm, "REALM_ROLE_1_APPLICATION");
realmRole1Application.setEnabled(true); realmRole1Application.setEnabled(true);
realm.addScopeMapping(realmRole1Application, realmRole1); realmRole1Application.addScopeMapping(realmRole1);
realmRole1Application.addRedirectUri("http://localhost:8081/app/*"); realmRole1Application.addRedirectUri("http://localhost:8081/app/*");
realmRole1Application.setBaseUrl("http://localhost:8081/app"); realmRole1Application.setBaseUrl("http://localhost:8081/app");
realmRole1Application.setManagementUrl("http://localhost:8081/app/logout"); realmRole1Application.setManagementUrl("http://localhost:8081/app/logout");
@ -117,12 +117,12 @@ public class CompositeRoleTest {
final UserModel realmAppCompositeUser = realm.addUser("REALM_APP_COMPOSITE_USER"); final UserModel realmAppCompositeUser = realm.addUser("REALM_APP_COMPOSITE_USER");
realmAppCompositeUser.setEnabled(true); realmAppCompositeUser.setEnabled(true);
realmAppCompositeUser.updateCredential(UserCredentialModel.password("password")); realmAppCompositeUser.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmAppCompositeUser, realmAppCompositeRole); realmAppCompositeUser.grantRole(realmAppCompositeRole);
final UserModel realmAppRoleUser = realm.addUser("REALM_APP_ROLE_USER"); final UserModel realmAppRoleUser = realm.addUser("REALM_APP_ROLE_USER");
realmAppRoleUser.setEnabled(true); realmAppRoleUser.setEnabled(true);
realmAppRoleUser.updateCredential(UserCredentialModel.password("password")); realmAppRoleUser.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmAppRoleUser, appRole2); realmAppRoleUser.grantRole(appRole2);
final ApplicationModel appCompositeApplication = new ApplicationManager(manager).createApplication(realm, "APP_COMPOSITE_APPLICATION"); final ApplicationModel appCompositeApplication = new ApplicationManager(manager).createApplication(realm, "APP_COMPOSITE_APPLICATION");
appCompositeApplication.setEnabled(true); appCompositeApplication.setEnabled(true);
@ -131,7 +131,7 @@ public class CompositeRoleTest {
appCompositeApplication.setManagementUrl("http://localhost:8081/app/logout"); appCompositeApplication.setManagementUrl("http://localhost:8081/app/logout");
appCompositeApplication.setSecret("password"); appCompositeApplication.setSecret("password");
final RoleModel appCompositeRole = appCompositeApplication.addRole("APP_COMPOSITE_ROLE"); final RoleModel appCompositeRole = appCompositeApplication.addRole("APP_COMPOSITE_ROLE");
realm.addScopeMapping(appCompositeApplication, appRole2); appCompositeApplication.addScopeMapping(appRole2);
appCompositeRole.addCompositeRole(realmRole1); appCompositeRole.addCompositeRole(realmRole1);
appCompositeRole.addCompositeRole(realmRole2); appCompositeRole.addCompositeRole(realmRole2);
appCompositeRole.addCompositeRole(realmRole3); appCompositeRole.addCompositeRole(realmRole3);
@ -140,8 +140,8 @@ public class CompositeRoleTest {
final UserModel appCompositeUser = realm.addUser("APP_COMPOSITE_USER"); final UserModel appCompositeUser = realm.addUser("APP_COMPOSITE_USER");
appCompositeUser.setEnabled(true); appCompositeUser.setEnabled(true);
appCompositeUser.updateCredential(UserCredentialModel.password("password")); appCompositeUser.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(appCompositeUser, realmAppCompositeRole); appCompositeUser.grantRole(realmAppCompositeRole);
realm.grantRole(appCompositeUser, realmComposite1); appCompositeUser.grantRole(realmComposite1);
deployServlet("app", "/app", ApplicationServlet.class); deployServlet("app", "/app", ApplicationServlet.class);

View file

@ -91,13 +91,13 @@ public class ReadUsersWorker implements Worker {
// Read roles of user in realm // Read roles of user in realm
if (readRoles) { if (readRoles) {
realm.getRoleMappings(user); user.getRoleMappings();
} }
// Read scopes of user in realm // Read scopes of user in realm
if (readScopes) { if (readScopes) {
ClientModel client = realm.findClient(username); ClientModel client = realm.findClient(username);
realm.getScopeMappings(client); client.getScopeMappings();
} }
// Validate password (shoould be same as username) // Validate password (shoould be same as username)

View file

@ -11,8 +11,7 @@
<class>org.keycloak.models.jpa.entities.RealmEntity</class> <class>org.keycloak.models.jpa.entities.RealmEntity</class>
<class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class> <class>org.keycloak.models.jpa.entities.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class> <class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class> <class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class> <class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class> <class>org.keycloak.models.jpa.entities.UserEntity</class>