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

View file

@ -207,7 +207,7 @@ public class ModelImporter {
private void addScopes(RealmModel realm, ClientModel client, ClientEntity clientEntity) {
for (String scopeId : clientEntity.getScopeIds()) {
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());
// 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)) {
realm.deleteRoleMapping(user, role);
for (RoleModel role : user.getRoleMappings()) {
user.deleteRoleMapping(role);
}
this.propertiesManager.setBasicPropertiesToModel(user, userEntity);
@ -291,7 +291,7 @@ public class ModelImporter {
if (userEntity.getRoleIds() != null) {
for (String roleId : userEntity.getRoleIds()) {
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);
Set<RoleModel> getApplicationRoleMappings(UserModel user);
Set<RoleModel> getApplicationScopeMappings(ClientModel client);
boolean isBearerOnly();

View file

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

View file

@ -3,6 +3,8 @@ package org.keycloak.models;
import org.keycloak.provider.Provider;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @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 getRealm(String id);
RealmModel getRealmByName(String name);
UserModel getUserById(String id, String realmId);
UserModel getUserByUsername(String username, String realmId);
UserModel getUserByEmail(String email, String realmId);
UserModel getUserById(String id, RealmModel realm);
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();
boolean removeRealm(String id);

View file

@ -10,7 +10,7 @@ import java.util.Set;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMapperModel {
public interface RealmModel extends RoleContainerModel {
String getId();
@ -205,10 +205,6 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
void setAuthenticationProviders(List<AuthenticationProviderModel> authenticationProviders);
Set<RoleModel> getRealmRoleMappings(UserModel user);
Set<RoleModel> getRealmScopeMappings(ClientModel client);
String getLoginTheme();
void setLoginTheme(String name);
@ -225,7 +221,6 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
void setEmailTheme(String name);
boolean hasScope(ClientModel client, RoleModel role);
/**
* 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 $
*/
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);
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;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SocialLinkModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.cache.entities.CachedRealm;
import org.keycloak.models.cache.entities.CachedRole;
import org.keycloak.provider.ProviderSession;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
@ -116,7 +123,7 @@ public class CacheKeycloakSession implements KeycloakSession {
if (cached == null) {
RealmModel model = getDelegate().getRealm(id);
if (model == null) return null;
cached = new CachedRealm(model);
cached = new CachedRealm(cache, this, model);
}
return new RealmAdapter(cached, this);
}
@ -127,23 +134,23 @@ public class CacheKeycloakSession implements KeycloakSession {
if (cached == null) {
RealmModel model = getDelegate().getRealmByName(name);
if (model == null) return null;
cached = new CachedRealm(model);
cached = new CachedRealm(cache, this, model);
}
return new RealmAdapter(cached, this);
}
@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.
}
@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.
}
@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.
}
@ -173,4 +180,59 @@ public class CacheKeycloakSession implements KeycloakSession {
public void 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;
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.CachedRole;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface KeycloakCache {
void clear();
CachedRealm getCachedRealm(String id);
void invalidateCachedRealm(CachedRealm realm);
@ -15,7 +20,31 @@ public interface KeycloakCache {
CachedRealm getCachedRealmByName(String name);
void clear();
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.UserSessionModel;
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.CachedRealmRole;
import org.keycloak.models.cache.entities.CachedRole;
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.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -34,6 +40,7 @@ public class RealmAdapter implements RealmModel {
protected CachedRealm cached;
protected CacheKeycloakSession cacheSession;
protected RealmModel updated;
protected KeycloakCache cache;
protected volatile transient PublicKey publicKey;
protected volatile transient PrivateKey privateKey;
@ -62,7 +69,7 @@ public class RealmAdapter implements RealmModel {
protected void getDelegateForUpdate() {
if (updated == null) {
updated = cacheSession.getRealm(getId());
updated = cacheSession.getDelegate().getRealm(getId());
if (updated == null) throw new IllegalStateException("Not found in database");
}
}
@ -376,272 +383,352 @@ public class RealmAdapter implements RealmModel {
@Override
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
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
public UserModel getUser(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates.
return cacheSession.getUserByUsername(name, this);
}
@Override
public UserModel getUserByEmail(String email) {
return null; //To change body of implemented methods use File | Settings | File Templates.
return cacheSession.getUserByEmail(email, this);
}
@Override
public UserModel getUserById(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates.
public UserModel getUserById(String id) {
return cacheSession.getUserById(id, this);
}
@Override
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
public UserModel addUser(String username) {
return null; //To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
return updated.addUser(username);
}
@Override
public boolean removeUser(String name) {
return false; //To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
return updated.removeUser(name);
}
@Override
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
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
public void addDefaultRole(String name) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.addDefaultRole(name);
}
@Override
public void updateDefaultRoles(String[] defaultRoles) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.updateDefaultRoles(defaultRoles);
}
@Override
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
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
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
public ApplicationModel addApplication(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
return updated.addApplication(name);
}
@Override
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
public boolean removeApplication(String id) {
return false; //To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
return updated.removeApplication(id);
}
@Override
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
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
public void updateRequiredCredentials(Set<String> creds) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.updateRequiredCredentials(creds);
}
@Override
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
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
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
public void addSocialLink(UserModel user, SocialLinkModel socialLink) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.addSocialLink(user, socialLink);
}
@Override
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
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
public void setAuthenticationLink(UserModel user, AuthenticationLinkModel authenticationLink) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.setAuthenticationLink(user, authenticationLink);
}
@Override
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
public void setSocial(boolean social) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.setSocial(social);
}
@Override
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
public void setUpdateProfileOnInitialSocialLogin(boolean updateProfileOnInitialSocialLogin) {
//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.
getDelegateForUpdate();
updated.setUpdateProfileOnInitialSocialLogin(updateProfileOnInitialSocialLogin);
}
@Override
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
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
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
public OAuthClientModel addOAuthClient(String name) {
return null; //To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
return updated.addOAuthClient(name);
}
@Override
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
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
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
public boolean removeOAuthClient(String id) {
return false; //To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
return updated.removeOAuthClient(id);
}
@Override
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
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
public void setSmtpConfig(Map<String, String> smtpConfig) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.setSmtpConfig(smtpConfig);
}
@Override
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
public void setSocialConfig(Map<String, String> socialConfig) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.setSocialConfig(socialConfig);
}
@Override
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
public void setLdapServerConfig(Map<String, String> ldapServerConfig) {
//To change body of implemented methods use File | Settings | File Templates.
getDelegateForUpdate();
updated.setLdapServerConfig(ldapServerConfig);
}
@Override
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
public void setAuthenticationProviders(List<AuthenticationProviderModel> authenticationProviders) {
//To change body of implemented methods use File | Settings | File Templates.
}
@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.
getDelegateForUpdate();
updated.setAuthenticationProviders(authenticationProviders);
}
@Override
@ -684,11 +771,6 @@ public class RealmAdapter implements RealmModel {
//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
public int getNotBefore() {
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.
}
@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
public UserSessionModel createUserSession(UserModel user, String ipAddress) {
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.
}
@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.KeycloakTransaction;
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.CachedRole;
import org.keycloak.provider.ProviderSession;
import org.keycloak.provider.ProviderSessionFactory;
@ -56,4 +59,64 @@ public class SimpleCache implements KeycloakCache {
public CachedRealm getCachedRealmByName(String 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;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.AuthenticationProviderModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SocialLinkModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.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 org.keycloak.models.cache.KeycloakCache;
import java.io.Serializable;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -81,11 +71,16 @@ public class CachedRealm {
private boolean auditEnabled;
private long auditExpiration;
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(RealmModel model) {
public CachedRealm(KeycloakCache cache, KeycloakSession delegate, RealmModel model) {
id = model.getId();
name = model.getName();
enabled = model.isEnabled();
@ -133,6 +128,30 @@ public class CachedRealm {
auditEnabled = model.isAuditEnabled();
auditExpiration = model.getAuditExpiration();
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;
}
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() {
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.ClientModel;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
@ -100,10 +101,10 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
@Override
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("application", entity);
List<ApplicationRoleEntity> roles = query.getResultList();
List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null;
return new RoleAdapter(realm, em, roles.get(0));
}
@ -115,10 +116,12 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
@Override
public RoleModel addRole(String id, String name) {
ApplicationRoleEntity roleEntity = new ApplicationRoleEntity();
RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id);
roleEntity.setName(name);
roleEntity.setApplication(applicationEntity);
roleEntity.setApplicationRole(true);
roleEntity.setRealmId(realm.getId());
em.persist(roleEntity);
applicationEntity.getRoles().add(roleEntity);
em.flush();
@ -133,9 +136,9 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
}
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.getDefaultRoles().remove(role);
@ -153,7 +156,7 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
@Override
public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>();
Collection<ApplicationRoleEntity> roles = applicationEntity.getRoles();
Collection<RoleEntity> roles = applicationEntity.getRoles();
if (roles == null) return list;
for (RoleEntity entity : roles) {
list.add(new RoleAdapter(realm, em, entity));
@ -161,28 +164,9 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
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
public Set<RoleModel> getApplicationScopeMappings(ClientModel client) {
Set<RoleModel> roleMappings = realm.getScopeMappings(client);
Set<RoleModel> roleMappings = client.getScopeMappings();
Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : roleMappings) {

View file

@ -2,9 +2,12 @@ package org.keycloak.models.jpa;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.jpa.entities.ClientEntity;
import org.keycloak.models.jpa.entities.ClientUserSessionAssociationEntity;
import org.keycloak.models.jpa.entities.ScopeMappingEntity;
import javax.persistence.EntityManager;
import javax.persistence.Query;
@ -174,6 +177,74 @@ public abstract class ClientAdapter implements ClientModel {
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
public boolean equals(Object o) {
if (this == o) return true;

View file

@ -10,6 +10,8 @@ import java.lang.reflect.Proxy;
import java.util.ArrayList;
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>
@ -73,35 +75,35 @@ public class JpaKeycloakSession implements KeycloakSession {
}
@Override
public UserModel getUserById(String id, String realmId) {
public UserModel getUserById(String id, RealmModel realmModel) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserById", UserEntity.class);
query.setParameter("id", id);
RealmEntity realm = em.getReference(RealmEntity.class, realmId);
RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId());
query.setParameter("realm", realm);
List<UserEntity> entities = query.getResultList();
if (entities.size() == 0) return null;
return new UserAdapter(em, entities.get(0));
return new UserAdapter(realmModel, em, entities.get(0));
}
@Override
public UserModel getUserByUsername(String username, String realmId) {
public UserModel getUserByUsername(String username, RealmModel realmModel) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByLoginName", UserEntity.class);
query.setParameter("loginName", username);
RealmEntity realm = em.getReference(RealmEntity.class, realmId);
RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId());
query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList();
if (results.size() == 0) return null;
return new UserAdapter(em, results.get(0));
return new UserAdapter(realmModel, em, results.get(0));
}
@Override
public UserModel getUserByEmail(String email, String realmId) {
public UserModel getUserByEmail(String email, RealmModel realmModel) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class);
query.setParameter("email", email);
RealmEntity realm = em.getReference(RealmEntity.class, realmId);
RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId());
query.setParameter("realm", realm);
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
@ -144,4 +146,59 @@ public class JpaKeycloakSession implements KeycloakSession {
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.AuthenticationProviderModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UsernameLoginFailureModel;
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.AuthenticationProviderEntity;
import org.keycloak.models.jpa.entities.CredentialEntity;
import org.keycloak.models.jpa.entities.OAuthClientEntity;
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.RoleEntity;
import org.keycloak.models.jpa.entities.ScopeMappingEntity;
@ -429,7 +427,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList();
if (results.size() == 0) return null;
return new UserAdapter(em, results.get(0));
return new UserAdapter(this, em, results.get(0));
}
@Override
@ -470,7 +468,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("email", email);
query.setParameter("realm", realm);
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
@ -479,7 +477,7 @@ public class RealmAdapter implements RealmModel {
// Check if user belongs to this realm
if (entity == null || !this.realm.equals(entity.getRealm())) return null;
return new UserAdapter(em, entity);
return new UserAdapter(this, em, entity);
}
@Override
@ -495,15 +493,15 @@ public class RealmAdapter implements RealmModel {
entity.setRealm(realm);
em.persist(entity);
em.flush();
UserModel userModel = new UserAdapter(em, entity);
UserModel userModel = new UserAdapter(this, em, entity);
for (String r : getDefaultRoles()) {
grantRole(userModel, getRole(r));
userModel.grantRole(getRole(r));
}
for (ApplicationModel application : getApplications()) {
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);
} else {
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);
List<UserEntity> results = query.getResultList();
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;
}
@ -819,7 +817,7 @@ public class RealmAdapter implements RealmModel {
query.setParameter("search", "%" + search.toLowerCase() + "%");
List<UserEntity> results = query.getResultList();
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;
}
@ -851,7 +849,7 @@ public class RealmAdapter implements RealmModel {
TypedQuery<UserEntity> query = em.createQuery(q, UserEntity.class);
List<UserEntity> results = query.getResultList();
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;
}
@ -1003,10 +1001,10 @@ public class RealmAdapter implements RealmModel {
@Override
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("realm", realm);
List<RealmRoleEntity> roles = query.getResultList();
List<RoleEntity> roles = query.getResultList();
if (roles.size() == 0) return null;
return new RoleAdapter(this, em, roles.get(0));
}
@ -1018,10 +1016,11 @@ public class RealmAdapter implements RealmModel {
@Override
public RoleModel addRole(String id, String name) {
RealmRoleEntity entity = new RealmRoleEntity();
RoleEntity entity = new RoleEntity();
entity.setId(id);
entity.setName(name);
entity.setRealm(realm);
entity.setRealmId(realm.getId());
realm.getRoles().add(entity);
em.persist(entity);
em.flush();
@ -1051,7 +1050,7 @@ public class RealmAdapter implements RealmModel {
@Override
public Set<RoleModel> getRoles() {
Set<RoleModel> list = new HashSet<RoleModel>();
Collection<RealmRoleEntity> roles = realm.getRoles();
Collection<RoleEntity> roles = realm.getRoles();
if (roles == null) return list;
for (RoleEntity entity : roles) {
list.add(new RoleAdapter(this, em, entity));
@ -1061,15 +1060,10 @@ public class RealmAdapter implements RealmModel {
@Override
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 instanceof RealmRoleEntity) {
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;
}
if (!getId().equals(entity.getRealmId())) return null;
return new RoleAdapter(this, em, entity);
}
@ -1080,141 +1074,9 @@ public class RealmAdapter implements RealmModel {
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
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.RoleContainerModel;
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.utils.KeycloakModelUtils;
@ -106,15 +104,12 @@ public class RoleAdapter implements RoleModel {
@Override
public RoleContainerModel getContainer() {
if (role instanceof ApplicationRoleEntity) {
ApplicationRoleEntity entity = (ApplicationRoleEntity)role;
return new ApplicationAdapter(realm, em, entity.getApplication());
} else if (role instanceof RealmRoleEntity) {
RealmRoleEntity entity = (RealmRoleEntity)role;
return new RealmAdapter(em, entity.getRealm());
if (role.isApplicationRole()) {
return realm.getApplicationById(role.getApplication().getId());
} else {
return realm;
}
throw new IllegalStateException("Unknown role entity type");
}
@Override

View file

@ -1,13 +1,20 @@
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.UserCredentialValueModel;
import org.keycloak.models.UserModel;
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.UserRoleMappingEntity;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@ -25,10 +32,12 @@ public class UserAdapter implements UserModel {
protected UserEntity user;
protected EntityManager em;
protected RealmModel realm;
public UserAdapter(EntityManager em, UserEntity user) {
public UserAdapter(RealmModel realm, EntityManager em, UserEntity user) {
this.em = em;
this.user = user;
this.realm = realm;
}
public UserEntity getUser() {
@ -243,6 +252,90 @@ public class UserAdapter implements UserModel {
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;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@ -17,9 +18,9 @@ public class AbstractRoleMappingEntity {
@GenericGenerator(name="keycloak_generator", strategy="org.keycloak.models.jpa.utils.JpaIdGenerator")
@GeneratedValue(generator = "keycloak_generator")
protected String id;
@ManyToOne
@ManyToOne(fetch= FetchType.LAZY)
protected UserEntity user;
@ManyToOne
@ManyToOne(fetch= FetchType.LAZY)
protected RoleEntity role;
public String getId() {

View file

@ -34,7 +34,7 @@ public class ApplicationEntity extends ClientEntity {
private boolean bearerOnly;
@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)
@JoinTable(name="ApplicationDefaultRoles")
@ -64,11 +64,11 @@ public class ApplicationEntity extends ClientEntity {
this.managementUrl = managementUrl;
}
public Collection<ApplicationRoleEntity> getRoles() {
public Collection<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Collection<ApplicationRoleEntity> roles) {
public void setRoles(Collection<RoleEntity> 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>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm")
Collection<RealmRoleEntity> roles = new ArrayList<RealmRoleEntity>();
Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@ElementCollection
@MapKeyColumn(name="name")
@ -292,17 +292,17 @@ public class RealmEntity {
this.applications = applications;
}
public Collection<RealmRoleEntity> getRoles() {
public Collection<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Collection<RealmRoleEntity> roles) {
public void setRoles(Collection<RoleEntity> roles) {
this.roles = roles;
}
public void addRole(RealmRoleEntity role) {
public void addRole(RoleEntity role) {
if (roles == null) {
roles = new ArrayList<RealmRoleEntity>();
roles = new ArrayList<RoleEntity>();
}
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;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
@ -9,6 +10,9 @@ import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.util.ArrayList;
@ -21,16 +25,38 @@ import org.hibernate.annotations.GenericGenerator;
* @version $Revision: 1 $
*/
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = { "name", "application" }),
@UniqueConstraint(columnNames = { "name", "application"}),
@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
@Column(name="id")
private String id;
private String name;
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 = {})
@JoinTable(name = "CompositeRole", joinColumns = @JoinColumn(name = "composite"), inverseJoinColumns = @JoinColumn(name = "role"))
private Collection<RoleEntity> compositeRoles = new ArrayList<RoleEntity>();
@ -43,9 +69,21 @@ public abstract class RoleEntity {
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() {
return description;
@ -63,6 +101,30 @@ public abstract class RoleEntity {
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
public boolean equals(Object o) {
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.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</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 ApplicationAdapter(RealmAdapter realm, MongoApplicationEntity applicationEntity, MongoStoreInvocationContext invContext) {
public ApplicationAdapter(RealmModel realm, MongoApplicationEntity applicationEntity, MongoStoreInvocationContext invContext) {
super(realm, applicationEntity, invContext);
}
@ -159,19 +159,6 @@ public class ApplicationAdapter extends ClientAdapter<MongoApplicationEntity> im
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
public Set<RoleModel> getApplicationScopeMappings(ClientModel client) {
Set<RoleModel> result = new HashSet<RoleModel>();

View file

@ -9,11 +9,14 @@ import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.entities.ClientEntity;
import org.keycloak.models.mongo.api.MongoIdentifiableEntity;
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.utils.MongoModelUtils;
/**
* @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 {
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);
this.clientEntity = clientEntity;
this.realm = realm;
@ -153,7 +156,7 @@ public abstract class ClientAdapter<T extends MongoIdentifiableEntity> extends A
}
@Override
public RealmAdapter getRealm() {
public RealmModel getRealm() {
return realm;
}
@ -188,4 +191,59 @@ public abstract class ClientAdapter<T extends MongoIdentifiableEntity> extends A
// todo, something more efficient like COUNT in JPAQL?
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.DBObject;
import com.mongodb.QueryBuilder;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.AuthenticationLinkModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.OAuthClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SocialLinkModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.mongo.api.MongoStore;
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.List;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
@ -92,44 +99,44 @@ public class MongoKeycloakSession implements KeycloakSession {
}
@Override
public UserModel getUserById(String id, String realmId) {
public UserModel getUserById(String id, RealmModel realm) {
MongoUserEntity user = getMongoStore().loadEntity(MongoUserEntity.class, id, invocationContext);
// 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;
} else {
return new UserAdapter(user, invocationContext);
return new UserAdapter(realm, user, invocationContext);
}
}
@Override
public UserModel getUserByUsername(String username, String realmId) {
public UserModel getUserByUsername(String username, RealmModel realm) {
DBObject query = new QueryBuilder()
.and("loginName").is(username)
.and("realmId").is(realmId)
.and("realmId").is(realm.getId())
.get();
MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext);
if (user == null) {
return null;
} else {
return new UserAdapter(user, invocationContext);
return new UserAdapter(realm, user, invocationContext);
}
}
@Override
public UserModel getUserByEmail(String email, String realmId) {
public UserModel getUserByEmail(String email, RealmModel realm) {
DBObject query = new QueryBuilder()
.and("email").is(email)
.and("realmId").is(realmId)
.and("realmId").is(realm.getId())
.get();
MongoUserEntity user = getMongoStore().loadSingleEntity(MongoUserEntity.class, query, invocationContext);
if (user == null) {
return null;
} else {
return new UserAdapter(user, invocationContext);
return new UserAdapter(realm, user, invocationContext);
}
}
@ -141,4 +148,59 @@ public class MongoKeycloakSession implements KeycloakSession {
protected MongoStore 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) {
return null;
} 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) {
return null;
} 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())) {
return null;
} 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);
for (String r : getDefaultRoles()) {
grantRole(userModel, getRole(r));
userModel.grantRole(getRole(r));
}
for (ApplicationModel application : getApplications()) {
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());
getMongoStore().insertEntity(userEntity, invocationContext);
return new UserAdapter(userEntity, invocationContext);
return new UserAdapter(this, userEntity, invocationContext);
}
@Override
@ -761,117 +761,6 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
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
public OAuthClientModel addOAuthClient(String name) {
return this.addOAuthClient(null, name);
@ -1024,7 +913,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
.and("realmId").is(getId())
.get();
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
@ -1196,7 +1085,7 @@ public class RealmAdapter extends AbstractMongoAdapter<MongoRealmEntity> impleme
protected List<UserModel> convertUserEntities(List<MongoUserEntity> userEntities) {
List<UserModel> userModels = new ArrayList<UserModel>();
for (MongoUserEntity user : userEntities) {
userModels.add(new UserAdapter(user, invocationContext));
userModels.add(new UserAdapter(this, user, invocationContext));
}
return userModels;
}

View file

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

View file

@ -1,11 +1,17 @@
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.UserCredentialValueModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.entities.CredentialEntity;
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.utils.MongoModelUtils;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import java.util.ArrayList;
@ -24,10 +30,12 @@ import java.util.Set;
public class UserAdapter extends AbstractMongoAdapter<MongoUserEntity> implements UserModel {
private final MongoUserEntity user;
private final RealmModel realm;
public UserAdapter(MongoUserEntity userEntity, MongoStoreInvocationContext invContext) {
public UserAdapter(RealmModel realm, MongoUserEntity userEntity, MongoStoreInvocationContext invContext) {
super(invContext);
this.user = userEntity;
this.realm = realm;
}
@Override
@ -249,6 +257,80 @@ public class UserAdapter extends AbstractMongoAdapter<MongoUserEntity> implement
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.keycloak.models.ApplicationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
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 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);
this.entity = entity;

View file

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

View file

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

View file

@ -104,7 +104,7 @@ public class ImportTest extends AbstractModelTest {
// Test role mappings
UserModel admin = realm.getUser("admin");
Set<RoleModel> allRoles = realm.getRoleMappings(admin);
Set<RoleModel> allRoles = admin.getRoleMappings();
Assert.assertEquals(5, allRoles.size());
Assert.assertTrue(allRoles.contains(realm.getRole("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)));
UserModel wburke = realm.getUser("wburke");
allRoles = realm.getRoleMappings(wburke);
allRoles = wburke.getRoleMappings();
Assert.assertEquals(4, allRoles.size());
Assert.assertFalse(allRoles.contains(realm.getRole("admin")));
Assert.assertTrue(allRoles.contains(application.getRole("app-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("admin", realmRoles.iterator().next().getName());
Set<RoleModel> appRoles = application.getApplicationRoleMappings(admin);
Set<RoleModel> appRoles = admin.getApplicationRoleMappings(application);
Assert.assertEquals(1, appRoles.size());
Assert.assertEquals("app-admin", appRoles.iterator().next().getName());
@ -136,12 +136,12 @@ public class ImportTest extends AbstractModelTest {
Assert.assertNotNull(oauthClient);
// Test scope relationship
Set<RoleModel> allScopes = realm.getScopeMappings(oauthClient);
Set<RoleModel> allScopes = oauthClient.getScopeMappings();
Assert.assertEquals(2, allScopes.size());
Assert.assertTrue(allScopes.contains(realm.getRole("admin")));
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")));
Set<RoleModel> appScopes = application.getApplicationScopeMappings(oauthClient);

View file

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

View file

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

View file

@ -75,11 +75,11 @@ public class ApplianceBootstrap {
adminUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
realm.grantRole(adminUser, adminRole);
adminUser.grantRole(adminRole);
ApplicationModel accountApp = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APP);
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) {
role = applicationModel.addRole(roleString.trim());
}
realm.grantRole(user, role);
user.grantRole(role);
}
}
}
@ -139,7 +139,7 @@ public class ApplicationManager {
role = applicationModel.addRole(roleString.trim());
}
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) {
if (cookie) {
return realm.hasRole(user, realm.getRole(role));
return user.hasRole(realm.getRole(role));
} else {
AccessToken.Access access = token.getRealmAccess();
return access != null && access.isUserInRole(role);
@ -66,7 +66,7 @@ public class Auth {
public boolean hasAppRole(ApplicationModel app, String role) {
if (cookie) {
return realm.hasRole(user, app.getRole(role));
return user.hasRole(app.getRole(role));
} else {
AccessToken.Access access = token.getResourceAccess(app.getName());
return access != null && access.isUserInRole(role);

View file

@ -119,7 +119,7 @@ public class RealmManager {
ApplicationModel realmAdminApp = realm.getApplicationByName(realmAdminApplicationName);
adminRole = realmAdminApp.getRole(AdminRoles.REALM_ADMIN);
}
realm.addScopeMapping(adminConsole, adminRole);
adminConsole.addScopeMapping(adminRole);
}
public String getMasterRealmAdminApplicationName(RealmModel realm) {
@ -463,7 +463,7 @@ public class RealmManager {
if (role == null) {
role = newRealm.addRole(roleString.trim());
}
newRealm.grantRole(user, role);
user.grantRole(role);
}
}
}
@ -476,7 +476,7 @@ public class RealmManager {
role = newRealm.addRole(roleString.trim());
}
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) {
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);
}
if (!realm.hasScope(client, role)) {
if (!client.hasScope(role)) {
throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has realm scope: " + roleName);
}
}
@ -180,10 +180,10 @@ public class TokenManager {
if (role == null) {
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);
}
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);
}
}
@ -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) {
// todo scopeParam is ignored until we figure out a scheme that fits with openid connect
Set<RoleModel> roleMappings = realm.getRoleMappings(user);
Set<RoleModel> scopeMappings = realm.getScopeMappings(client);
Set<RoleModel> roleMappings = user.getRoleMappings();
Set<RoleModel> scopeMappings = client.getScopeMappings();
ApplicationModel clientApp = (client instanceof ApplicationModel) ? (ApplicationModel)client : null;
Set<RoleModel> clientAppRoles = clientApp == null ? null : clientApp.getRoles();
if (clientAppRoles != null) scopeMappings.addAll(clientAppRoles);

View file

@ -210,7 +210,7 @@ public class SocialResource {
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);
return oauth.forwardToSecurityFailure("Insufficient permissions to link social account");
}

View file

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

View file

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

View file

@ -198,7 +198,7 @@ public class RealmsAdminResource {
ApplicationModel realmAdminApp = realm.getMasterAdminApp();
for (String r : AdminRoles.ALL_REALM_ROLES) {
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();
MappingsRepresentation all = new MappingsRepresentation();
Set<RoleModel> realmMappings = realm.getRealmScopeMappings(client);
Set<RoleModel> realmMappings = client.getRealmScopeMappings();
if (realmMappings.size() > 0) {
List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : realmMappings) {
@ -101,7 +101,7 @@ public class ScopeMappedResource {
public List<RoleRepresentation> getRealmScopeMappings() {
auth.requireView();
Set<RoleModel> realmMappings = realm.getRealmScopeMappings(client);
Set<RoleModel> realmMappings = client.getRealmScopeMappings();
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : realmMappings) {
realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -128,7 +128,7 @@ public class ScopeMappedResource {
private List<RoleRepresentation> getAvailable(Set<RoleModel> roles) {
List<RoleRepresentation> available = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : roles) {
if (realm.hasScope(client, roleModel)) continue;
if (client.hasScope(roleModel)) continue;
available.add(ModelToRepresentation.toRepresentation(roleModel));
}
return available;
@ -155,7 +155,7 @@ public class ScopeMappedResource {
private List<RoleRepresentation> getComposite(Set<RoleModel> roles) {
List<RoleRepresentation> composite = new ArrayList<RoleRepresentation>();
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;
}
@ -176,7 +176,7 @@ public class ScopeMappedResource {
if (roleModel == null) {
throw new NotFoundException("Role not found");
}
realm.addScopeMapping(client, roleModel);
client.addScopeMapping(roleModel);
}
@ -194,9 +194,9 @@ public class ScopeMappedResource {
auth.requireManage();
if (roles == null) {
Set<RoleModel> roleModels = realm.getRealmScopeMappings(client);
Set<RoleModel> roleModels = client.getRealmScopeMappings();
for (RoleModel roleModel : roleModels) {
realm.deleteScopeMapping(client, roleModel);
client.deleteScopeMapping(roleModel);
}
} else {
@ -205,7 +205,7 @@ public class ScopeMappedResource {
if (roleModel == null) {
throw new NotFoundException("Role not found");
}
realm.deleteScopeMapping(client, roleModel);
client.deleteScopeMapping(roleModel);
}
}
}
@ -306,7 +306,7 @@ public class ScopeMappedResource {
if (roleModel == null) {
throw new NotFoundException("Role not found");
}
realm.addScopeMapping(client, roleModel);
client.addScopeMapping(roleModel);
}
}
@ -332,7 +332,7 @@ public class ScopeMappedResource {
if (roles == null) {
Set<RoleModel> roleModels = app.getApplicationScopeMappings(client);
for (RoleModel roleModel : roleModels) {
realm.deleteScopeMapping(client, roleModel);
client.deleteScopeMapping(roleModel);
}
} else {
@ -341,7 +341,7 @@ public class ScopeMappedResource {
if (roleModel == null) {
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();
Set<RoleModel> realmMappings = realm.getRoleMappings(user);
Set<RoleModel> realmMappings = user.getRoleMappings();
RealmManager manager = new RealmManager(session);
if (realmMappings.size() > 0) {
List<RoleRepresentation> realmRep = new ArrayList<RoleRepresentation>();
@ -390,7 +390,7 @@ public class UsersResource {
if (applications.size() > 0) {
Map<String, ApplicationMappingsRepresentation> appMappings = new HashMap<String, ApplicationMappingsRepresentation>();
for (ApplicationModel application : applications) {
Set<RoleModel> roleMappings = application.getApplicationRoleMappings(user);
Set<RoleModel> roleMappings = user.getApplicationRoleMappings(application);
if (roleMappings.size() > 0) {
ApplicationMappingsRepresentation mappings = new ApplicationMappingsRepresentation();
mappings.setApplicationId(application.getId());
@ -426,7 +426,7 @@ public class UsersResource {
throw new NotFoundException("User not found");
}
Set<RoleModel> realmMappings = realm.getRealmRoleMappings(user);
Set<RoleModel> realmMappings = user.getRealmRoleMappings();
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : realmMappings) {
realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -455,7 +455,7 @@ public class UsersResource {
Set<RoleModel> roles = realm.getRoles();
List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : roles) {
if (realm.hasRole(user, roleModel)) {
if (user.hasRole(roleModel)) {
realmMappingsRep.add(ModelToRepresentation.toRepresentation(roleModel));
}
}
@ -507,7 +507,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found");
}
realm.grantRole(user, roleModel);
user.grantRole(roleModel);
}
@ -532,9 +532,9 @@ public class UsersResource {
}
if (roles == null) {
Set<RoleModel> roleModels = realm.getRealmRoleMappings(user);
Set<RoleModel> roleModels = user.getRealmRoleMappings();
for (RoleModel roleModel : roleModels) {
realm.deleteRoleMapping(user, roleModel);
user.deleteRoleMapping(roleModel);
}
} else {
@ -543,7 +543,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) {
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");
}
Set<RoleModel> mappings = application.getApplicationRoleMappings(user);
Set<RoleModel> mappings = user.getApplicationRoleMappings(application);
List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
for (RoleModel roleModel : mappings) {
mapRep.add(ModelToRepresentation.toRepresentation(roleModel));
@ -614,7 +614,7 @@ public class UsersResource {
Set<RoleModel> roles = application.getRoles();
List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
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());
return mapRep;
@ -653,7 +653,7 @@ public class UsersResource {
protected List<RoleRepresentation> getAvailableRoles(UserModel user, Set<RoleModel> available) {
Set<RoleModel> roles = new HashSet<RoleModel>();
for (RoleModel roleModel : available) {
if (realm.hasRole(user, roleModel)) continue;
if (user.hasRole(roleModel)) continue;
roles.add(roleModel);
}
@ -694,7 +694,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found");
}
realm.grantRole(user, roleModel);
user.grantRole(roleModel);
}
}
@ -724,13 +724,13 @@ public class UsersResource {
}
if (roles == null) {
Set<RoleModel> roleModels = application.getApplicationRoleMappings(user);
Set<RoleModel> roleModels = user.getApplicationRoleMappings(application);
for (RoleModel roleModel : roleModels) {
if (!(roleModel.getContainer() instanceof ApplicationModel)) {
ApplicationModel app = (ApplicationModel) roleModel.getContainer();
if (!app.getId().equals(application.getId())) continue;
}
realm.deleteRoleMapping(user, roleModel);
user.deleteRoleMapping(roleModel);
}
} else {
@ -739,7 +739,7 @@ public class UsersResource {
if (roleModel == null || !roleModel.getId().equals(role.getId())) {
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.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class>

View file

@ -4,4 +4,4 @@ log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] %m%n
log4j.logger.org.keycloak=warn
log4j.logger.org.keycloak=warn

View file

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

View file

@ -59,7 +59,7 @@ public class ProfileTest {
UserModel user2 = appRealm.addUser("test-user-no-access@localhost");
user2.setEnabled(true);
for (String r : accountApp.getDefaultRoles()) {
appRealm.deleteRoleMapping(user2, accountApp.getRole(r));
user2.deleteRoleMapping(accountApp.getRole(r));
}
UserCredentialModel creds = new UserCredentialModel();
creds.setType(CredentialRepresentation.PASSWORD);
@ -67,12 +67,12 @@ public class ProfileTest {
user2.updateCredential(creds);
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.addWebOrigin("http://localtest.me:8081");
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");
realmComposite1User.setEnabled(true);
realmComposite1User.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmComposite1User, realmComposite1);
realmComposite1User.grantRole(realmComposite1);
final UserModel realmRole1User = realm.addUser("REALM_ROLE_1_USER");
realmRole1User.setEnabled(true);
realmRole1User.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmRole1User, realmRole1);
realmRole1User.grantRole(realmRole1);
final ApplicationModel realmComposite1Application = new ApplicationManager(manager).createApplication(realm, "REALM_COMPOSITE_1_APPLICATION");
realmComposite1Application.setEnabled(true);
realm.addScopeMapping(realmComposite1Application, realmComposite1);
realmComposite1Application.addScopeMapping(realmComposite1);
realmComposite1Application.addRedirectUri("http://localhost:8081/app/*");
realmComposite1Application.setBaseUrl("http://localhost:8081/app");
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");
realmRole1Application.setEnabled(true);
realm.addScopeMapping(realmRole1Application, realmRole1);
realmRole1Application.addScopeMapping(realmRole1);
realmRole1Application.addRedirectUri("http://localhost:8081/app/*");
realmRole1Application.setBaseUrl("http://localhost:8081/app");
realmRole1Application.setManagementUrl("http://localhost:8081/app/logout");
@ -117,12 +117,12 @@ public class CompositeRoleTest {
final UserModel realmAppCompositeUser = realm.addUser("REALM_APP_COMPOSITE_USER");
realmAppCompositeUser.setEnabled(true);
realmAppCompositeUser.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmAppCompositeUser, realmAppCompositeRole);
realmAppCompositeUser.grantRole(realmAppCompositeRole);
final UserModel realmAppRoleUser = realm.addUser("REALM_APP_ROLE_USER");
realmAppRoleUser.setEnabled(true);
realmAppRoleUser.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(realmAppRoleUser, appRole2);
realmAppRoleUser.grantRole(appRole2);
final ApplicationModel appCompositeApplication = new ApplicationManager(manager).createApplication(realm, "APP_COMPOSITE_APPLICATION");
appCompositeApplication.setEnabled(true);
@ -131,7 +131,7 @@ public class CompositeRoleTest {
appCompositeApplication.setManagementUrl("http://localhost:8081/app/logout");
appCompositeApplication.setSecret("password");
final RoleModel appCompositeRole = appCompositeApplication.addRole("APP_COMPOSITE_ROLE");
realm.addScopeMapping(appCompositeApplication, appRole2);
appCompositeApplication.addScopeMapping(appRole2);
appCompositeRole.addCompositeRole(realmRole1);
appCompositeRole.addCompositeRole(realmRole2);
appCompositeRole.addCompositeRole(realmRole3);
@ -140,8 +140,8 @@ public class CompositeRoleTest {
final UserModel appCompositeUser = realm.addUser("APP_COMPOSITE_USER");
appCompositeUser.setEnabled(true);
appCompositeUser.updateCredential(UserCredentialModel.password("password"));
realm.grantRole(appCompositeUser, realmAppCompositeRole);
realm.grantRole(appCompositeUser, realmComposite1);
appCompositeUser.grantRole(realmAppCompositeRole);
appCompositeUser.grantRole(realmComposite1);
deployServlet("app", "/app", ApplicationServlet.class);

View file

@ -91,13 +91,13 @@ public class ReadUsersWorker implements Worker {
// Read roles of user in realm
if (readRoles) {
realm.getRoleMappings(user);
user.getRoleMappings();
}
// Read scopes of user in realm
if (readScopes) {
ClientModel client = realm.findClient(username);
realm.getScopeMappings(client);
client.getScopeMappings();
}
// 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.RequiredCredentialEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationProviderEntity</class>
<class>org.keycloak.models.jpa.entities.ApplicationRoleEntity</class>
<class>org.keycloak.models.jpa.entities.RealmRoleEntity</class>
<class>org.keycloak.models.jpa.entities.RoleEntity</class>
<class>org.keycloak.models.jpa.entities.SocialLinkEntity</class>
<class>org.keycloak.models.jpa.entities.AuthenticationLinkEntity</class>
<class>org.keycloak.models.jpa.entities.UserEntity</class>