Search in sources :

Example 41 with GroupModel

use of org.keycloak.models.GroupModel in project keycloak by keycloak.

the class GroupLDAPStorageMapper method syncNonExistingGroup.

private void syncNonExistingGroup(RealmModel realm, Map.Entry<String, LDAPObject> groupEntry, SynchronizationResult syncResult, Set<String> visitedGroupIds, String groupName) {
    try {
        // Create each non-existing group to be synced in its own inner transaction to prevent race condition when
        // the group intended to be created was already created via other channel in the meantime
        KeycloakModelUtils.runJobInTransaction(ldapProvider.getSession().getKeycloakSessionFactory(), session -> {
            RealmModel innerTransactionRealm = session.realms().getRealm(realm.getId());
            GroupModel kcGroup = createKcGroup(innerTransactionRealm, groupName, null);
            updateAttributesOfKCGroup(kcGroup, groupEntry.getValue());
            syncResult.increaseAdded();
            visitedGroupIds.add(kcGroup.getId());
        });
    } catch (ModelException me) {
        logger.error(String.format("Failed to sync group %s from LDAP: ", groupName), me);
        syncResult.increaseFailed();
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ModelException(org.keycloak.models.ModelException) GroupModel(org.keycloak.models.GroupModel)

Example 42 with GroupModel

use of org.keycloak.models.GroupModel in project keycloak by keycloak.

the class DefaultEvaluation method createRealm.

private Realm createRealm() {
    return new Realm() {

        @Override
        public boolean isUserInGroup(String id, String groupId, boolean checkParent) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            RealmModel realm = session.getContext().getRealm();
            GroupModel group = KeycloakModelUtils.findGroupByPath(realm, groupId);
            if (Objects.isNull(group)) {
                return false;
            }
            if (checkParent) {
                return RoleUtils.isMember(user.getGroupsStream(), group);
            }
            return user.isMemberOf(group);
        }

        private UserModel getUser(String id, KeycloakSession session) {
            RealmModel realm = session.getContext().getRealm();
            UserModel user = session.users().getUserById(realm, id);
            if (Objects.isNull(user)) {
                user = session.users().getUserByUsername(realm, id);
            }
            if (Objects.isNull(user)) {
                user = session.users().getUserByEmail(realm, id);
            }
            if (Objects.isNull(user)) {
                user = session.users().getServiceAccount(realm.getClientById(id));
            }
            return user;
        }

        @Override
        public boolean isUserInRealmRole(String id, String roleName) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            Stream<RoleModel> roleMappings = user.getRoleMappingsStream().filter(isNotClientRole);
            return RoleUtils.hasRole(roleMappings, session.getContext().getRealm().getRole(roleName));
        }

        @Override
        public boolean isUserInClientRole(String id, String clientId, String roleName) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            RealmModel realm = session.getContext().getRealm();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            Set<RoleModel> roleMappings = user.getRoleMappingsStream().filter(RoleModel::isClientRole).filter(role -> Objects.equals(((ClientModel) role.getContainer()).getClientId(), clientId)).collect(Collectors.toSet());
            if (roleMappings.isEmpty()) {
                return false;
            }
            RoleModel role = realm.getClientById(roleMappings.iterator().next().getContainer().getId()).getRole(roleName);
            if (Objects.isNull(role)) {
                return false;
            }
            return RoleUtils.hasRole(roleMappings, role);
        }

        @Override
        public boolean isGroupInRole(String id, String role) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            RealmModel realm = session.getContext().getRealm();
            GroupModel group = KeycloakModelUtils.findGroupByPath(realm, id);
            return RoleUtils.hasRoleFromGroup(group, realm.getRole(role), false);
        }

        @Override
        public List<String> getUserRealmRoles(String id) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(isNotClientRole).map(RoleModel::getName).collect(Collectors.toList());
        }

        @Override
        public List<String> getUserClientRoles(String id, String clientId) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(RoleModel::isClientRole).map(RoleModel::getName).collect(Collectors.toList());
        }

        @Override
        public List<String> getUserGroups(String id) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getGroupsStream().map(ModelToRepresentation::buildGroupPath).collect(Collectors.toList());
        }

        @Override
        public Map<String, List<String>> getUserAttributes(String id) {
            return Collections.unmodifiableMap(getUser(id, authorizationProvider.getKeycloakSession()).getAttributes());
        }
    };
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) ClientModel(org.keycloak.models.ClientModel) java.util(java.util) Effect(org.keycloak.authorization.Decision.Effect) RealmModel(org.keycloak.models.RealmModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Predicate(java.util.function.Predicate) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) RoleUtils(org.keycloak.models.utils.RoleUtils) Policy(org.keycloak.authorization.model.Policy) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) UserModel(org.keycloak.models.UserModel) Logic(org.keycloak.representations.idm.authorization.Logic) GroupModel(org.keycloak.models.GroupModel) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) KeycloakSession(org.keycloak.models.KeycloakSession) GroupModel(org.keycloak.models.GroupModel) RoleModel(org.keycloak.models.RoleModel)

