From 9433ef284a08168c78c1750137bfcb4cd4ead662 Mon Sep 17 00:00:00 2001 From: Bill Burke Date: Fri, 16 Oct 2015 11:03:30 -0400 Subject: [PATCH 1/4] set browser flow switch --- .../src/main/java/org/keycloak/protocol/saml/SamlService.java | 1 + .../keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java | 1 + 2 files changed, 2 insertions(+) diff --git a/saml/saml-protocol/src/main/java/org/keycloak/protocol/saml/SamlService.java b/saml/saml-protocol/src/main/java/org/keycloak/protocol/saml/SamlService.java index 6aae844da6..2ebdb23671 100755 --- a/saml/saml-protocol/src/main/java/org/keycloak/protocol/saml/SamlService.java +++ b/saml/saml-protocol/src/main/java/org/keycloak/protocol/saml/SamlService.java @@ -511,6 +511,7 @@ public class SamlService { processor.setClientSession(clientSession) .setFlowPath(LoginActionsService.AUTHENTICATE_PATH) .setFlowId(flowId) + .setBrowserFlow(true) .setConnection(clientConnection) .setEventBuilder(event) .setProtector(authManager.getProtector()) diff --git a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java index da13ae6334..85c7fd87d2 100755 --- a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java +++ b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java @@ -347,6 +347,7 @@ public class AuthorizationEndpoint { processor.setClientSession(clientSession) .setFlowPath(flowPath) .setFlowId(flowId) + .setBrowserFlow(true) .setConnection(clientConnection) .setEventBuilder(event) .setProtector(authManager.getProtector()) From d896800ec653d92699b430cf676e862fdf3116d7 Mon Sep 17 00:00:00 2001 From: Bill Burke Date: Thu, 29 Oct 2015 16:33:02 -0400 Subject: [PATCH 2/4] groups initial --- .../idm/GroupRepresentation.java | 81 +++++ .../idm/RealmRepresentation.java | 9 + .../BasePropertiesFederationProvider.java | 7 + ...ClasspathPropertiesFederationProvider.java | 2 + .../kerberos/KerberosFederationProvider.java | 6 + .../ldap/LDAPFederationProvider.java | 6 + .../RefreshableKeycloakSecurityContext.java | 3 +- .../java/org/keycloak/models/GroupModel.java | 74 ++++ .../java/org/keycloak/models/RealmModel.java | 8 + .../org/keycloak/models/RealmProvider.java | 5 +- .../models/UserFederationManager.java | 20 ++ .../models/UserFederationProvider.java | 8 + .../java/org/keycloak/models/UserModel.java | 5 + .../org/keycloak/models/UserProvider.java | 5 + .../keycloak/models/entities/GroupEntity.java | 60 ++++ .../keycloak/models/entities/UserEntity.java | 9 + .../models/utils/KeycloakModelUtils.java | 19 ++ .../models/utils/UserModelDelegate.java | 23 ++ .../models/file/FileRealmProvider.java | 6 + .../models/file/FileUserProvider.java | 16 + .../models/file/adapter/GroupAdapter.java | 208 ++++++++++++ .../models/file/adapter/RealmAdapter.java | 32 ++ .../models/file/adapter/UserAdapter.java | 25 ++ .../infinispan/DefaultCacheRealmProvider.java | 36 ++ .../infinispan/DefaultCacheUserProvider.java | 15 + .../models/cache/infinispan/GroupAdapter.java | 236 +++++++++++++ .../infinispan/InfinispanRealmCache.java | 38 +++ .../models/cache/infinispan/RealmAdapter.java | 38 +++ .../models/cache/infinispan/UserAdapter.java | 39 +++ .../models/cache/CacheRealmProvider.java | 2 + .../org/keycloak/models/cache/RealmCache.java | 11 + .../models/cache/entities/CachedGroup.java | 74 ++++ .../models/cache/entities/CachedRealm.java | 9 + .../models/cache/entities/CachedUser.java | 12 + .../org/keycloak/models/jpa/GroupAdapter.java | 320 ++++++++++++++++++ .../keycloak/models/jpa/JpaRealmProvider.java | 10 + .../keycloak/models/jpa/JpaUserProvider.java | 41 +++ .../org/keycloak/models/jpa/RealmAdapter.java | 58 ++++ .../org/keycloak/models/jpa/UserAdapter.java | 59 ++++ .../jpa/entities/GroupAttributeEntity.java | 70 ++++ .../models/jpa/entities/GroupEntity.java | 109 ++++++ .../jpa/entities/GroupRoleMappingEntity.java | 101 ++++++ .../models/jpa/entities/RealmEntity.java | 19 ++ .../entities/UserGroupMembershipEntity.java | 102 ++++++ .../mongo/keycloak/adapters/GroupAdapter.java | 225 ++++++++++++ .../keycloak/adapters/MongoRealmProvider.java | 10 + .../keycloak/adapters/MongoUserProvider.java | 28 ++ .../mongo/keycloak/adapters/RealmAdapter.java | 43 +++ .../mongo/keycloak/adapters/UserAdapter.java | 32 ++ .../keycloak/entities/MongoGroupEntity.java | 26 ++ .../models/mongo/utils/MongoModelUtils.java | 2 + .../DummyUserFederationProvider.java | 6 + 52 files changed, 2406 insertions(+), 2 deletions(-) create mode 100755 core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java mode change 100644 => 100755 federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java create mode 100755 model/api/src/main/java/org/keycloak/models/GroupModel.java create mode 100755 model/api/src/main/java/org/keycloak/models/entities/GroupEntity.java create mode 100755 model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java mode change 100644 => 100755 model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheRealmProvider.java mode change 100644 => 100755 model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheUserProvider.java create mode 100755 model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java create mode 100755 model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedGroup.java create mode 100755 model/jpa/src/main/java/org/keycloak/models/jpa/GroupAdapter.java create mode 100755 model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java create mode 100755 model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java create mode 100755 model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java create mode 100755 model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserGroupMembershipEntity.java create mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java create mode 100755 model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java diff --git a/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java new file mode 100755 index 0000000000..833dfe3a5f --- /dev/null +++ b/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java @@ -0,0 +1,81 @@ +package org.keycloak.representations.idm; + +import org.codehaus.jackson.annotate.JsonIgnore; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class GroupRepresentation { + private String id; + private String name; + protected Map attributes; + protected List realmRoles; + protected Map> clientRoles; + protected List subGroups; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getRealmRoles() { + return realmRoles; + } + + public void setRealmRoles(List realmRoles) { + this.realmRoles = realmRoles; + } + + public Map> getClientRoles() { + return clientRoles; + } + + public void setClientRoles(Map> clientRoles) { + this.clientRoles = clientRoles; + } + + public Map getAttributes() { + return attributes; + } + + // This method can be removed once we can remove backwards compatibility with Keycloak 1.3 (then getAttributes() can be changed to return Map> ) + @JsonIgnore + public Map> getAttributesAsListValues() { + return (Map) attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public GroupRepresentation singleAttribute(String name, String value) { + if (this.attributes == null) attributes = new HashMap<>(); + attributes.put(name, Arrays.asList(value)); + return this; + } + + public List getSubGroups() { + return subGroups; + } + + public void setSubGroups(List subGroups) { + this.subGroups = subGroups; + } +} diff --git a/core/src/main/java/org/keycloak/representations/idm/RealmRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/RealmRepresentation.java index 387ab7e783..e1333e9280 100755 --- a/core/src/main/java/org/keycloak/representations/idm/RealmRepresentation.java +++ b/core/src/main/java/org/keycloak/representations/idm/RealmRepresentation.java @@ -47,6 +47,7 @@ public class RealmRepresentation { protected String certificate; protected String codeSecret; protected RolesRepresentation roles; + protected List groups; protected List defaultRoles; @Deprecated protected Set requiredCredentials; @@ -775,4 +776,12 @@ public class RealmRepresentation { public void setClientAuthenticationFlow(String clientAuthenticationFlow) { this.clientAuthenticationFlow = clientAuthenticationFlow; } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } } diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java index f6228959c8..d6475aaa61 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java @@ -1,6 +1,7 @@ package org.keycloak.examples.federation.properties; import org.keycloak.models.CredentialValidationOutput; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; @@ -106,6 +107,12 @@ public abstract class BasePropertiesFederationProvider implements UserFederation } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + // complete we dont'care if a role is removed + + } + /** * See if the user is still in the properties file * diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java index 164cf79cdb..5467a425f0 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java @@ -63,4 +63,6 @@ public class ClasspathPropertiesFederationProvider extends BasePropertiesFederat throw new IllegalStateException("Remove not supported"); } + + } diff --git a/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java b/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java old mode 100644 new mode 100755 index ec1a905010..09a4da75b6 --- a/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java +++ b/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java @@ -12,6 +12,7 @@ import org.jboss.logging.Logger; import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator; import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator; import org.keycloak.models.CredentialValidationOutput; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; @@ -105,6 +106,11 @@ public class KerberosFederationProvider implements UserFederationProvider { } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + + } + @Override public boolean isValid(RealmModel realm, UserModel local) { // KerberosUsernamePasswordAuthenticator.isUserAvailable is an overhead, so avoid it for now diff --git a/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java b/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java index 322155b61a..3704f7626f 100755 --- a/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java +++ b/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java @@ -12,6 +12,7 @@ import org.keycloak.federation.ldap.idm.store.ldap.LDAPIdentityStore; import org.keycloak.federation.ldap.kerberos.LDAPProviderKerberosConfig; import org.keycloak.federation.ldap.mappers.LDAPFederationMapper; import org.keycloak.models.CredentialValidationOutput; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.LDAPConstants; import org.keycloak.models.ModelDuplicateException; @@ -319,6 +320,11 @@ public class LDAPFederationProvider implements UserFederationProvider { // TODO: Maybe mappers callback to ensure role deletion propagated to LDAP by RoleLDAPFederationMapper? } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + + } + public boolean validPassword(RealmModel realm, UserModel user, String password) { if (kerberosConfig.isAllowKerberosAuthentication() && kerberosConfig.isUseKerberosForPasswordAuthentication()) { // Use Kerberos JAAS (Krb5LoginModule) diff --git a/integration/adapter-core/src/main/java/org/keycloak/adapters/RefreshableKeycloakSecurityContext.java b/integration/adapter-core/src/main/java/org/keycloak/adapters/RefreshableKeycloakSecurityContext.java index b9bdb0dc2f..6e954e7cbb 100755 --- a/integration/adapter-core/src/main/java/org/keycloak/adapters/RefreshableKeycloakSecurityContext.java +++ b/integration/adapter-core/src/main/java/org/keycloak/adapters/RefreshableKeycloakSecurityContext.java @@ -57,7 +57,7 @@ public class RefreshableKeycloakSecurityContext extends KeycloakSecurityContext } public boolean isActive() { - return this.token.isActive() && this.token.getIssuedAt() > deployment.getNotBefore(); + return token != null && this.token.isActive() && this.token.getIssuedAt() > deployment.getNotBefore(); } public KeycloakDeployment getDeployment() { @@ -111,6 +111,7 @@ public class RefreshableKeycloakSecurityContext extends KeycloakSecurityContext log.debug("Token Verification succeeded!"); } catch (VerificationException e) { log.error("failed verification of token"); + return false; } if (response.getNotBeforePolicy() > deployment.getNotBefore()) { deployment.setNotBefore(response.getNotBeforePolicy()); diff --git a/model/api/src/main/java/org/keycloak/models/GroupModel.java b/model/api/src/main/java/org/keycloak/models/GroupModel.java new file mode 100755 index 0000000000..a1a63f8034 --- /dev/null +++ b/model/api/src/main/java/org/keycloak/models/GroupModel.java @@ -0,0 +1,74 @@ +package org.keycloak.models; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public interface GroupModel { + String getId(); + + String getName(); + + void setName(String name); + + /** + * Set single value of specified attribute. Remove all other existing values + * + * @param name + * @param value + */ + void setSingleAttribute(String name, String value); + + void setAttribute(String name, List values); + + void removeAttribute(String name); + + /** + * @param name + * @return null if there is not any value of specified attribute or first value otherwise. Don't throw exception if there are more values of the attribute + */ + String getFirstAttribute(String name); + + /** + * @param name + * @return list of all attribute values or empty list if there are not any values. Never return null + */ + List getAttribute(String name); + + Map> getAttributes(); + + Set getRealmRoleMappings(); + Set getClientRoleMappings(ClientModel app); + boolean hasRole(RoleModel role); + void grantRole(RoleModel role); + Set getRoleMappings(); + void deleteRoleMapping(RoleModel role); + + GroupModel getParent(); + Set getSubGroups(); + + /** + * You must also call joinGroup on the parent group. + * + * @param group + */ + void setParent(GroupModel group); + + /** + * Automatically calls setParent() on the subGroup + * + * @param subGroup + */ + void addChild(GroupModel subGroup); + + /** + * Automatically calls setParent() on the subGroup + * + * @param subGroup + */ + void removeChild(GroupModel subGroup); +} diff --git a/model/api/src/main/java/org/keycloak/models/RealmModel.java b/model/api/src/main/java/org/keycloak/models/RealmModel.java index 0737ee385b..43934ef8cb 100755 --- a/model/api/src/main/java/org/keycloak/models/RealmModel.java +++ b/model/api/src/main/java/org/keycloak/models/RealmModel.java @@ -328,4 +328,12 @@ public interface RealmModel extends RoleContainerModel { void setSupportedLocales(Set locales); String getDefaultLocale(); void setDefaultLocale(String locale); + + GroupModel getGroupById(String id); + List getGroups(); + List getTopLevelGroups(); + boolean removeGroup(GroupModel group); + + + } diff --git a/model/api/src/main/java/org/keycloak/models/RealmProvider.java b/model/api/src/main/java/org/keycloak/models/RealmProvider.java index 8e864cf874..f649f3509c 100755 --- a/model/api/src/main/java/org/keycloak/models/RealmProvider.java +++ b/model/api/src/main/java/org/keycloak/models/RealmProvider.java @@ -20,8 +20,11 @@ public interface RealmProvider extends Provider { RoleModel getRoleById(String id, RealmModel realm); ClientModel getClientById(String id, RealmModel realm); + GroupModel getGroupById(String id, RealmModel realm); + + + List getRealms(); boolean removeRealm(String id); - void close(); } diff --git a/model/api/src/main/java/org/keycloak/models/UserFederationManager.java b/model/api/src/main/java/org/keycloak/models/UserFederationManager.java index bea51e0473..b0ffba4752 100755 --- a/model/api/src/main/java/org/keycloak/models/UserFederationManager.java +++ b/model/api/src/main/java/org/keycloak/models/UserFederationManager.java @@ -165,6 +165,16 @@ public class UserFederationManager implements UserProvider { return user; } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { + return session.userStorage().getGroupMembers(realm, group, firstResult, maxResults); + } + + @Override + public List getGroupMembers(RealmModel realm, GroupModel group) { + return getGroupMembers(realm, group, -1, -1); + } + @Override public UserModel getUserByUsername(String username, RealmModel realm) { UserModel user = session.userStorage().getUserByUsername(username.toLowerCase(), realm); @@ -347,6 +357,16 @@ public class UserFederationManager implements UserProvider { session.userStorage().preRemove(realm, model); } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + for (UserFederationProviderModel federation : realm.getUserFederationProviders()) { + UserFederationProvider fed = getFederationProvider(federation); + fed.preRemove(realm, group); + } + session.userStorage().preRemove(realm, group); + + } + @Override public void preRemove(RealmModel realm, RoleModel role) { for (UserFederationProviderModel federation : realm.getUserFederationProviders()) { diff --git a/model/api/src/main/java/org/keycloak/models/UserFederationProvider.java b/model/api/src/main/java/org/keycloak/models/UserFederationProvider.java index f60c21d7a7..043176e88b 100755 --- a/model/api/src/main/java/org/keycloak/models/UserFederationProvider.java +++ b/model/api/src/main/java/org/keycloak/models/UserFederationProvider.java @@ -119,6 +119,14 @@ public interface UserFederationProvider extends Provider { */ void preRemove(RealmModel realm, RoleModel role); + /** + * called before a role is removed. + * + * @param realm + * @param group + */ + void preRemove(RealmModel realm, GroupModel group); + /** * Is the Keycloak UserModel still valid and/or existing in federated storage? Keycloak may call this method * in various user operations. The local storage may be deleted if this method returns false. diff --git a/model/api/src/main/java/org/keycloak/models/UserModel.java b/model/api/src/main/java/org/keycloak/models/UserModel.java index 9dec77844c..e35633d05e 100755 --- a/model/api/src/main/java/org/keycloak/models/UserModel.java +++ b/model/api/src/main/java/org/keycloak/models/UserModel.java @@ -101,6 +101,11 @@ public interface UserModel { Set getRoleMappings(); void deleteRoleMapping(RoleModel role); + Set getGroups(); + void joinGroup(GroupModel group); + void leaveGroup(GroupModel group); + boolean isMemberOf(GroupModel group); + String getFederationLink(); void setFederationLink(String link); diff --git a/model/api/src/main/java/org/keycloak/models/UserProvider.java b/model/api/src/main/java/org/keycloak/models/UserProvider.java index 7d7064d76e..2ad5c55f8a 100755 --- a/model/api/src/main/java/org/keycloak/models/UserProvider.java +++ b/model/api/src/main/java/org/keycloak/models/UserProvider.java @@ -25,12 +25,16 @@ public interface UserProvider extends Provider { UserModel getUserById(String id, RealmModel realm); UserModel getUserByUsername(String username, RealmModel realm); UserModel getUserByEmail(String email, RealmModel realm); + + List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults); + UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm); UserModel getUserByServiceAccountClient(ClientModel client); List getUsers(RealmModel realm, boolean includeServiceAccounts); // Service account is included for counts int getUsersCount(RealmModel realm); + List getGroupMembers(RealmModel realm, GroupModel group); List getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts); List searchForUser(String search, RealmModel realm); List searchForUser(String search, RealmModel realm, int firstResult, int maxResults); @@ -48,6 +52,7 @@ public interface UserProvider extends Provider { void preRemove(RealmModel realm, UserFederationProviderModel link); void preRemove(RealmModel realm, RoleModel role); + void preRemove(RealmModel realm, GroupModel group); void preRemove(RealmModel realm, ClientModel client); void preRemove(ClientModel realm, ProtocolMapperModel protocolMapper); diff --git a/model/api/src/main/java/org/keycloak/models/entities/GroupEntity.java b/model/api/src/main/java/org/keycloak/models/entities/GroupEntity.java new file mode 100755 index 0000000000..5e64643e57 --- /dev/null +++ b/model/api/src/main/java/org/keycloak/models/entities/GroupEntity.java @@ -0,0 +1,60 @@ +package org.keycloak.models.entities; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author Bill Burke/a> + */ +public class GroupEntity extends AbstractIdentifiableEntity { + + private String name; + private String realmId; + + private List roleIds; + private String parentId; + private Map> attributes; + + public String getRealmId() { + return realmId; + } + + public void setRealmId(String realmId) { + this.realmId = realmId; + } + + public List getRoleIds() { + return roleIds; + } + + public void setRoleIds(List roleIds) { + this.roleIds = roleIds; + } + + public Map> getAttributes() { + return attributes; + } + + public void setAttributes(Map> attributes) { + this.attributes = attributes; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getParentId() { + return parentId; + } + + public void setParentId(String parentId) { + this.parentId = parentId; + } +} + diff --git a/model/api/src/main/java/org/keycloak/models/entities/UserEntity.java b/model/api/src/main/java/org/keycloak/models/entities/UserEntity.java index 8c82a8e13b..2c118beb06 100755 --- a/model/api/src/main/java/org/keycloak/models/entities/UserEntity.java +++ b/model/api/src/main/java/org/keycloak/models/entities/UserEntity.java @@ -21,6 +21,7 @@ public class UserEntity extends AbstractIdentifiableEntity { private String realmId; private List roleIds; + private List groupIds; private Map> attributes; private List requiredActions; @@ -157,5 +158,13 @@ public class UserEntity extends AbstractIdentifiableEntity { public void setServiceAccountClientLink(String serviceAccountClientLink) { this.serviceAccountClientLink = serviceAccountClientLink; } + + public List getGroupIds() { + return groupIds; + } + + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } } diff --git a/model/api/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java b/model/api/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java index 4b630d8019..8244467096 100755 --- a/model/api/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java +++ b/model/api/src/main/java/org/keycloak/models/utils/KeycloakModelUtils.java @@ -3,6 +3,7 @@ package org.keycloak.models.utils; import org.bouncycastle.openssl.PEMWriter; import org.keycloak.models.ClientModel; import org.keycloak.models.Constants; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.KeycloakSessionTask; @@ -279,6 +280,24 @@ public final class KeycloakModelUtils { return false; } + /** + * + * @param groups + * @param targetGroup + * @return true if targetGroup is in groups (directly or indirectly via parent child relationship) + */ + public static boolean isMember(Set groups, GroupModel targetGroup) { + if (groups.contains(targetGroup)) return true; + + for (GroupModel mapping : groups) { + GroupModel child = mapping; + while(child.getParent() != null) { + if (child.getParent().equals(targetGroup)) return true; + child = child.getParent(); + } + } + return false; + } // USER FEDERATION RELATED STUFF /** diff --git a/model/api/src/main/java/org/keycloak/models/utils/UserModelDelegate.java b/model/api/src/main/java/org/keycloak/models/utils/UserModelDelegate.java index 4cd162bce6..23ca7f673e 100755 --- a/model/api/src/main/java/org/keycloak/models/utils/UserModelDelegate.java +++ b/model/api/src/main/java/org/keycloak/models/utils/UserModelDelegate.java @@ -1,6 +1,7 @@ package org.keycloak.models.utils; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.UserConsentModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; @@ -255,4 +256,26 @@ public class UserModelDelegate implements UserModel { public void setCreatedTimestamp(Long timestamp){ delegate.setCreatedTimestamp(timestamp); } + + @Override + public Set getGroups() { + return delegate.getGroups(); + } + + @Override + public void joinGroup(GroupModel group) { + delegate.joinGroup(group); + + } + + @Override + public void leaveGroup(GroupModel group) { + delegate.leaveGroup(group); + + } + + @Override + public boolean isMemberOf(GroupModel group) { + return delegate.isMemberOf(group); + } } diff --git a/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java b/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java index 593aa88a1a..33d4fa36d3 100755 --- a/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java +++ b/model/file/src/main/java/org/keycloak/models/file/FileRealmProvider.java @@ -20,6 +20,7 @@ import org.keycloak.connections.file.FileConnectionProvider; import org.keycloak.connections.file.InMemoryModel; import org.keycloak.migration.MigrationModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.RealmModel; @@ -78,6 +79,11 @@ public class FileRealmProvider implements RealmProvider { return realm; } + @Override + public GroupModel getGroupById(String id, RealmModel realm) { + return null; + } + @Override public RealmModel getRealm(String id) { RealmModel model = inMemoryModel.getRealm(id); diff --git a/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java b/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java index 8edfe3ec2e..6540c37684 100755 --- a/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java +++ b/model/file/src/main/java/org/keycloak/models/file/FileUserProvider.java @@ -21,6 +21,7 @@ import org.keycloak.connections.file.InMemoryModel; import org.keycloak.models.ClientModel; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.FederatedIdentityModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelException; @@ -80,6 +81,21 @@ public class FileUserProvider implements UserProvider { return inMemoryModel.getUser(realm.getId(), userId); } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { + return null; + } + + @Override + public List getGroupMembers(RealmModel realm, GroupModel group) { + return null; + } + + @Override + public void preRemove(RealmModel realm, GroupModel group) { + + } + @Override public UserModel getUserByUsername(String username, RealmModel realm) { for (UserModel user : inMemoryModel.getUsers(realm.getId())) { diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java new file mode 100755 index 0000000000..ca10f6c901 --- /dev/null +++ b/model/file/src/main/java/org/keycloak/models/file/adapter/GroupAdapter.java @@ -0,0 +1,208 @@ +package org.keycloak.models.file.adapter; + +import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.entities.GroupEntity; +import org.keycloak.models.utils.KeycloakModelUtils; + +import java.util.ArrayList; +import java.util.Collections; +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 Marek Posolda + */ +public class GroupAdapter implements GroupModel { + + private final GroupEntity group; + private RealmModel realm; + private KeycloakSession session; + + public GroupAdapter(KeycloakSession session, RealmModel realm, GroupEntity group) { + this.group = group; + this.realm = realm; + this.session = session; + } + + @Override + public String getId() { + return group.getId(); + } + + @Override + public String getName() { + return group.getName(); + } + + @Override + public void setName(String name) { + group.setName(name); + } + + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || !(o instanceof GroupModel)) return false; + + GroupModel that = (GroupModel) o; + return that.getId().equals(getId()); + } + + @Override + public int hashCode() { + return getId().hashCode(); + } + + @Override + public void setSingleAttribute(String name, String value) { + if (group.getAttributes() == null) { + group.setAttributes(new HashMap>()); + } + + List attrValues = new ArrayList<>(); + attrValues.add(value); + group.getAttributes().put(name, attrValues); + } + + @Override + public void setAttribute(String name, List values) { + if (group.getAttributes() == null) { + group.setAttributes(new HashMap>()); + } + + group.getAttributes().put(name, values); + } + + @Override + public void removeAttribute(String name) { + if (group.getAttributes() == null) return; + + group.getAttributes().remove(name); + } + + @Override + public String getFirstAttribute(String name) { + if (group.getAttributes()==null) return null; + + List attrValues = group.getAttributes().get(name); + return (attrValues==null || attrValues.isEmpty()) ? null : attrValues.get(0); + } + + @Override + public List getAttribute(String name) { + if (group.getAttributes()==null) return Collections.emptyList(); + List attrValues = group.getAttributes().get(name); + return (attrValues == null) ? Collections.emptyList() : Collections.unmodifiableList(attrValues); + } + + @Override + public Map> getAttributes() { + return group.getAttributes()==null ? Collections.>emptyMap() : Collections.unmodifiableMap((Map) group.getAttributes()); + } + + @Override + public boolean hasRole(RoleModel role) { + Set roles = getRoleMappings(); + return KeycloakModelUtils.hasRole(roles, role); + } + + @Override + public void grantRole(RoleModel role) { + if (group.getRoleIds() == null) { + group.setRoleIds(new LinkedList()); + } + if (group.getRoleIds().contains(role.getId())) { + return; + } + group.getRoleIds().add(role.getId()); + } + + @Override + public Set getRoleMappings() { + if (group.getRoleIds() == null || group.getRoleIds().isEmpty()) return Collections.EMPTY_SET; + Set roles = new HashSet<>(); + for (String id : group.getRoleIds()) { + roles.add(realm.getRoleById(id)); + } + return roles; + } + + @Override + public Set getRealmRoleMappings() { + Set allRoles = getRoleMappings(); + + // Filter to retrieve just realm roles + Set realmRoles = new HashSet(); + for (RoleModel role : allRoles) { + if (role.getContainer() instanceof RealmModel) { + realmRoles.add(role); + } + } + return realmRoles; + } + + @Override + public void deleteRoleMapping(RoleModel role) { + if (group == null || role == null) return; + if (group.getRoleIds() == null) return; + group.getRoleIds().remove(role.getId()); + } + + @Override + public Set getClientRoleMappings(ClientModel app) { + Set result = new HashSet(); + Set roles = getRoleMappings(); + + for (RoleModel role : roles) { + if (app.equals(role.getContainer())) { + result.add(role); + } + } + return result; + } + + @Override + public GroupModel getParent() { + if (group.getParentId() == null) return null; + return realm.getGroupById(group.getParentId()); + } + + @Override + public Set getSubGroups() { + Set subGroups = new HashSet<>(); + for (GroupModel groupModel : realm.getGroups()) { + if (groupModel.getParent().equals(this)) { + subGroups.add(groupModel); + } + } + return subGroups; + } + + @Override + public void setParent(GroupModel group) { + this.group.setParentId(group.getId()); + + } + + @Override + public void addChild(GroupModel subGroup) { + subGroup.setParent(this); + + } + + @Override + public void removeChild(GroupModel subGroup) { + subGroup.setParent(null); + + } +} diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java index 584348074e..4f24afd867 100755 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java +++ b/model/file/src/main/java/org/keycloak/models/file/adapter/RealmAdapter.java @@ -22,6 +22,7 @@ import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationFlowModel; import org.keycloak.models.AuthenticatorConfigModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; @@ -88,6 +89,7 @@ public class RealmAdapter implements RealmModel { private final Map allApps = new HashMap(); private ClientModel masterAdminApp = null; private final Map allRoles = new HashMap(); + private final Map allGroups = new HashMap(); private final Map allIdProviders = new HashMap(); public RealmAdapter(KeycloakSession session, RealmEntity realm, InMemoryModel inMemoryModel) { @@ -601,6 +603,36 @@ public class RealmAdapter implements RealmModel { return null; } + @Override + public GroupModel getGroupById(String id) { + GroupModel found = allGroups.get(id); + if (found != null) return found; + return null; + } + + @Override + public List getGroups() { + List list = new LinkedList<>(); + for (GroupAdapter group : allGroups.values()) { + list.add(group); + } + return list; + } + + @Override + public List getTopLevelGroups() { + List list = new LinkedList<>(); + for (GroupAdapter group : allGroups.values()) { + if (group.getParent() == null) list.add(group); + } + return list; + } + + @Override + public boolean removeGroup(GroupModel group) { + return allGroups.remove(group.getId()) != null; + } + @Override public List getDefaultRoles() { return realm.getDefaultRoles(); diff --git a/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java b/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java index 9a3379c610..d0dc92b756 100755 --- a/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java +++ b/model/file/src/main/java/org/keycloak/models/file/adapter/UserAdapter.java @@ -21,6 +21,7 @@ import org.keycloak.models.ClientModel; import static org.keycloak.models.utils.Pbkdf2PasswordEncoder.getSalt; +import org.keycloak.models.GroupModel; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.OTPPolicy; import org.keycloak.models.UserConsentModel; @@ -59,6 +60,7 @@ public class UserAdapter implements UserModel, Comparable { private final RealmModel realm; private final Set allRoles = new HashSet(); + private final Set allGroups = new HashSet(); public UserAdapter(RealmModel realm, UserEntity userEntity, InMemoryModel inMemoryModel) { this.user = userEntity; @@ -467,6 +469,29 @@ public class UserAdapter implements UserModel, Comparable { credentialEntity.setPeriod(credModel.getPeriod()); } + @Override + public Set getGroups() { + return Collections.unmodifiableSet(allGroups); + } + + @Override + public void joinGroup(GroupModel group) { + allGroups.add(group); + + } + + @Override + public void leaveGroup(GroupModel group) { + if (user == null || group == null) return; + allGroups.remove(group); + + } + + @Override + public boolean isMemberOf(GroupModel group) { + return KeycloakModelUtils.isMember(getGroups(), group); + } + @Override public boolean hasRole(RoleModel role) { Set roles = getRoleMappings(); diff --git a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheRealmProvider.java b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheRealmProvider.java old mode 100644 new mode 100755 index b84079f25f..3e45a69f75 --- a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheRealmProvider.java +++ b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheRealmProvider.java @@ -21,9 +21,11 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider { protected Set realmInvalidations = new HashSet(); protected Set appInvalidations = new HashSet(); protected Set roleInvalidations = new HashSet(); + protected Set groupInvalidations = new HashSet(); protected Map managedRealms = new HashMap(); protected Map managedApplications = new HashMap(); protected Map managedRoles = new HashMap(); + protected Map managedGroups = new HashMap(); protected boolean clearAll; @@ -73,6 +75,12 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider { roleInvalidations.add(id); } + @Override + public void registerGroupInvalidation(String id) { + groupInvalidations.add(id); + + } + protected void runInvalidations() { for (String id : realmInvalidations) { cache.invalidateCachedRealmById(id); @@ -80,6 +88,9 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider { for (String id : roleInvalidations) { cache.invalidateRoleById(id); } + for (String id : groupInvalidations) { + cache.invalidateGroupById(id); + } for (String id : appInvalidations) { cache.invalidateCachedApplicationById(id); } @@ -254,6 +265,31 @@ public class DefaultCacheRealmProvider implements CacheRealmProvider { return adapter; } + @Override + public GroupModel getGroupById(String id, RealmModel realm) { + if (!cache.isEnabled()) return getDelegate().getGroupById(id, realm); + CachedGroup cached = cache.getGroup(id); + if (cached != null && !cached.getRealm().equals(realm.getId())) { + cached = null; + } + + if (cached == null) { + GroupModel model = getDelegate().getGroupById(id, realm); + if (model == null) return null; + if (groupInvalidations.contains(id)) return model; + cached = new CachedGroup(realm, model); + cache.addCachedGroup(cached); + + } else if (groupInvalidations.contains(id)) { + return getDelegate().getGroupById(id, realm); + } else if (managedGroups.containsKey(id)) { + return managedGroups.get(id); + } + GroupAdapter adapter = new GroupAdapter(cached, this, session, realm); + managedGroups.put(id, adapter); + return adapter; + } + @Override public ClientModel getClientById(String id, RealmModel realm) { if (!cache.isEnabled()) return getDelegate().getClientById(id, realm); diff --git a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheUserProvider.java b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheUserProvider.java old mode 100644 new mode 100755 index 69fc5cf577..3ea488d4b9 --- a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheUserProvider.java +++ b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultCacheUserProvider.java @@ -197,6 +197,16 @@ public class DefaultCacheUserProvider implements CacheUserProvider { return getDelegate().getUserByFederatedIdentity(socialLink, realm); } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { + return getDelegate().getGroupMembers(realm, group, firstResult, maxResults); + } + + @Override + public List getGroupMembers(RealmModel realm, GroupModel group) { + return getDelegate().getGroupMembers(realm, group); + } + @Override public UserModel getUserByServiceAccountClient(ClientModel client) { return getDelegate().getUserByServiceAccountClient(client); @@ -313,6 +323,11 @@ public class DefaultCacheUserProvider implements CacheUserProvider { public void preRemove(RealmModel realm, RoleModel role) { getDelegate().preRemove(realm, role); } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + getDelegate().preRemove(realm, group); + } + @Override public void preRemove(RealmModel realm, UserFederationProviderModel link) { diff --git a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java new file mode 100755 index 0000000000..4712272be6 --- /dev/null +++ b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java @@ -0,0 +1,236 @@ +package org.keycloak.models.cache.infinispan; + +import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleContainerModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.UserModel; +import org.keycloak.models.cache.CacheRealmProvider; +import org.keycloak.models.cache.CacheUserProvider; +import org.keycloak.models.cache.entities.CachedGroup; +import org.keycloak.models.cache.entities.CachedUser; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class GroupAdapter implements GroupModel { + protected GroupModel updated; + protected CachedGroup cached; + protected CacheRealmProvider cacheSession; + protected KeycloakSession keycloakSession; + protected RealmModel realm; + + public GroupAdapter(CachedGroup cached, CacheRealmProvider cacheSession, KeycloakSession keycloakSession, RealmModel realm) { + this.cached = cached; + this.cacheSession = cacheSession; + this.keycloakSession = keycloakSession; + this.realm = realm; + } + + protected void getDelegateForUpdate() { + if (updated == null) { + cacheSession.registerGroupInvalidation(getId()); + updated = cacheSession.getDelegate().getGroupById(getId(), realm); + if (updated == null) throw new IllegalStateException("Not found in database"); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || !(o instanceof GroupModel)) return false; + + GroupModel that = (GroupModel) o; + + if (!cached.getId().equals(that.getId())) return false; + + return true; + } + + @Override + public int hashCode() { + return cached.getId().hashCode(); + } + + @Override + public String getId() { + if (updated != null) return updated.getId(); + return cached.getId(); + } + + @Override + public String getName() { + if (updated != null) return updated.getName(); + return cached.getName(); + } + + @Override + public void setName(String name) { + getDelegateForUpdate(); + updated.setName(name); + + } + + @Override + public void setSingleAttribute(String name, String value) { + getDelegateForUpdate(); + updated.setSingleAttribute(name, value); + } + + @Override + public void setAttribute(String name, List values) { + getDelegateForUpdate(); + updated.setAttribute(name, values); + } + + @Override + public void removeAttribute(String name) { + getDelegateForUpdate(); + updated.removeAttribute(name); + + } + + @Override + public String getFirstAttribute(String name) { + if (updated != null) return updated.getFirstAttribute(name); + return cached.getAttributes().getFirst(name); + } + + @Override + public List getAttribute(String name) { + List values = cached.getAttributes().get(name); + if (values == null) return null; + return values; + } + + @Override + public Map> getAttributes() { + return cached.getAttributes(); + } + + @Override + public Set getRealmRoleMappings() { + if (updated != null) return updated.getRealmRoleMappings(); + Set roleMappings = getRoleMappings(); + Set realmMappings = new HashSet(); + for (RoleModel role : roleMappings) { + RoleContainerModel container = role.getContainer(); + if (container instanceof RealmModel) { + if (((RealmModel) container).getId().equals(realm.getId())) { + realmMappings.add(role); + } + } + } + return realmMappings; + } + + @Override + public Set getClientRoleMappings(ClientModel app) { + if (updated != null) return updated.getClientRoleMappings(app); + Set roleMappings = getRoleMappings(); + Set appMappings = new HashSet(); + for (RoleModel role : roleMappings) { + RoleContainerModel container = role.getContainer(); + if (container instanceof ClientModel) { + if (((ClientModel) container).getId().equals(app.getId())) { + appMappings.add(role); + } + } + } + return appMappings; + } + + @Override + public boolean hasRole(RoleModel role) { + if (updated != null) return updated.hasRole(role); + if (cached.getRoleMappings().contains(role.getId())) return true; + + Set mappings = getRoleMappings(); + for (RoleModel mapping: mappings) { + if (mapping.hasRole(role)) return true; + } + return false; + } + + @Override + public void grantRole(RoleModel role) { + getDelegateForUpdate(); + updated.grantRole(role); + } + + @Override + public Set getRoleMappings() { + if (updated != null) return updated.getRoleMappings(); + Set roles = new HashSet(); + for (String id : cached.getRoleMappings()) { + RoleModel roleById = keycloakSession.realms().getRoleById(id, realm); + if (roleById == null) { + // chance that role was removed, so just delegate to persistence and get user invalidated + getDelegateForUpdate(); + return updated.getRoleMappings(); + } + roles.add(roleById); + + } + return roles; + } + + @Override + public void deleteRoleMapping(RoleModel role) { + getDelegateForUpdate(); + updated.deleteRoleMapping(role); + } + + @Override + public GroupModel getParent() { + if (updated != null) return updated.getParent(); + if (cached.getParentId() == null) return null; + return keycloakSession.realms().getGroupById(cached.getParentId(), realm); + } + + @Override + public Set getSubGroups() { + if (updated != null) return updated.getSubGroups(); + Set subGroups = new HashSet<>(); + for (String id : cached.getSubGroups()) { + GroupModel subGroup = keycloakSession.realms().getGroupById(id, realm); + if (subGroup == null) { + // chance that role was removed, so just delegate to persistence and get user invalidated + getDelegateForUpdate(); + return updated.getSubGroups(); + + } + subGroups.add(subGroup); + } + return subGroups; + } + + @Override + public void setParent(GroupModel group) { + getDelegateForUpdate(); + updated.setParent(group); + + } + + @Override + public void addChild(GroupModel subGroup) { + getDelegateForUpdate(); + updated.addChild(subGroup); + + } + + @Override + public void removeChild(GroupModel subGroup) { + getDelegateForUpdate(); + updated.removeChild(subGroup); + } +} diff --git a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanRealmCache.java b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanRealmCache.java index 07554a889e..a5239fbcf5 100755 --- a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanRealmCache.java +++ b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanRealmCache.java @@ -4,6 +4,7 @@ import org.infinispan.Cache; import org.jboss.logging.Logger; import org.keycloak.models.cache.RealmCache; import org.keycloak.models.cache.entities.CachedClient; +import org.keycloak.models.cache.entities.CachedGroup; import org.keycloak.models.cache.entities.CachedRealm; import org.keycloak.models.cache.entities.CachedRole; @@ -101,12 +102,49 @@ public class InfinispanRealmCache implements RealmCache { cache.remove(id); } + @Override + public CachedGroup getGroup(String id) { + if (!enabled) return null; + return get(id, CachedGroup.class); + } + + @Override + public void invalidateGroup(CachedGroup role) { + logger.tracev("Removing group {0}", role.getId()); + cache.remove(role.getId()); + + } + + @Override + public void addCachedGroup(CachedGroup role) { + if (!enabled) return; + logger.tracev("Adding group {0}", role.getId()); + cache.put(role.getId(), role); + + } + + @Override + public void invalidateCachedGroupById(String id) { + logger.tracev("Removing group {0}", id); + cache.remove(id); + + } + + @Override + public void invalidateGroupById(String id) { + logger.tracev("Removing group {0}", id); + cache.remove(id); + + } + @Override public CachedRole getRole(String id) { if (!enabled) return null; return get(id, CachedRole.class); } + + @Override public void invalidateRole(CachedRole role) { logger.tracev("Removing role {0}", role.getId()); diff --git a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java index 13ec945ee7..14c111d445 100755 --- a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java +++ b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java @@ -1262,4 +1262,42 @@ public class RealmAdapter implements RealmModel { if (updated != null) return updated.getRequiredActionProviderByAlias(alias); return cached.getRequiredActionProvidersByAlias().get(alias); } + + @Override + public GroupModel getGroupById(String id) { + if (updated != null) return updated.getGroupById(id); + return cacheSession.getGroupById(id, this); + } + + @Override + public List getGroups() { + if (updated != null) return updated.getGroups(); + if (cached.getGroups().isEmpty()) return null; + List list = new LinkedList<>(); + for (String id : cached.getGroups()) { + GroupModel group = cacheSession.getGroupById(id, this); + if (group == null) continue; + list.add(group); + } + return list; + } + + @Override + public List getTopLevelGroups() { + List all = getGroups(); + Iterator it = all.iterator(); + while (it.hasNext()) { + GroupModel group = it.next(); + if (group.getParent() != null) { + it.remove(); + } + } + return all; + } + + @Override + public boolean removeGroup(GroupModel group) { + getDelegateForUpdate(); + return updated.removeGroup(group); + } } diff --git a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java index 5a74b01a35..7113fde9a5 100755 --- a/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java +++ b/model/invalidation-cache/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java @@ -317,6 +317,44 @@ public class UserAdapter implements UserModel { updated.deleteRoleMapping(role); } + @Override + public Set getGroups() { + if (updated != null) return updated.getGroups(); + Set groups = new HashSet(); + for (String id : cached.getRoleMappings()) { + GroupModel groupModel = keycloakSession.realms().getGroupById(id, realm); + if (groupModel == null) { + // chance that role was removed, so just delete to persistence and get user invalidated + getDelegateForUpdate(); + return updated.getGroups(); + } + groups.add(groupModel); + + } + return groups; + } + + @Override + public void joinGroup(GroupModel group) { + getDelegateForUpdate(); + updated.joinGroup(group); + + } + + @Override + public void leaveGroup(GroupModel group) { + getDelegateForUpdate(); + updated.leaveGroup(group); + } + + @Override + public boolean isMemberOf(GroupModel group) { + if (updated != null) return updated.isMemberOf(group); + if (cached.getGroups().contains(group.getId())) return true; + Set roles = getGroups(); + return KeycloakModelUtils.isMember(roles, group); + } + @Override public void addConsent(UserConsentModel consent) { getDelegateForUpdate(); @@ -348,4 +386,5 @@ public class UserAdapter implements UserModel { getDelegateForUpdate(); return updated.revokeConsentForClient(clientId); } + } diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java index 4aab371699..26ad12de2d 100755 --- a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/CacheRealmProvider.java @@ -17,4 +17,6 @@ public interface CacheRealmProvider extends RealmProvider { void registerApplicationInvalidation(String id); void registerRoleInvalidation(String id); + + void registerGroupInvalidation(String id); } diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmCache.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmCache.java index 9c895c376f..df74b536af 100755 --- a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmCache.java +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/RealmCache.java @@ -1,6 +1,7 @@ package org.keycloak.models.cache; import org.keycloak.models.cache.entities.CachedClient; +import org.keycloak.models.cache.entities.CachedGroup; import org.keycloak.models.cache.entities.CachedRealm; import org.keycloak.models.cache.entities.CachedRole; @@ -39,6 +40,16 @@ public interface RealmCache { void invalidateRoleById(String id); + CachedGroup getGroup(String id); + + void invalidateGroup(CachedGroup role); + + void addCachedGroup(CachedGroup role); + + void invalidateCachedGroupById(String id); + + void invalidateGroupById(String id); + boolean isEnabled(); void setEnabled(boolean enabled); diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedGroup.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedGroup.java new file mode 100755 index 0000000000..7f16e948de --- /dev/null +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedGroup.java @@ -0,0 +1,74 @@ +package org.keycloak.models.cache.entities; + +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.models.GroupModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.UserCredentialValueModel; +import org.keycloak.models.UserModel; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class CachedGroup implements Serializable { + private String id; + private String realm; + private String name; + private String parentId; + private MultivaluedHashMap attributes = new MultivaluedHashMap<>(); + private Set roleMappings = new HashSet<>(); + private Set subGroups = new HashSet<>(); + + public CachedGroup(RealmModel realm, GroupModel group) { + this.id = group.getId(); + this.realm = realm.getId(); + this.name = group.getName(); + if (group.getParent() != null) this.parentId = group.getParent().getId(); + + this.attributes.putAll(group.getAttributes()); + for (RoleModel role : group.getRoleMappings()) { + roleMappings.add(role.getId()); + } + Set subGroups1 = group.getSubGroups(); + if (subGroups1 != null) { + for (GroupModel subGroup : subGroups1) { + subGroups.add(subGroup.getId()); + } + } + } + + public String getId() { + return id; + } + + public String getRealm() { + return realm; + } + + public MultivaluedHashMap getAttributes() { + return attributes; + } + + public Set getRoleMappings() { + return roleMappings; + } + + public String getName() { + return name; + } + + public String getParentId() { + return parentId; + } + + public Set getSubGroups() { + return subGroups; + } +} diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java index 18b8540e4d..604d7fa825 100755 --- a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedRealm.java @@ -5,6 +5,7 @@ import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationFlowModel; import org.keycloak.models.AuthenticatorConfigModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.OTPPolicy; @@ -106,6 +107,7 @@ public class CachedRealm implements Serializable { protected Set adminEnabledEventOperations = new HashSet(); protected boolean adminEventsDetailsEnabled; private List defaultRoles = new LinkedList(); + private Set groups = new HashSet(); private Map realmRoles = new HashMap(); private Map clients = new HashMap(); private boolean internationalizationEnabled; @@ -216,6 +218,9 @@ public class CachedRealm implements Serializable { executionsById.put(execution.getId(), execution); } } + for (GroupModel group : model.getGroups()) { + groups.add(group.getId()); + } for (AuthenticatorConfigModel authenticator : model.getAuthenticatorConfigs()) { authenticatorConfigs.put(authenticator.getId(), authenticator); } @@ -507,4 +512,8 @@ public class CachedRealm implements Serializable { public AuthenticationFlowModel getClientAuthenticationFlow() { return clientAuthenticationFlow; } + + public Set getGroups() { + return groups; + } } diff --git a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedUser.java b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedUser.java index 0b5fc78496..fcd36c1b27 100755 --- a/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedUser.java +++ b/model/invalidation-cache/model-adapters/src/main/java/org/keycloak/models/cache/entities/CachedUser.java @@ -1,5 +1,6 @@ package org.keycloak.models.cache.entities; +import org.keycloak.models.GroupModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialValueModel; @@ -33,6 +34,7 @@ public class CachedUser implements Serializable { private MultivaluedHashMap attributes = new MultivaluedHashMap<>(); private Set requiredActions = new HashSet<>(); private Set roleMappings = new HashSet<>(); + private Set groups = new HashSet<>(); public CachedUser(RealmModel realm, UserModel user) { this.id = user.getId(); @@ -53,6 +55,12 @@ public class CachedUser implements Serializable { for (RoleModel role : user.getRoleMappings()) { roleMappings.add(role.getId()); } + Set groupMappings = user.getGroups(); + if (groupMappings != null) { + for (GroupModel group : groupMappings) { + groups.add(group.getId()); + } + } } public String getId() { @@ -118,4 +126,8 @@ public class CachedUser implements Serializable { public String getServiceAccountClientLink() { return serviceAccountClientLink; } + + public Set getGroups() { + return groups; + } } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/GroupAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/GroupAdapter.java new file mode 100755 index 0000000000..0e2e64407a --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/GroupAdapter.java @@ -0,0 +1,320 @@ +package org.keycloak.models.jpa; + +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.common.util.Time; +import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; +import org.keycloak.models.ModelDuplicateException; +import org.keycloak.models.ModelException; +import org.keycloak.models.OTPPolicy; +import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.ProtocolMapperModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleContainerModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.UserConsentModel; +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.GroupAttributeEntity; +import org.keycloak.models.jpa.entities.GroupEntity; +import org.keycloak.models.jpa.entities.GroupRoleMappingEntity; +import org.keycloak.models.jpa.entities.RoleEntity; +import org.keycloak.models.jpa.entities.UserAttributeEntity; +import org.keycloak.models.jpa.entities.UserConsentEntity; +import org.keycloak.models.jpa.entities.UserConsentProtocolMapperEntity; +import org.keycloak.models.jpa.entities.UserConsentRoleEntity; +import org.keycloak.models.jpa.entities.UserEntity; +import org.keycloak.models.jpa.entities.UserRequiredActionEntity; +import org.keycloak.models.jpa.entities.UserRoleMappingEntity; +import org.keycloak.models.utils.KeycloakModelUtils; +import org.keycloak.models.utils.Pbkdf2PasswordEncoder; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.keycloak.models.utils.Pbkdf2PasswordEncoder.getSalt; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class GroupAdapter implements GroupModel { + + protected GroupEntity group; + protected EntityManager em; + protected RealmModel realm; + + public GroupAdapter(RealmModel realm, EntityManager em, GroupEntity group) { + this.em = em; + this.group = group; + this.realm = realm; + } + + public GroupEntity getGroup() { + return group; + } + + @Override + public String getId() { + return group.getId(); + } + + @Override + public String getName() { + return group.getName(); + } + + @Override + public void setName(String name) { + group.setName(name); + } + + @Override + public GroupModel getParent() { + GroupEntity parent = group.getParent(); + if (parent == null) return null; + return realm.getGroupById(parent.getId()); + } + + public static GroupEntity toEntity(GroupModel model, EntityManager em) { + if (model instanceof GroupAdapter) { + return ((GroupAdapter)model).getGroup(); + } + return em.getReference(GroupEntity.class, model.getId()); + } + + @Override + public void setParent(GroupModel group) { + GroupEntity parent = toEntity(group, em); + group.setParent(group); + } + + @Override + public void addChild(GroupModel subGroup) { + subGroup.setParent(this); + + } + + @Override + public void removeChild(GroupModel subGroup) { + subGroup.setParent(null); + + } + + @Override + public Set getSubGroups() { + TypedQuery query = em.createNamedQuery("getGroupIdsByParent", String.class); + query.setParameter("parent", group); + List ids = query.getResultList(); + Set set = new HashSet<>(); + for (String id : ids) { + GroupModel subGroup = realm.getGroupById(id); + if (subGroup == null) continue; + set.add(subGroup); + } + return set; + } + + @Override + public void setSingleAttribute(String name, String value) { + boolean found = false; + List toRemove = new ArrayList<>(); + for (GroupAttributeEntity attr : group.getAttributes()) { + if (attr.getName().equals(name)) { + if (!found) { + attr.setValue(value); + found = true; + } else { + toRemove.add(attr); + } + } + } + + for (GroupAttributeEntity attr : toRemove) { + em.remove(attr); + group.getAttributes().remove(attr); + } + + if (found) { + return; + } + + persistAttributeValue(name, value); + } + + @Override + public void setAttribute(String name, List values) { + // Remove all existing + removeAttribute(name); + + // Put all new + for (String value : values) { + persistAttributeValue(name, value); + } + } + + private void persistAttributeValue(String name, String value) { + GroupAttributeEntity attr = new GroupAttributeEntity(); + attr.setId(KeycloakModelUtils.generateId()); + attr.setName(name); + attr.setValue(value); + attr.setGroup(group); + em.persist(attr); + group.getAttributes().add(attr); + } + + @Override + public void removeAttribute(String name) { + Iterator it = group.getAttributes().iterator(); + while (it.hasNext()) { + GroupAttributeEntity attr = it.next(); + if (attr.getName().equals(name)) { + it.remove(); + em.remove(attr); + } + } + } + + @Override + public String getFirstAttribute(String name) { + for (GroupAttributeEntity attr : group.getAttributes()) { + if (attr.getName().equals(name)) { + return attr.getValue(); + } + } + return null; + } + + @Override + public List getAttribute(String name) { + List result = new ArrayList<>(); + for (GroupAttributeEntity attr : group.getAttributes()) { + if (attr.getName().equals(name)) { + result.add(attr.getValue()); + } + } + return result; + } + + @Override + public Map> getAttributes() { + MultivaluedHashMap result = new MultivaluedHashMap<>(); + for (GroupAttributeEntity attr : group.getAttributes()) { + result.add(attr.getName(), attr.getValue()); + } + return result; + } + + @Override + public boolean hasRole(RoleModel role) { + Set roles = getRoleMappings(); + return KeycloakModelUtils.hasRole(roles, role); + } + + protected TypedQuery getGroupRoleMappingEntityTypedQuery(RoleModel role) { + TypedQuery query = em.createNamedQuery("groupHasRole", GroupRoleMappingEntity.class); + query.setParameter("group", getGroup()); + query.setParameter("roleId", role.getId()); + return query; + } + + @Override + public void grantRole(RoleModel role) { + if (hasRole(role)) return; + GroupRoleMappingEntity entity = new GroupRoleMappingEntity(); + entity.setGroup(getGroup()); + entity.setRoleId(role.getId()); + em.persist(entity); + em.flush(); + em.detach(entity); + } + + @Override + public Set getRealmRoleMappings() { + Set roleMappings = getRoleMappings(); + + Set realmRoles = new HashSet(); + for (RoleModel role : roleMappings) { + RoleContainerModel container = role.getContainer(); + if (container instanceof RealmModel) { + realmRoles.add(role); + } + } + return realmRoles; + } + + + @Override + public Set getRoleMappings() { + // we query ids only as the role might be cached and following the @ManyToOne will result in a load + // even if we're getting just the id. + TypedQuery query = em.createNamedQuery("groupRoleMappingIds", String.class); + query.setParameter("group", getGroup()); + List ids = query.getResultList(); + Set roles = new HashSet(); + for (String roleId : ids) { + RoleModel roleById = realm.getRoleById(roleId); + if (roleById == null) continue; + roles.add(roleById); + } + return roles; + } + + @Override + public void deleteRoleMapping(RoleModel role) { + if (group == null || role == null) return; + + TypedQuery query = getGroupRoleMappingEntityTypedQuery(role); + List results = query.getResultList(); + if (results.size() == 0) return; + for (GroupRoleMappingEntity entity : results) { + em.remove(entity); + } + em.flush(); + } + + @Override + public Set getClientRoleMappings(ClientModel app) { + Set roleMappings = getRoleMappings(); + + Set roles = new HashSet(); + for (RoleModel role : roleMappings) { + RoleContainerModel container = role.getContainer(); + if (container instanceof ClientModel) { + ClientModel appModel = (ClientModel)container; + if (appModel.getId().equals(app.getId())) { + roles.add(role); + } + } + } + return roles; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || !(o instanceof UserModel)) return false; + + UserModel that = (UserModel) o; + return that.getId().equals(getId()); + } + + @Override + public int hashCode() { + return getId().hashCode(); + } + + + +} diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java index b9229bbb11..c5396cb50b 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java @@ -2,11 +2,13 @@ package org.keycloak.models.jpa; import org.keycloak.migration.MigrationModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RealmProvider; import org.keycloak.models.RoleModel; import org.keycloak.models.jpa.entities.ClientEntity; +import org.keycloak.models.jpa.entities.GroupEntity; import org.keycloak.models.jpa.entities.RealmEntity; import org.keycloak.models.jpa.entities.RoleEntity; import org.keycloak.models.utils.KeycloakModelUtils; @@ -117,6 +119,14 @@ public class JpaRealmProvider implements RealmProvider { return new RoleAdapter(realm, em, entity); } + @Override + public GroupModel getGroupById(String id, RealmModel realm) { + GroupEntity groupEntity = em.find(GroupEntity.class, id); + if (groupEntity == null) return null; + if (groupEntity.getRealm().getId().equals(realm.getId())) return null; + return new GroupAdapter(realm, em, groupEntity); + } + @Override public ClientModel getClientById(String id, RealmModel realm) { ClientEntity app = em.find(ClientEntity.class, id); diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java index d4d533a9dc..b643bb6d0c 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java @@ -3,6 +3,7 @@ package org.keycloak.models.jpa; import org.keycloak.models.ClientModel; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.FederatedIdentityModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; @@ -169,6 +170,8 @@ public class JpaUserProvider implements UserProvider { .setParameter("realmId", realm.getId()).executeUpdate(); num = em.createNamedQuery("deleteUsersByRealm") .setParameter("realmId", realm.getId()).executeUpdate(); + num = em.createNamedQuery("deleteUserGroupMembershipByRealm") + .setParameter("realmId", realm.getId()).executeUpdate(); } @Override @@ -219,6 +222,25 @@ public class JpaUserProvider implements UserProvider { .executeUpdate(); } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group) { + TypedQuery query = em.createNamedQuery("groupMembership", UserEntity.class); + query.setParameter("groupId", group.getId()); + List results = query.getResultList(); + + List users = new ArrayList(); + for (UserEntity user : results) { + users.add(new UserAdapter(realm, em, user)); + } + return users; + } + + @Override + public void preRemove(RealmModel realm, GroupModel group) { + em.createNamedQuery("deleteUserGroupMembershipsByGroup").setParameter("groupId", group.getId()).executeUpdate(); + + } + @Override public UserModel getUserById(String id, RealmModel realm) { TypedQuery query = em.createNamedQuery("getRealmUserById", UserEntity.class); @@ -318,6 +340,25 @@ public class JpaUserProvider implements UserProvider { return users; } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { + TypedQuery query = em.createNamedQuery("groupMembership", UserEntity.class); + query.setParameter("groupId", group.getId()); + if (firstResult != -1) { + query.setFirstResult(firstResult); + } + if (maxResults != -1) { + query.setMaxResults(maxResults); + } + List results = query.getResultList(); + + List users = new ArrayList(); + for (UserEntity user : results) { + users.add(new UserAdapter(realm, em, user)); + } + return users; + } + @Override public List searchForUser(String search, RealmModel realm) { return searchForUser(search, realm, -1, -1); diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java index 86f4490a03..385ad7e872 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java @@ -6,6 +6,7 @@ import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationFlowModel; import org.keycloak.models.AuthenticatorConfigModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; @@ -24,6 +25,7 @@ import org.keycloak.models.jpa.entities.AuthenticationExecutionEntity; import org.keycloak.models.jpa.entities.AuthenticationFlowEntity; import org.keycloak.models.jpa.entities.AuthenticatorConfigEntity; import org.keycloak.models.jpa.entities.ClientEntity; +import org.keycloak.models.jpa.entities.GroupEntity; import org.keycloak.models.jpa.entities.IdentityProviderEntity; import org.keycloak.models.jpa.entities.IdentityProviderMapperEntity; import org.keycloak.models.jpa.entities.RealmAttributeEntity; @@ -1944,4 +1946,60 @@ public class RealmAdapter implements RealmModel { } return null; } + + @Override + public GroupModel getGroupById(String id) { + GroupEntity groupEntity = em.find(GroupEntity.class, id); + if (groupEntity == null) return null; + if (groupEntity.getRealm().getId().equals(getId())) return null; + return new GroupAdapter(this, em, groupEntity); + } + + @Override + public List getGroups() { + List list = new LinkedList<>(); + Collection groups = realm.getGroups(); + if (groups == null) return list; + for (GroupEntity entity : groups) { + list.add(new GroupAdapter(this, em, entity)); + } + return list; + } + + @Override + public List getTopLevelGroups() { + List all = getGroups(); + Iterator it = all.iterator(); + while (it.hasNext()) { + GroupModel group = it.next(); + if (group.getParent() != null) { + it.remove(); + } + } + return all; + } + + @Override + public boolean removeGroup(GroupModel group) { + if (group == null) { + return false; + } + GroupEntity groupEntity = GroupAdapter.toEntity(group, em); + if (!groupEntity.getRealm().getId().equals(getId())) { + return false; + } + for (GroupModel subGroup : group.getSubGroups()) { + removeGroup(subGroup); + } + + + session.users().preRemove(this, group); + realm.getGroups().remove(groupEntity); + em.createNamedQuery("deleteGroupAttributesByGroup").setParameter("group", group).executeUpdate(); + em.createNamedQuery("deleteGroupRoleMappingsByGroup").setParameter("group", group).executeUpdate(); + em.remove(groupEntity); + return true; + + + } } \ No newline at end of file diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java index b370886ccb..5246890979 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java @@ -1,6 +1,7 @@ package org.keycloak.models.jpa; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.OTPPolicy; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.UserConsentModel; @@ -19,6 +20,7 @@ import org.keycloak.models.jpa.entities.UserConsentProtocolMapperEntity; import org.keycloak.models.jpa.entities.UserConsentRoleEntity; import org.keycloak.models.jpa.entities.UserAttributeEntity; import org.keycloak.models.jpa.entities.UserEntity; +import org.keycloak.models.jpa.entities.UserGroupMembershipEntity; import org.keycloak.models.jpa.entities.UserRequiredActionEntity; import org.keycloak.models.jpa.entities.UserRoleMappingEntity; import org.keycloak.models.utils.KeycloakModelUtils; @@ -485,6 +487,63 @@ public class UserAdapter implements UserModel { em.flush(); } + + @Override + public Set getGroups() { + // we query ids only as the group might be cached and following the @ManyToOne will result in a load + // even if we're getting just the id. + TypedQuery query = em.createNamedQuery("userGroupIds", String.class); + query.setParameter("user", getUser()); + List ids = query.getResultList(); + Set groups = new HashSet<>(); + for (String groupId : ids) { + GroupModel group = realm.getGroupById(groupId); + if (group == null) continue; + groups.add(group); + } + return groups; + } + + @Override + public void joinGroup(GroupModel group) { + if (isMemberOf(group)) return; + UserGroupMembershipEntity entity = new UserGroupMembershipEntity(); + entity.setUser(getUser()); + entity.setGroupId(group.getId()); + em.persist(entity); + em.flush(); + em.detach(entity); + + } + + @Override + public void leaveGroup(GroupModel group) { + if (user == null || group == null) return; + + TypedQuery query = getUserGroupMappingQuery(group); + List results = query.getResultList(); + if (results.size() == 0) return; + for (UserGroupMembershipEntity entity : results) { + em.remove(entity); + } + em.flush(); + + } + + @Override + public boolean isMemberOf(GroupModel group) { + Set roles = getGroups(); + return KeycloakModelUtils.isMember(roles, group); + } + + protected TypedQuery getUserGroupMappingQuery(GroupModel group) { + TypedQuery query = em.createNamedQuery("userMemberOf", UserGroupMembershipEntity.class); + query.setParameter("user", getUser()); + query.setParameter("groupId", group.getId()); + return query; + } + + @Override public boolean hasRole(RoleModel role) { Set roles = getRoleMappings(); diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java new file mode 100755 index 0000000000..8ee79e093d --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java @@ -0,0 +1,70 @@ +package org.keycloak.models.jpa.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +@NamedQueries({ + @NamedQuery(name="getGroupAttributesByNameAndValue", query="select attr from GroupAttributeEntity attr where attr.name = :name and attr.value = :value"), + @NamedQuery(name="deleteGroupAttributesByGroup", query="delete from GroupAttributeEntity attr where attr.group = :group"), + @NamedQuery(name="deleteGroupAttributesByRealm", query="delete from GroupAttributeEntity attr where attr.group IN (select u from GroupEntity u where u.realmId=:realmId)") +}) +@Table(name="USER_ATTRIBUTE") +@Entity +public class GroupAttributeEntity { + + @Id + @Column(name="ID", length = 36) + protected String id; + + @ManyToOne(fetch= FetchType.LAZY) + @JoinColumn(name = "GROUP_ID") + protected GroupEntity group; + + @Column(name = "NAME") + protected String name; + @Column(name = "VALUE") + protected String value; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public GroupEntity getGroup() { + return group; + } + + public void setGroup(GroupEntity group) { + this.group = group; + } +} diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java new file mode 100755 index 0000000000..b944379cea --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java @@ -0,0 +1,109 @@ +package org.keycloak.models.jpa.entities; + +import org.keycloak.models.utils.KeycloakModelUtils; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import java.util.ArrayList; +import java.util.Collection; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +@NamedQueries({ + @NamedQuery(name="getAllGroupsByRealm", query="select u from GroupEntity u where u.realmId = :realmId order by u.name"), + @NamedQuery(name="getGroupById", query="select u from GroupEntity u where u.id = :id and u.realmId = :realmId"), + @NamedQuery(name="getGroupIdsByParent", query="select u.id from GroupEntity u where u.parent = :parent"), + @NamedQuery(name="getGroupByName", query="select u from GroupEntity u where u.name = :name and u.realmId = :realmId"), + @NamedQuery(name="getGroupCount", query="select count(u) from GroupEntity u where u.realmId = :realmId"), + @NamedQuery(name="deleteGroupsByRealm", query="delete from GroupEntity u where u.realmId = :realmId") +}) +@Entity +@Table(name="GROUP_ENTITY") +public class GroupEntity { + @Id + @Column(name="ID", length = 36) + protected String id; + + @Column(name = "NAME") + protected String name; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "PARENT_GROUP") + private GroupEntity parent; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "REALM") + private RealmEntity realm; + + @OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true, mappedBy="group") + protected Collection attributes = new ArrayList(); + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Collection getAttributes() { + return attributes; + } + + public void setAttributes(Collection attributes) { + this.attributes = attributes; + } + + 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; + } + + public GroupEntity getParent() { + return parent; + } + + public void setParent(GroupEntity parent) { + this.parent = parent; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + GroupEntity that = (GroupEntity) o; + + if (!id.equals(that.id)) return false; + + return true; + } + + @Override + public int hashCode() { + return id.hashCode(); + } +} diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java new file mode 100755 index 0000000000..86db554f71 --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java @@ -0,0 +1,101 @@ +package org.keycloak.models.jpa.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +@NamedQueries({ + @NamedQuery(name="groupHasRole", query="select m from GroupRoleMappingEntity m where m.group = :group and m.roleId = :roleId"), + @NamedQuery(name="groupRoleMappings", query="select m from GroupRoleMappingEntity m where m.group = :group"), + @NamedQuery(name="groupRoleMappingIds", query="select m.roleId from GroupRoleMappingEntity m where m.group = :group"), + @NamedQuery(name="deleteGroupRoleMappingsByRealm", query="delete from GroupRoleMappingEntity mapping where mapping.group IN (select u from GroupEntity u where u.realmId=:realmId)"), + @NamedQuery(name="deleteGroupRoleMappingsByRole", query="delete from GroupRoleMappingEntity m where m.roleId = :roleId"), + @NamedQuery(name="deleteGroupRoleMappingsByGroup", query="delete from GroupRoleMappingEntity m where m.group = :group") + +}) +@Table(name="GROUP_ROLE_MAPPING") +@Entity +@IdClass(GroupRoleMappingEntity.Key.class) +public class GroupRoleMappingEntity { + + @Id + @ManyToOne(fetch= FetchType.LAZY) + @JoinColumn(name="GROUP_ID") + protected GroupEntity group; + + @Id + @Column(name = "ROLE_ID") + protected String roleId; + + public GroupEntity getGroup() { + return group; + } + + public void setGroup(GroupEntity group) { + this.group = group; + } + + public String getRoleId() { + return roleId; + } + + public void setRoleId(String roleId) { + this.roleId = roleId; + } + + + public static class Key implements Serializable { + + protected GroupEntity group; + + protected String roleId; + + public Key() { + } + + public Key(GroupEntity group, String roleId) { + this.group = group; + this.roleId = roleId; + } + + public GroupEntity getGroup() { + return group; + } + + public String getRoleId() { + return roleId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Key key = (Key) o; + + if (!roleId.equals(key.roleId)) return false; + if (!group.equals(key.group)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = group.hashCode(); + result = 31 * result + roleId.hashCode(); + return result; + } + } +} diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java index bf5b339577..95b75d979e 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/RealmEntity.java @@ -133,6 +133,9 @@ public class RealmEntity { @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") Collection roles = new ArrayList(); + @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "realm") + Collection groups = new ArrayList(); + @ElementCollection @MapKeyColumn(name="NAME") @Column(name="VALUE") @@ -718,5 +721,21 @@ public class RealmEntity { public void setClientAuthenticationFlow(String clientAuthenticationFlow) { this.clientAuthenticationFlow = clientAuthenticationFlow; } + + public Collection getGroups() { + return groups; + } + + public void setGroups(Collection groups) { + this.groups = groups; + } + + public void addGroup(GroupEntity group) { + if (groups == null) { + groups = new ArrayList(); + } + groups.add(group); + } + } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserGroupMembershipEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserGroupMembershipEntity.java new file mode 100755 index 0000000000..76b7797dd0 --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserGroupMembershipEntity.java @@ -0,0 +1,102 @@ +package org.keycloak.models.jpa.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; +import java.io.Serializable; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +@NamedQueries({ + @NamedQuery(name="userMemberOf", query="select m from UserGroupMembershipEntity m where m.user = :user and m.groupId = :groupId"), + @NamedQuery(name="userGroupMembership", query="select m from UserGroupMembershipEntity m where m.user = :user"), + @NamedQuery(name="groupMembership", query="select g.user from UserGroupMembershipEntity g where g.groupId = :groupId"), + @NamedQuery(name="userGroupIds", query="select m.groupId from UserGroupMembershipEntity m where m.user = :user"), + @NamedQuery(name="deleteUserGroupMembershipByRealm", query="delete from UserGroupMembershipEntity mapping where mapping.user IN (select u from UserEntity u where u.realmId=:realmId)"), + @NamedQuery(name="deleteUserGroupMembershipsByRealmAndLink", query="delete from UserGroupMembershipEntity mapping where mapping.user IN (select u from UserEntity u where u.realmId=:realmId and u.federationLink=:link)"), + @NamedQuery(name="deleteUserGroupMembershipsByGroup", query="delete from UserGroupMembershipEntity m where m.groupId = :groupId"), + @NamedQuery(name="deleteUserGroupMembershipsByUser", query="delete from UserGroupMembershipEntity m where m.user = :user") + +}) +@Table(name="USER_GROUP_MEMBERSHIP") +@Entity +@IdClass(UserGroupMembershipEntity.Key.class) +public class UserGroupMembershipEntity { + + @Id + @ManyToOne(fetch= FetchType.LAZY) + @JoinColumn(name="USER_ID") + protected UserEntity user; + + @Id + @Column(name = "GROUP_ID") + protected String groupId; + + public UserEntity getUser() { + return user; + } + + public void setUser(UserEntity user) { + this.user = user; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public static class Key implements Serializable { + + protected UserEntity user; + + protected String groupId; + + public Key() { + } + + public Key(UserEntity user, String groupId) { + this.user = user; + this.groupId = groupId; + } + + public UserEntity getUser() { + return user; + } + + public String getGroupId() { + return groupId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Key key = (Key) o; + + if (!groupId.equals(key.groupId)) return false; + if (!user.equals(key.user)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = user.hashCode(); + result = 31 * result + groupId.hashCode(); + return result; + } + } +} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java new file mode 100755 index 0000000000..6fdb97b505 --- /dev/null +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/GroupAdapter.java @@ -0,0 +1,225 @@ +package org.keycloak.models.mongo.keycloak.adapters; + +import com.mongodb.DBObject; +import com.mongodb.QueryBuilder; +import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; +import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RoleContainerModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity; +import org.keycloak.models.mongo.keycloak.entities.MongoGroupEntity; +import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity; +import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; +import org.keycloak.models.mongo.utils.MongoModelUtils; +import org.keycloak.models.utils.KeycloakModelUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * + * @author Marek Posolda + */ +public class GroupAdapter extends AbstractMongoAdapter implements GroupModel { + + private final MongoGroupEntity group; + private RealmModel realm; + private KeycloakSession session; + + public GroupAdapter(KeycloakSession session, RealmModel realm, MongoGroupEntity group, MongoStoreInvocationContext invContext) { + super(invContext); + this.group = group; + this.realm = realm; + this.session = session; + } + + @Override + public String getId() { + return group.getId(); + } + + @Override + public String getName() { + return group.getName(); + } + + @Override + public void setName(String name) { + group.setName(name); + updateGroup(); + } + + protected void updateGroup() { + super.updateMongoEntity(); + } + + @Override + public MongoGroupEntity getMongoEntity() { + return group; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || !(o instanceof GroupModel)) return false; + + GroupModel that = (GroupModel) o; + return that.getId().equals(getId()); + } + + @Override + public int hashCode() { + return getId().hashCode(); + } + + @Override + public void setSingleAttribute(String name, String value) { + if (group.getAttributes() == null) { + group.setAttributes(new HashMap>()); + } + + List attrValues = new ArrayList<>(); + attrValues.add(value); + group.getAttributes().put(name, attrValues); + updateGroup(); + } + + @Override + public void setAttribute(String name, List values) { + if (group.getAttributes() == null) { + group.setAttributes(new HashMap>()); + } + + group.getAttributes().put(name, values); + updateGroup(); + } + + @Override + public void removeAttribute(String name) { + if (group.getAttributes() == null) return; + + group.getAttributes().remove(name); + updateGroup(); + } + + @Override + public String getFirstAttribute(String name) { + if (group.getAttributes()==null) return null; + + List attrValues = group.getAttributes().get(name); + return (attrValues==null || attrValues.isEmpty()) ? null : attrValues.get(0); + } + + @Override + public List getAttribute(String name) { + if (group.getAttributes()==null) return Collections.emptyList(); + List attrValues = group.getAttributes().get(name); + return (attrValues == null) ? Collections.emptyList() : Collections.unmodifiableList(attrValues); + } + + @Override + public Map> getAttributes() { + return group.getAttributes()==null ? Collections.>emptyMap() : Collections.unmodifiableMap((Map) group.getAttributes()); + } + + @Override + public boolean hasRole(RoleModel role) { + Set roles = getRoleMappings(); + return KeycloakModelUtils.hasRole(roles, role); + } + + @Override + public void grantRole(RoleModel role) { + getMongoStore().pushItemToList(group, "roleIds", role.getId(), true, invocationContext); + } + + @Override + public Set getRoleMappings() { + if (group.getRoleIds() == null || group.getRoleIds().isEmpty()) return Collections.EMPTY_SET; + Set roles = new HashSet<>(); + for (String id : group.getRoleIds()) { + roles.add(realm.getRoleById(id)); + } + return roles; + } + + @Override + public Set getRealmRoleMappings() { + Set allRoles = getRoleMappings(); + + // Filter to retrieve just realm roles + Set realmRoles = new HashSet(); + for (RoleModel role : allRoles) { + if (role.getContainer() instanceof RealmModel) { + realmRoles.add(role); + } + } + return realmRoles; + } + + @Override + public void deleteRoleMapping(RoleModel role) { + if (group == null || role == null) return; + + getMongoStore().pullItemFromList(group, "roleIds", role.getId(), invocationContext); + } + + @Override + public Set getClientRoleMappings(ClientModel app) { + Set result = new HashSet(); + Set roles = getRoleMappings(); + + for (RoleModel role : roles) { + if (app.equals(role.getContainer())) { + result.add(role); + } + } + return result; + } + + @Override + public GroupModel getParent() { + if (group.getParentId() == null) return null; + return realm.getGroupById(group.getParentId()); + } + + @Override + public Set getSubGroups() { + Set subGroups = new HashSet<>(); + for (GroupModel groupModel : realm.getGroups()) { + if (groupModel.getParent().equals(this)) { + subGroups.add(groupModel); + } + } + return subGroups; + } + + @Override + public void setParent(GroupModel group) { + this.group.setParentId(group.getId()); + updateGroup(); + + } + + @Override + public void addChild(GroupModel subGroup) { + subGroup.setParent(this); + updateGroup(); + + } + + @Override + public void removeChild(GroupModel subGroup) { + subGroup.setParent(null); + updateGroup(); + + } +} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java index a84026132e..18acfa9cc6 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoRealmProvider.java @@ -7,11 +7,13 @@ import org.keycloak.connections.mongo.api.MongoStore; import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.migration.MigrationModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RealmProvider; import org.keycloak.models.RoleModel; import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity; +import org.keycloak.models.mongo.keycloak.entities.MongoGroupEntity; import org.keycloak.models.mongo.keycloak.entities.MongoMigrationModelEntity; import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity; import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; @@ -121,6 +123,14 @@ public class MongoRealmProvider implements RealmProvider { return new RoleAdapter(session, realm, role, null, invocationContext); } + @Override + public GroupModel getGroupById(String id, RealmModel realm) { + MongoGroupEntity group = getMongoStore().loadEntity(MongoGroupEntity.class, id, invocationContext); + if (group == null) return null; + if (group.getRealmId() != null && !group.getRealmId().equals(realm.getId())) return null; + return new GroupAdapter(session, realm, group, invocationContext); + } + @Override public ClientModel getClientById(String id, RealmModel realm) { MongoClientEntity appData = getMongoStore().loadEntity(MongoClientEntity.class, id, invocationContext); diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java index 358e6f2d28..bb4ab4c4dd 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java @@ -9,6 +9,7 @@ import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.ClientModel; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.FederatedIdentityModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; @@ -90,10 +91,26 @@ public class MongoUserProvider implements UserProvider { } } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) { + QueryBuilder queryBuilder = new QueryBuilder() + .and("realmId").is(realm.getId()); + queryBuilder.and("groupIds").is(group.getId()); + DBObject sort = new BasicDBObject("username", 1); + + List users = getMongoStore().loadEntities(MongoUserEntity.class, queryBuilder.get(), sort, firstResult, maxResults, invocationContext); + return convertUserEntities(realm, users); + } + protected MongoStore getMongoStore() { return invocationContext.getMongoStore(); } + @Override + public List getGroupMembers(RealmModel realm, GroupModel group) { + return getGroupMembers(realm, group, -1, -1); + } + @Override public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) { DBObject query = new QueryBuilder() @@ -411,6 +428,17 @@ public class MongoUserProvider implements UserProvider { getMongoStore().updateEntities(MongoUserConsentEntity.class, query, pull, invocationContext); } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + // Remove this role from all users, which has it + DBObject query = new QueryBuilder() + .and("groupIds").is(group.getId()) + .get(); + + DBObject pull = new BasicDBObject("$pull", query); + getMongoStore().updateEntities(MongoUserEntity.class, query, pull, invocationContext); + } + @Override public void preRemove(RealmModel realm, RoleModel role) { // Remove this role from all users, which has it diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java index f21744de14..064b4617e8 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/RealmAdapter.java @@ -9,6 +9,7 @@ import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationFlowModel; import org.keycloak.models.AuthenticatorConfigModel; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; @@ -34,6 +35,7 @@ import org.keycloak.models.entities.RequiredCredentialEntity; import org.keycloak.models.entities.UserFederationMapperEntity; import org.keycloak.models.entities.UserFederationProviderEntity; import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity; +import org.keycloak.models.mongo.keycloak.entities.MongoGroupEntity; import org.keycloak.models.mongo.keycloak.entities.MongoRealmEntity; import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; import org.keycloak.models.utils.KeycloakModelUtils; @@ -607,6 +609,47 @@ public class RealmAdapter extends AbstractMongoAdapter impleme return model.getRoleById(id, this); } + @Override + public GroupModel getGroupById(String id) { + return model.getGroupById(id, this); + } + + @Override + public List getGroups() { + DBObject query = new QueryBuilder() + .and("realmId").is(getId()) + .get(); + List groups = getMongoStore().loadEntities(MongoGroupEntity.class, query, invocationContext); + + List result = new LinkedList<>(); + + if (groups == null) return result; + for (MongoGroupEntity group : groups) { + result.add(new GroupAdapter(session, this, group, invocationContext)); + } + + return result; + } + + @Override + public List getTopLevelGroups() { + List all = getGroups(); + Iterator it = all.iterator(); + while (it.hasNext()) { + GroupModel group = it.next(); + if (group.getParent() != null) { + it.remove(); + } + } + return all; + } + + @Override + public boolean removeGroup(GroupModel group) { + session.users().preRemove(this, group); + return getMongoStore().removeEntity(MongoGroupEntity.class, group.getId(), invocationContext); + } + @Override public List getDefaultRoles() { return realm.getDefaultRoles(); diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java index 3235eac1cc..87729d4a6b 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java @@ -7,6 +7,7 @@ import com.mongodb.QueryBuilder; import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.OTPPolicy; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.UserConsentModel; @@ -450,6 +451,37 @@ public class UserAdapter extends AbstractMongoAdapter implement return user; } + @Override + public Set getGroups() { + if (user.getGroupIds() == null && user.getGroupIds().size() == 0) return Collections.EMPTY_SET; + Set groups = new HashSet<>(); + for (String id : user.getGroupIds()) { + groups.add(realm.getGroupById(id)); + } + return groups; + } + + @Override + public void joinGroup(GroupModel group) { + getMongoStore().pushItemToList(getUser(), "groupIds", group.getId(), true, invocationContext); + + } + + @Override + public void leaveGroup(GroupModel group) { + if (user == null || group == null) return; + + getMongoStore().pullItemFromList(getUser(), "groupIds", group.getId(), invocationContext); + + } + + @Override + public boolean isMemberOf(GroupModel group) { + if (user.getGroupIds().contains(group.getId())) return true; + Set groups = getGroups(); + return KeycloakModelUtils.isMember(groups, group); + } + @Override public boolean hasRole(RoleModel role) { Set roles = getRoleMappings(); diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java new file mode 100755 index 0000000000..80e51a92f1 --- /dev/null +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/entities/MongoGroupEntity.java @@ -0,0 +1,26 @@ +package org.keycloak.models.mongo.keycloak.entities; + +import com.mongodb.DBObject; +import com.mongodb.QueryBuilder; +import org.jboss.logging.Logger; +import org.keycloak.connections.mongo.api.MongoCollection; +import org.keycloak.connections.mongo.api.MongoField; +import org.keycloak.connections.mongo.api.MongoIdentifiableEntity; +import org.keycloak.connections.mongo.api.MongoStore; +import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; +import org.keycloak.models.entities.GroupEntity; +import org.keycloak.models.entities.RoleEntity; + +import java.util.List; + +/** + */ +@MongoCollection(collectionName = "groups") +public class MongoGroupEntity extends GroupEntity implements MongoIdentifiableEntity { + + private static final Logger logger = Logger.getLogger(MongoGroupEntity.class); + + @Override + public void afterRemove(MongoStoreInvocationContext invContext) { + } +} diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java b/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java index 9c2b326005..eaf221698a 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/utils/MongoModelUtils.java @@ -4,11 +4,13 @@ import com.mongodb.DBObject; import com.mongodb.QueryBuilder; import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext; import org.keycloak.models.ClientModel; +import org.keycloak.models.GroupModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; import org.keycloak.models.entities.ClientEntity; import org.keycloak.models.mongo.keycloak.adapters.ClientAdapter; +import org.keycloak.models.mongo.keycloak.adapters.GroupAdapter; import org.keycloak.models.mongo.keycloak.adapters.UserAdapter; import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity; import org.keycloak.models.mongo.keycloak.entities.MongoUserEntity; diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/DummyUserFederationProvider.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/DummyUserFederationProvider.java index b501da9e31..51dbbd4f45 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/DummyUserFederationProvider.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/DummyUserFederationProvider.java @@ -1,6 +1,7 @@ package org.keycloak.testsuite; import org.keycloak.models.CredentialValidationOutput; +import org.keycloak.models.GroupModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; @@ -67,6 +68,11 @@ public class DummyUserFederationProvider implements UserFederationProvider { } + @Override + public void preRemove(RealmModel realm, GroupModel group) { + + } + @Override public boolean isValid(RealmModel realm, UserModel local) { return false; From c2ad9189752307dec9ab6eaf44a4c058e4e5c21f Mon Sep 17 00:00:00 2001 From: Bill Burke Date: Mon, 2 Nov 2015 11:19:19 -0500 Subject: [PATCH 3/4] group model --- .../META-INF/jpa-changelog-1.7.0.xml | 56 +++++++++++++++++++ .../META-INF/jpa-changelog-master.xml | 1 + .../jpa/updater/JpaUpdaterProvider.java | 2 +- .../main/resources/META-INF/persistence.xml | 4 ++ .../keycloak/migration/MigrationModel.java | 2 +- .../keycloak/models/jpa/JpaRealmProvider.java | 8 +++ .../jpa/entities/GroupAttributeEntity.java | 4 +- .../models/jpa/entities/GroupEntity.java | 13 ++--- .../jpa/entities/GroupRoleMappingEntity.java | 3 +- 9 files changed, 80 insertions(+), 13 deletions(-) create mode 100755 connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-1.7.0.xml diff --git a/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-1.7.0.xml b/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-1.7.0.xml new file mode 100755 index 0000000000..ba886698ba --- /dev/null +++ b/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-1.7.0.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-master.xml b/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-master.xml index 6cd96c626c..93c2824a42 100755 --- a/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-master.xml +++ b/connections/jpa-liquibase/src/main/resources/META-INF/jpa-changelog-master.xml @@ -10,4 +10,5 @@ + diff --git a/connections/jpa/src/main/java/org/keycloak/connections/jpa/updater/JpaUpdaterProvider.java b/connections/jpa/src/main/java/org/keycloak/connections/jpa/updater/JpaUpdaterProvider.java index 60b063513e..a5429e4685 100755 --- a/connections/jpa/src/main/java/org/keycloak/connections/jpa/updater/JpaUpdaterProvider.java +++ b/connections/jpa/src/main/java/org/keycloak/connections/jpa/updater/JpaUpdaterProvider.java @@ -12,7 +12,7 @@ public interface JpaUpdaterProvider extends Provider { public String FIRST_VERSION = "1.0.0.Final"; - public String LAST_VERSION = "1.6.0"; + public String LAST_VERSION = "1.7.0"; public String getCurrentVersionSql(String defaultSchema); diff --git a/connections/jpa/src/main/resources/META-INF/persistence.xml b/connections/jpa/src/main/resources/META-INF/persistence.xml index b8592a365c..e415488be3 100755 --- a/connections/jpa/src/main/resources/META-INF/persistence.xml +++ b/connections/jpa/src/main/resources/META-INF/persistence.xml @@ -31,6 +31,10 @@ org.keycloak.models.jpa.entities.RequiredActionProviderEntity org.keycloak.models.jpa.session.PersistentUserSessionEntity org.keycloak.models.jpa.session.PersistentClientSessionEntity + org.keycloak.models.jpa.entities.GroupEntity + org.keycloak.models.jpa.entities.GroupAttributeEntity + org.keycloak.models.jpa.entities.GroupRoleMappingEntity + org.keycloak.models.jpa.entities.UserGroupMembershipEntity org.keycloak.events.jpa.EventEntity diff --git a/model/api/src/main/java/org/keycloak/migration/MigrationModel.java b/model/api/src/main/java/org/keycloak/migration/MigrationModel.java index beb2f984be..596f2783da 100755 --- a/model/api/src/main/java/org/keycloak/migration/MigrationModel.java +++ b/model/api/src/main/java/org/keycloak/migration/MigrationModel.java @@ -11,7 +11,7 @@ public interface MigrationModel { /** * Must have the form of major.minor.micro as the version is parsed and numbers are compared */ - public static final String LATEST_VERSION = "1.6.0"; + public static final String LATEST_VERSION = "1.7.0"; String getStoredVersion(); void setStoredVersion(String version); diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java index c5396cb50b..5fe5faa7f3 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java @@ -103,6 +103,14 @@ public class JpaRealmProvider implements RealmProvider { adapter.removeClient(a.getId()); } + int num = em.createNamedQuery("deleteGroupRoleMappingsByRealm") + .setParameter("realm", realm).executeUpdate(); + num = em.createNamedQuery("deleteGroupAttributesByRealm") + .setParameter("realm", realm).executeUpdate(); + num = em.createNamedQuery("deleteGroupsByRealm") + .setParameter("realm", realm).executeUpdate(); + + em.remove(realm); return true; } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java index 8ee79e093d..87744e10af 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupAttributeEntity.java @@ -17,9 +17,9 @@ import javax.persistence.Table; @NamedQueries({ @NamedQuery(name="getGroupAttributesByNameAndValue", query="select attr from GroupAttributeEntity attr where attr.name = :name and attr.value = :value"), @NamedQuery(name="deleteGroupAttributesByGroup", query="delete from GroupAttributeEntity attr where attr.group = :group"), - @NamedQuery(name="deleteGroupAttributesByRealm", query="delete from GroupAttributeEntity attr where attr.group IN (select u from GroupEntity u where u.realmId=:realmId)") + @NamedQuery(name="deleteGroupAttributesByRealm", query="delete from GroupAttributeEntity attr where attr.group IN (select u from GroupEntity u where u.realm=:realm)") }) -@Table(name="USER_ATTRIBUTE") +@Table(name="GROUP_ATTRIBUTE") @Entity public class GroupAttributeEntity { diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java index b944379cea..d5851fd1b6 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupEntity.java @@ -22,15 +22,14 @@ import java.util.Collection; * @version $Revision: 1 $ */ @NamedQueries({ - @NamedQuery(name="getAllGroupsByRealm", query="select u from GroupEntity u where u.realmId = :realmId order by u.name"), - @NamedQuery(name="getGroupById", query="select u from GroupEntity u where u.id = :id and u.realmId = :realmId"), + @NamedQuery(name="getAllGroupsByRealm", query="select u from GroupEntity u where u.realm = :realm order by u.name"), + @NamedQuery(name="getGroupById", query="select u from GroupEntity u where u.id = :id and u.realm = :realm"), @NamedQuery(name="getGroupIdsByParent", query="select u.id from GroupEntity u where u.parent = :parent"), - @NamedQuery(name="getGroupByName", query="select u from GroupEntity u where u.name = :name and u.realmId = :realmId"), - @NamedQuery(name="getGroupCount", query="select count(u) from GroupEntity u where u.realmId = :realmId"), - @NamedQuery(name="deleteGroupsByRealm", query="delete from GroupEntity u where u.realmId = :realmId") + @NamedQuery(name="getGroupCount", query="select count(u) from GroupEntity u where u.realm = :realm"), + @NamedQuery(name="deleteGroupsByRealm", query="delete from GroupEntity u where u.realm = :realm") }) @Entity -@Table(name="GROUP_ENTITY") +@Table(name="KEYCLOAK_GROUP") public class GroupEntity { @Id @Column(name="ID", length = 36) @@ -44,7 +43,7 @@ public class GroupEntity { private GroupEntity parent; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "REALM") + @JoinColumn(name = "REALM_ID") private RealmEntity realm; @OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true, mappedBy="group") diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java index 86db554f71..27fe1ac2a2 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/GroupRoleMappingEntity.java @@ -20,7 +20,7 @@ import java.io.Serializable; @NamedQuery(name="groupHasRole", query="select m from GroupRoleMappingEntity m where m.group = :group and m.roleId = :roleId"), @NamedQuery(name="groupRoleMappings", query="select m from GroupRoleMappingEntity m where m.group = :group"), @NamedQuery(name="groupRoleMappingIds", query="select m.roleId from GroupRoleMappingEntity m where m.group = :group"), - @NamedQuery(name="deleteGroupRoleMappingsByRealm", query="delete from GroupRoleMappingEntity mapping where mapping.group IN (select u from GroupEntity u where u.realmId=:realmId)"), + @NamedQuery(name="deleteGroupRoleMappingsByRealm", query="delete from GroupRoleMappingEntity mapping where mapping.group IN (select u from GroupEntity u where u.realm=:realm)"), @NamedQuery(name="deleteGroupRoleMappingsByRole", query="delete from GroupRoleMappingEntity m where m.roleId = :roleId"), @NamedQuery(name="deleteGroupRoleMappingsByGroup", query="delete from GroupRoleMappingEntity m where m.group = :group") @@ -55,7 +55,6 @@ public class GroupRoleMappingEntity { this.roleId = roleId; } - public static class Key implements Serializable { protected GroupEntity group; From e25157655b4a6dfa45b2f402d3bdb972e6da8d18 Mon Sep 17 00:00:00 2001 From: Bill Burke Date: Wed, 11 Nov 2015 18:03:53 -0500 Subject: [PATCH 4/4] group ui --- .../idm/GroupRepresentation.java | 17 +- .../idm/UserRoleMappingRepresentation.java | 45 --- .../main/resources/theme/base/admin/index.ftl | 2 + .../theme/base/admin/resources/js/app.js | 78 ++++- .../admin/resources/js/controllers/groups.js | 321 ++++++++++++++++++ .../admin/resources/js/controllers/realm.js | 4 + .../theme/base/admin/resources/js/loaders.js | 18 + .../theme/base/admin/resources/js/services.js | 72 ++++ .../resources/partials/create-group.html | 25 ++ .../resources/partials/group-attributes.html | 45 +++ .../resources/partials/group-detail.html | 28 ++ .../admin/resources/partials/group-list.html | 40 +++ .../partials/group-role-mappings.html | 101 ++++++ .../admin/resources/templates/kc-menu.html | 3 +- .../resources/templates/kc-tabs-group.html | 13 + .../theme/keycloak/admin/theme.properties | 2 +- .../resources/lib/angular/treeview/LICENSE | 20 ++ .../resources/lib/angular/treeview/README.md | 122 +++++++ .../lib/angular/treeview/angular.treeview.js | 97 ++++++ .../angular/treeview/angular.treeview.min.js | 9 + .../angular/treeview/css/angular.treeview.css | 99 ++++++ .../lib/angular/treeview/img/file.png | Bin 0 -> 263 bytes .../angular/treeview/img/folder-closed.png | Bin 0 -> 281 bytes .../lib/angular/treeview/img/folder.png | Bin 0 -> 289 bytes .../java/org/keycloak/models/GroupModel.java | 12 +- .../java/org/keycloak/models/RealmModel.java | 13 +- .../org/keycloak/models/RoleMapperModel.java | 21 ++ .../java/org/keycloak/models/UserModel.java | 9 +- .../models/utils/ModelToRepresentation.java | 55 +++ .../models/file/adapter/GroupAdapter.java | 5 + .../models/file/adapter/RealmAdapter.java | 20 +- .../models/cache/infinispan/GroupAdapter.java | 8 + .../models/cache/infinispan/RealmAdapter.java | 21 +- .../models/cache/entities/CachedGroup.java | 2 +- .../org/keycloak/models/jpa/GroupAdapter.java | 18 +- .../keycloak/models/jpa/JpaRealmProvider.java | 2 +- .../org/keycloak/models/jpa/RealmAdapter.java | 36 +- .../mongo/keycloak/adapters/GroupAdapter.java | 5 + .../mongo/keycloak/adapters/RealmAdapter.java | 32 ++ ...e.java => ClientRoleMappingsResource.java} | 13 +- .../resources/admin/GroupResource.java | 261 ++++++++++++++ .../resources/admin/RealmAdminResource.java | 7 + .../resources/admin/RoleMapperResource.java | 271 +++++++++++++++ .../resources/admin/UsersResource.java | 209 +----------- .../keycloak/testsuite/KeycloakServer.java | 3 + 45 files changed, 1882 insertions(+), 302 deletions(-) delete mode 100755 core/src/main/java/org/keycloak/representations/idm/UserRoleMappingRepresentation.java create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/groups.js create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/partials/create-group.html create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-attributes.html create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-detail.html create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-list.html create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-role-mappings.html create mode 100755 forms/common-themes/src/main/resources/theme/base/admin/resources/templates/kc-tabs-group.html mode change 100644 => 100755 forms/common-themes/src/main/resources/theme/keycloak/admin/theme.properties create mode 100644 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/LICENSE create mode 100644 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/README.md create mode 100755 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/angular.treeview.js create mode 100644 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/angular.treeview.min.js create mode 100755 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/css/angular.treeview.css create mode 100644 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/img/file.png create mode 100644 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/img/folder-closed.png create mode 100644 forms/common-themes/src/main/resources/theme/keycloak/common/resources/lib/angular/treeview/img/folder.png create mode 100755 model/api/src/main/java/org/keycloak/models/RoleMapperModel.java rename services/src/main/java/org/keycloak/services/resources/admin/{UserClientRoleMappingsResource.java => ClientRoleMappingsResource.java} (90%) create mode 100755 services/src/main/java/org/keycloak/services/resources/admin/GroupResource.java create mode 100755 services/src/main/java/org/keycloak/services/resources/admin/RoleMapperResource.java diff --git a/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java index 833dfe3a5f..cd5292f071 100755 --- a/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java +++ b/core/src/main/java/org/keycloak/representations/idm/GroupRepresentation.java @@ -12,9 +12,9 @@ import java.util.Map; * @version $Revision: 1 $ */ public class GroupRepresentation { - private String id; - private String name; - protected Map attributes; + protected String id; + protected String name; + protected Map> attributes; protected List realmRoles; protected Map> clientRoles; protected List subGroups; @@ -51,17 +51,12 @@ public class GroupRepresentation { this.clientRoles = clientRoles; } - public Map getAttributes() { + + public Map> getAttributes() { return attributes; } - // This method can be removed once we can remove backwards compatibility with Keycloak 1.3 (then getAttributes() can be changed to return Map> ) - @JsonIgnore - public Map> getAttributesAsListValues() { - return (Map) attributes; - } - - public void setAttributes(Map attributes) { + public void setAttributes(Map> attributes) { this.attributes = attributes; } diff --git a/core/src/main/java/org/keycloak/representations/idm/UserRoleMappingRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/UserRoleMappingRepresentation.java deleted file mode 100755 index a1a1e1c21e..0000000000 --- a/core/src/main/java/org/keycloak/representations/idm/UserRoleMappingRepresentation.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.keycloak.representations.idm; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class UserRoleMappingRepresentation { - protected String self; // link - protected String username; - protected Set roles; - - public String getSelf() { - return self; - } - - public void setSelf(String self) { - this.self = self; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getRoles() { - return roles; - } - - public void setRoles(Set roles) { - this.roles = roles; - } - - public UserRoleMappingRepresentation role(String role) { - if (this.roles == null) this.roles = new HashSet(); - this.roles.add(role); - return this; - } - -} diff --git a/forms/common-themes/src/main/resources/theme/base/admin/index.ftl b/forms/common-themes/src/main/resources/theme/base/admin/index.ftl index 1584d0d93a..0cdadfb0cb 100755 --- a/forms/common-themes/src/main/resources/theme/base/admin/index.ftl +++ b/forms/common-themes/src/main/resources/theme/base/admin/index.ftl @@ -25,6 +25,7 @@ + @@ -37,6 +38,7 @@ + diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/app.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/app.js index f1d922b31a..b4fe6684e9 100755 --- a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/app.js +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/app.js @@ -7,7 +7,7 @@ var configUrl = consoleBaseUrl + "/config"; var auth = {}; -var module = angular.module('keycloak', [ 'keycloak.services', 'keycloak.loaders', 'ui.bootstrap', 'ui.select2', 'angularFileUpload', 'pascalprecht.translate', 'ngCookies', 'ngSanitize']); +var module = angular.module('keycloak', [ 'keycloak.services', 'keycloak.loaders', 'ui.bootstrap', 'ui.select2', 'angularFileUpload', 'angularTreeview', 'pascalprecht.translate', 'ngCookies', 'ngSanitize']); var resourceRequests = 0; var loadingTimer = -1; @@ -574,6 +574,73 @@ module.config([ '$routeProvider', function($routeProvider) { }, controller : 'RoleListCtrl' }) + .when('/realms/:realm/groups', { + templateUrl : resourceUrl + '/partials/group-list.html', + resolve : { + realm : function(RealmLoader) { + return RealmLoader(); + }, + groups : function(GroupListLoader) { + return GroupListLoader(); + } + }, + controller : 'GroupListCtrl' + }) + .when('/create/group/:realm/parent/:parentId', { + templateUrl : resourceUrl + '/partials/create-group.html', + resolve : { + realm : function(RealmLoader) { + return RealmLoader(); + }, + parentId : function($route) { + return $route.current.params.parentId; + } + }, + controller : 'GroupCreateCtrl' + }) + .when('/realms/:realm/groups/:group', { + templateUrl : resourceUrl + '/partials/group-detail.html', + resolve : { + realm : function(RealmLoader) { + return RealmLoader(); + }, + group : function(GroupLoader) { + return GroupLoader(); + } + }, + controller : 'GroupDetailCtrl' + }) + .when('/realms/:realm/groups/:group/attributes', { + templateUrl : resourceUrl + '/partials/group-attributes.html', + resolve : { + realm : function(RealmLoader) { + return RealmLoader(); + }, + group : function(GroupLoader) { + return GroupLoader(); + } + }, + controller : 'GroupDetailCtrl' + }) + .when('/realms/:realm/groups/:group/role-mappings', { + templateUrl : resourceUrl + '/partials/group-role-mappings.html', + resolve : { + realm : function(RealmLoader) { + return RealmLoader(); + }, + group : function(GroupLoader) { + return GroupLoader(); + }, + clients : function(ClientListLoader) { + return ClientListLoader(); + }, + client : function() { + return {}; + } + }, + controller : 'GroupRoleMappingCtrl' + }) + .when('/create/role/:realm/clients/:client', { templateUrl : resourceUrl + '/partials/client-role-detail.html', @@ -1856,6 +1923,15 @@ module.directive('kcTabsUser', function () { } }); +module.directive('kcTabsGroup', function () { + return { + scope: true, + restrict: 'E', + replace: true, + templateUrl: resourceUrl + '/templates/kc-tabs-group.html' + } +}); + module.directive('kcTabsClient', function () { return { scope: true, diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/groups.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/groups.js new file mode 100755 index 0000000000..7e82f32b36 --- /dev/null +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/groups.js @@ -0,0 +1,321 @@ +module.controller('GroupListCtrl', function($scope, $route, realm, groups, Groups, Group, GroupChildren, Notifications, $location, Dialog) { + $scope.realm = realm; + $scope.groupList = [ + {"id" : "realm", "name": "Groups", + "subGroups" : groups} + ]; + + $scope.tree = []; + + $scope.edit = function(selected) { + $location.url("/realms/" + realm.realm + "/groups/" + selected.id); + } + + $scope.cut = function(selected) { + $scope.cutNode = selected; + } + + $scope.isDisabled = function() { + if (!$scope.tree.currentNode) return true; + return $scope.tree.currentNode.id == 'realm'; + } + + $scope.paste = function(selected) { + if (selected == null) return; + if ($scope.cutNode == null) return; + if (selected.id == 'realm') { + Groups.save({realm: realm.realm}, {id:$scope.cutNode.id}, function() { + $route.reload(); + Notifications.success("Group moved."); + + }); + + } else { + GroupChildren.save({realm: realm.realm, groupId: selected.id}, {id:$scope.cutNode.id}, function() { + $route.reload(); + Notifications.success("Group moved."); + + }); + + } + + } + + $scope.remove = function(selected) { + if (selected == null) return; + Dialog.confirmDelete(selected.name, 'group', function() { + Group.remove({ realm: realm.realm, groupId : selected.id }, function() { + $route.reload(); + Notifications.success("The group has been deleted."); + }); + }); + + } + + $scope.createGroup = function(selected) { + var parent = 'realm'; + if (selected) { + parent = selected.id; + } + $location.url("/create/group/" + realm.realm + '/parent/' + parent); + + } + var isLeaf = function(node) { + return node.id != "realm" && (!node.subGroups || node.subGroups.length == 0); + } + + $scope.getGroupClass = function(node) { + if (node.id == "realm") { + return 'pficon pficon-users'; + } + if (isLeaf(node)) { + return 'normal'; + } + if (node.subGroups.length && node.collapsed) return 'collapsed'; + if (node.subGroups.length && !node.collapsed) return 'expanded'; + return 'collapsed'; + + } + + $scope.getSelectedClass = function(node) { + if (node.selected) { + return 'selected'; + } else if ($scope.cutNode && $scope.cutNode.id == node.id) { + return 'cut'; + } + return undefined; + } + +}); + +module.controller('GroupCreateCtrl', function($scope, $route, realm, parentId, Groups, Group, GroupChildren, Notifications, $location) { + $scope.realm = realm; + $scope.group = {}; + $scope.save = function() { + console.log('save!!!'); + if (parentId == 'realm') { + console.log('realm') + Groups.save({realm: realm.realm, groupId: parentId}, $scope.group, function(data, headers) { + var l = headers().location; + + + var id = l.substring(l.lastIndexOf("/") + 1); + + $location.url("/realms/" + realm.realm + "/groups/" + id); + Notifications.success("Group Created."); + }) + + } else { + GroupChildren.save({realm: realm.realm, groupId: parentId}, $scope.group, function(data, headers) { + var l = headers().location; + + + var id = l.substring(l.lastIndexOf("/") + 1); + + $location.url("/realms/" + realm.realm + "/groups/" + id); + Notifications.success("Group Created."); + }) + + } + + } + $scope.cancel = function() { + $location.url("/realms/" + realm.realm + "/groups"); + }; +}); + +module.controller('GroupTabCtrl', function(Dialog, $scope, Current, Group, Notifications, $location) { + $scope.removeGroup = function() { + Dialog.confirmDelete($scope.group.name, 'group', function() { + Group.remove({ + realm : Current.realm.realm, + groupId : $scope.group.id + }, function() { + $location.url("/realms/" + Current.realm.realm + "/groups"); + Notifications.success("The group has been deleted."); + }); + }); + }; +}); + +module.controller('GroupDetailCtrl', function(Dialog, $scope, realm, group, Group, Notifications, $location) { + $scope.realm = realm; + + if (!group.attributes) { + group.attributes = {} + } + convertAttributeValuesToString(group); + + + $scope.group = angular.copy(group); + + $scope.changed = false; // $scope.create; + $scope.$watch('group', function() { + if (!angular.equals($scope.group, group)) { + $scope.changed = true; + } + }, true); + + $scope.save = function() { + convertAttributeValuesToLists(); + + Group.update({ + realm: realm.realm, + groupId: $scope.group.id + }, $scope.group, function () { + $scope.changed = false; + convertAttributeValuesToString($scope.group); + group = angular.copy($scope.group); + Notifications.success("Your changes have been saved to the group."); + }); + }; + + function convertAttributeValuesToLists() { + var attrs = $scope.group.attributes; + for (var attribute in attrs) { + if (typeof attrs[attribute] === "string") { + var attrVals = attrs[attribute].split("##"); + attrs[attribute] = attrVals; + } + } + } + + function convertAttributeValuesToString(group) { + var attrs = group.attributes; + for (var attribute in attrs) { + if (typeof attrs[attribute] === "object") { + var attrVals = attrs[attribute].join("##"); + attrs[attribute] = attrVals; + } + } + } + + $scope.reset = function() { + $scope.group = angular.copy(group); + $scope.changed = false; + }; + + $scope.cancel = function() { + $location.url("/realms/" + realm.realm + "/groups"); + }; + + $scope.addAttribute = function() { + $scope.group.attributes[$scope.newAttribute.key] = $scope.newAttribute.value; + delete $scope.newAttribute; + } + + $scope.removeAttribute = function(key) { + delete $scope.group.attributes[key]; + } +}); + +module.controller('GroupRoleMappingCtrl', function($scope, $http, realm, group, clients, client, Notifications, GroupRealmRoleMapping, + GroupClientRoleMapping, GroupAvailableRealmRoleMapping, GroupAvailableClientRoleMapping, + GroupCompositeRealmRoleMapping, GroupCompositeClientRoleMapping) { + $scope.realm = realm; + $scope.group = group; + $scope.selectedRealmRoles = []; + $scope.selectedRealmMappings = []; + $scope.realmMappings = []; + $scope.clients = clients; + $scope.client = client; + $scope.clientRoles = []; + $scope.clientComposite = []; + $scope.selectedClientRoles = []; + $scope.selectedClientMappings = []; + $scope.clientMappings = []; + $scope.dummymodel = []; + + $scope.realmMappings = GroupRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmRoles = GroupAvailableRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmComposite = GroupCompositeRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + + $scope.addRealmRole = function() { + var roles = $scope.selectedRealmRoles; + $scope.selectedRealmRoles = []; + $http.post(authUrl + '/admin/realms/' + realm.realm + '/groups/' + group.id + '/role-mappings/realm', + roles).success(function() { + $scope.realmMappings = GroupRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmRoles = GroupAvailableRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmComposite = GroupCompositeRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.selectedRealmMappings = []; + $scope.selectRealmRoles = []; + if ($scope.targetClient) { + console.log('load available'); + $scope.clientComposite = GroupCompositeClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientRoles = GroupAvailableClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientMappings = GroupClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.selectedClientRoles = []; + $scope.selectedClientMappings = []; + } + Notifications.success("Role mappings updated."); + + }); + }; + + $scope.deleteRealmRole = function() { + $http.delete(authUrl + '/admin/realms/' + realm.realm + '/groups/' + group.id + '/role-mappings/realm', + {data : $scope.selectedRealmMappings, headers : {"content-type" : "application/json"}}).success(function() { + $scope.realmMappings = GroupRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmRoles = GroupAvailableRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmComposite = GroupCompositeRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.selectedRealmMappings = []; + $scope.selectRealmRoles = []; + if ($scope.targetClient) { + console.log('load available'); + $scope.clientComposite = GroupCompositeClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientRoles = GroupAvailableClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientMappings = GroupClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.selectedClientRoles = []; + $scope.selectedClientMappings = []; + } + Notifications.success("Role mappings updated."); + }); + }; + + $scope.addClientRole = function() { + $http.post(authUrl + '/admin/realms/' + realm.realm + '/groups/' + group.id + '/role-mappings/clients/' + $scope.targetClient.id, + $scope.selectedClientRoles).success(function() { + $scope.clientMappings = GroupClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientRoles = GroupAvailableClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientComposite = GroupCompositeClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.selectedClientRoles = []; + $scope.selectedClientMappings = []; + $scope.realmComposite = GroupCompositeRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmRoles = GroupAvailableRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + Notifications.success("Role mappings updated."); + }); + }; + + $scope.deleteClientRole = function() { + $http.delete(authUrl + '/admin/realms/' + realm.realm + '/groups/' + group.id + '/role-mappings/clients/' + $scope.targetClient.id, + {data : $scope.selectedClientMappings, headers : {"content-type" : "application/json"}}).success(function() { + $scope.clientMappings = GroupClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientRoles = GroupAvailableClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientComposite = GroupCompositeClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.selectedClientRoles = []; + $scope.selectedClientMappings = []; + $scope.realmComposite = GroupCompositeRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + $scope.realmRoles = GroupAvailableRealmRoleMapping.query({realm : realm.realm, groupId : group.id}); + Notifications.success("Role mappings updated."); + }); + }; + + + $scope.changeClient = function() { + if ($scope.targetClient) { + $scope.clientComposite = GroupCompositeClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientRoles = GroupAvailableClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + $scope.clientMappings = GroupClientRoleMapping.query({realm : realm.realm, groupId : group.id, client : $scope.targetClient.id}); + } else { + $scope.clientRoles = null; + $scope.clientMappings = null; + $scope.clientComposite = null; + } + $scope.selectedClientRoles = []; + $scope.selectedClientMappings = []; + }; + + + +}); diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js index 4a4fe89c5d..4fa1d8f4a8 100755 --- a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/controllers/realm.js @@ -1994,3 +1994,7 @@ module.controller('AuthenticationConfigCreateCtrl', function($scope, realm, conf + + + + diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/loaders.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/loaders.js index 7706f0fda8..bcd98b1486 100755 --- a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/loaders.js +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/loaders.js @@ -458,6 +458,24 @@ module.factory('AuthenticationConfigLoader', function(Loader, AuthenticationConf }); }); +module.factory('GroupListLoader', function(Loader, Groups, $route, $q) { + return Loader.query(Groups, function() { + return { + realm : $route.current.params.realm + } + }); +}); + +module.factory('GroupLoader', function(Loader, Group, $route, $q) { + return Loader.get(Group, function() { + return { + realm : $route.current.params.realm, + groupId : $route.current.params.group + } + }); +}); + + diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js index ec0d475bf7..b9e4705c7e 100755 --- a/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/js/services.js @@ -1442,6 +1442,78 @@ module.service('SelectRoleDialog', function($modal) { return dialog }); +module.factory('Group', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId', { + realm : '@realm', + userId : '@groupId' + }, { + update : { + method : 'PUT' + } + }); +}); + +module.factory('GroupChildren', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/children', { + realm : '@realm', + groupId : '@groupId' + }); +}); + +module.factory('Groups', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups', { + realm : '@realm' + }); +}); + +module.factory('GroupRealmRoleMapping', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/role-mappings/realm', { + realm : '@realm', + groupId : '@groupId' + }); +}); + +module.factory('GroupCompositeRealmRoleMapping', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/role-mappings/realm/composite', { + realm : '@realm', + groupId : '@groupId' + }); +}); + +module.factory('GroupAvailableRealmRoleMapping', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/role-mappings/realm/available', { + realm : '@realm', + groupId : '@groupId' + }); +}); + + +module.factory('GroupClientRoleMapping', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/role-mappings/clients/:client', { + realm : '@realm', + groupId : '@groupId', + client : "@client" + }); +}); + +module.factory('GroupAvailableClientRoleMapping', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/role-mappings/clients/:client/available', { + realm : '@realm', + groupId : '@groupId', + client : "@client" + }); +}); + +module.factory('GroupCompositeClientRoleMapping', function($resource) { + return $resource(authUrl + '/admin/realms/:realm/groups/:groupId/role-mappings/clients/:client/composite', { + realm : '@realm', + groupId : '@groupId', + client : "@client" + }); +}); + + + diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/create-group.html b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/create-group.html new file mode 100755 index 0000000000..6e4788016c --- /dev/null +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/create-group.html @@ -0,0 +1,25 @@ +
+
+

Create Group

+
+
+
+
+ +
+ +
+
+
+ +
+
+ + +
+
+
+
+ + \ No newline at end of file diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-attributes.html b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-attributes.html new file mode 100755 index 0000000000..9fcfc8b741 --- /dev/null +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-attributes.html @@ -0,0 +1,45 @@ +
+ + + + +
+ + + + + + + + + + + + + + + + + + + + +
KeyValueActions
{{key}} + +
+ +
+ +
+
+ + +
+
+
+
+ + diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-detail.html b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-detail.html new file mode 100755 index 0000000000..3dc41aa59e --- /dev/null +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-detail.html @@ -0,0 +1,28 @@ +
+ + + +
+
+
+ +
+ +
+
+
+ +
+
+ + +
+
+
+
+ + \ No newline at end of file diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-list.html b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-list.html new file mode 100755 index 0000000000..14acbaecba --- /dev/null +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-list.html @@ -0,0 +1,40 @@ +
+

+ User Groups + User groups +

+ + + + + + + + + + + + +
+
+
+ + + + + +
+
+
+
+
+ +
+ + \ No newline at end of file diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-role-mappings.html b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-role-mappings.html new file mode 100755 index 0000000000..22916e1217 --- /dev/null +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/partials/group-role-mappings.html @@ -0,0 +1,101 @@ +
+ + + + +
+
+ + +
+
+
+ + + + Realm roles that can be assigned to the group. +
+
+ + Realm roles mapped to the group + + +
+
+ + All realm role mappings. Some roles here might be inherited from a mapped composite role. + +
+
+
+
+ +
+ +
+
+
Select client to view roles for client
+
+
+
+ + Assignable roles from this client. + + +
+
+ + Role mappings for this client. + + +
+
+ + +
+
+
+
+
+ + + + \ No newline at end of file diff --git a/forms/common-themes/src/main/resources/theme/base/admin/resources/templates/kc-menu.html b/forms/common-themes/src/main/resources/theme/base/admin/resources/templates/kc-menu.html index baa3b45d5e..8da0e56148 100755 --- a/forms/common-themes/src/main/resources/theme/base/admin/resources/templates/kc-menu.html +++ b/forms/common-themes/src/main/resources/theme/base/admin/resources/templates/kc-menu.html @@ -40,7 +40,8 @@