Example 43 with GroupModel

use of org.keycloak.models.GroupModel in project keycloak by keycloak.

the class UserResource method removeMembership.

@DELETE
@Path("groups/{groupId}")
@NoCache
public void removeMembership(@PathParam("groupId") String groupId) {
    auth.users().requireManageGroupMembership(user);
    GroupModel group = session.groups().getGroupById(realm, groupId);
    if (group == null) {
        throw new NotFoundException("Group not found");
    }
    auth.groups().requireManageMembership(group);
    try {
        if (user.isMemberOf(group)) {
            user.leaveGroup(group);
            adminEvent.operation(OperationType.DELETE).resource(ResourceType.GROUP_MEMBERSHIP).representation(ModelToRepresentation.toRepresentation(group, true)).resourcePath(session.getContext().getUri()).success();
        }
    } catch (ModelException me) {
        Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
        throw new ErrorResponseException(me.getMessage(), MessageFormat.format(messages.getProperty(me.getMessage(), me.getMessage()), me.getParameters()), Status.BAD_REQUEST);
    }
}
Also used : ModelException(org.keycloak.models.ModelException) GroupModel(org.keycloak.models.GroupModel) NotFoundException(javax.ws.rs.NotFoundException) ErrorResponseException(org.keycloak.services.ErrorResponseException) Properties(java.util.Properties) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 44 with GroupModel

use of org.keycloak.models.GroupModel in project keycloak by keycloak.

the class GroupsResource method addTopLevelGroup.

/**
 * create or add a top level realm groupSet or create child.  This will update the group and set the parent if it exists.  Create it and set the parent
 * if the group doesn't exist.
 *
 * @param rep
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addTopLevelGroup(GroupRepresentation rep) {
    auth.groups().requireManage();
    GroupModel child;
    Response.ResponseBuilder builder = Response.status(204);
    String groupName = rep.getName();
    if (ObjectUtil.isBlank(groupName)) {
        return ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
    }
    try {
        if (rep.getId() != null) {
            child = realm.getGroupById(rep.getId());
            if (child == null) {
                throw new NotFoundException("Could not find child by id");
            }
            realm.moveGroup(child, null);
            adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri());
        } else {
            child = realm.createGroup(groupName);
            GroupResource.updateGroup(rep, child);
            URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(child.getId()).build();
            builder.status(201).location(uri);
            rep.setId(child.getId());
            adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), child.getId());
        }
    } catch (ModelDuplicateException mde) {
        return ErrorResponse.exists("Top level group named '" + groupName + "' already exists.");
    }
    adminEvent.representation(rep).success();
    return builder.build();
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) GroupModel(org.keycloak.models.GroupModel) NotFoundException(javax.ws.rs.NotFoundException) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 45 with GroupModel

use of org.keycloak.models.GroupModel in project keycloak by keycloak.

the class GroupsResource method getGroupById.

/**
 * Does not expand hierarchy.  Subgroups will not be set.
 *
 * @param id
 * @return
 */
@Path("{id}")
public GroupResource getGroupById(@PathParam("id") String id) {
    GroupModel group = realm.getGroupById(id);
    if (group == null) {
        throw new NotFoundException("Could not find group by id");
    }
    GroupResource resource = new GroupResource(realm, group, session, this.auth, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(resource);
    return resource;
}
Also used : GroupModel(org.keycloak.models.GroupModel) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path)

Aggregations

GroupModel (org.keycloak.models.GroupModel)72 RealmModel (org.keycloak.models.RealmModel)40 Test (org.junit.Test)26 ComponentModel (org.keycloak.component.ComponentModel)23 UserModel (org.keycloak.models.UserModel)20 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)18 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)13 GroupLDAPStorageMapper (org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper)12 RoleModel (org.keycloak.models.RoleModel)10 ClientModel (org.keycloak.models.ClientModel)9 GroupLDAPStorageMapperFactory (org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapperFactory)9 HashMap (java.util.HashMap)8 List (java.util.List)8 NotFoundException (javax.ws.rs.NotFoundException)7 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)7 HashSet (java.util.HashSet)6 Map (java.util.Map)6 Collectors (java.util.stream.Collectors)6 Path (javax.ws.rs.Path)6 Policy (org.keycloak.authorization.model.Policy)6