Search in sources :

Example 1 with RoleScope

use of io.gravitee.rest.api.model.permissions.RoleScope in project gravitee-management-rest-api by gravitee-io.

the class MembershipCommandHandler method handle.

@Override
public Single<MembershipReply> handle(MembershipCommand command) {
    MembershipPayload membershipPayload = command.getPayload();
    GraviteeContext.setCurrentOrganization(membershipPayload.getOrganizationId());
    try {
        RoleScope roleScope;
        MembershipReferenceType membershipReferenceType;
        try {
            roleScope = RoleScope.valueOf(membershipPayload.getReferenceType());
            membershipReferenceType = MembershipReferenceType.valueOf(membershipPayload.getReferenceType());
        } catch (Exception e) {
            logger.error("Invalid referenceType [{}].", membershipPayload.getReferenceType());
            return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
        }
        final UserEntity userEntity = userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false);
        final RoleEntity roleEntity = findRole(roleScope, membershipPayload.getRole());
        final MembershipService.MembershipReference membershipReference = new MembershipService.MembershipReference(membershipReferenceType, membershipPayload.getReferenceId());
        final MembershipService.MembershipMember membershipMember = new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER);
        final MembershipService.MembershipRole membershipRole = new MembershipService.MembershipRole(roleEntity.getScope(), roleEntity.getName());
        membershipService.updateRolesToMemberOnReference(membershipReference, membershipMember, Collections.singletonList(membershipRole), COCKPIT_SOURCE, false);
        logger.info("Role [{}] assigned on {} [{}] for user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), userEntity.getId(), membershipPayload.getOrganizationId());
        return Single.just(new MembershipReply(command.getId(), CommandStatus.SUCCEEDED));
    } catch (Exception e) {
        logger.error("Error occurred when trying to assign role [{}] on {} [{}] for cockpit user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), membershipPayload.getUserId(), membershipPayload.getOrganizationId(), e);
        return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
    } finally {
        GraviteeContext.cleanContext();
    }
}
Also used : MembershipReply(io.gravitee.cockpit.api.command.membership.MembershipReply) RoleNotFoundException(io.gravitee.rest.api.service.exceptions.RoleNotFoundException) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) MembershipService(io.gravitee.rest.api.service.MembershipService) MembershipPayload(io.gravitee.cockpit.api.command.membership.MembershipPayload) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType)

Example 2 with RoleScope

use of io.gravitee.rest.api.model.permissions.RoleScope in project gravitee-management-rest-api by gravitee-io.

the class GroupMembersResource method addOrUpdateGroupMember.

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add or update a group member")
@ApiResponses({ @ApiResponse(code = 201, message = "Member has been added"), @ApiResponse(code = 200, message = "Member has been updated"), @ApiResponse(code = 400, message = "Membership is not valid"), @ApiResponse(code = 500, message = "Internal server error") })
@Permissions({ @Permission(value = ENVIRONMENT_GROUP, acls = RolePermissionAction.CREATE), @Permission(value = ENVIRONMENT_GROUP, acls = RolePermissionAction.UPDATE), @Permission(value = RolePermission.GROUP_MEMBER, acls = RolePermissionAction.CREATE), @Permission(value = RolePermission.GROUP_MEMBER, acls = RolePermissionAction.UPDATE) })
public Response addOrUpdateGroupMember(@Valid @NotNull final List<GroupMembership> memberships) {
    // Check that group exists
    final GroupEntity groupEntity = groupService.findById(group);
    // check if user is a 'simple group admin' or a platform admin
    final boolean hasPermission = permissionService.hasPermission(ENVIRONMENT_GROUP, GraviteeContext.getCurrentEnvironment(), CREATE, UPDATE, DELETE);
    if (!hasPermission) {
        if (groupEntity.getMaxInvitation() != null) {
            final Set<MemberEntity> members = membershipService.getMembersByReference(MembershipReferenceType.GROUP, group);
            final long membershipsToAddSize = memberships.stream().map(GroupMembership::getId).filter(s -> {
                final List<String> membershipIdsToSave = members.stream().map(MemberEntity::getId).collect(toList());
                return !membershipIdsToSave.contains(s);
            }).count();
            if ((groupService.getNumberOfMembers(group) + membershipsToAddSize) > groupEntity.getMaxInvitation()) {
                throw new GroupMembersLimitationExceededException(groupEntity.getMaxInvitation());
            }
        }
        if (!groupEntity.isSystemInvitation()) {
            throw new GroupInvitationForbiddenException(SYSTEM, group);
        }
    }
    for (GroupMembership membership : memberships) {
        RoleEntity previousApiRole = null;
        RoleEntity previousApplicationRole = null;
        RoleEntity previousGroupRole = null;
        if (membership.getId() != null) {
            Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, membership.getId());
            for (RoleEntity role : userRoles) {
                switch(role.getScope()) {
                    case API:
                        previousApiRole = role;
                        break;
                    case APPLICATION:
                        previousApplicationRole = role;
                        break;
                    case GROUP:
                        previousGroupRole = role;
                        break;
                    default:
                        break;
                }
            }
        }
        // Process add / update before delete to avoid having a user without role
        if (membership.getRoles() != null && !membership.getRoles().isEmpty()) {
            Map<RoleScope, RoleEntity> roleEntities = new HashMap<>();
            for (MemberRoleEntity item : membership.getRoles()) {
                roleService.findByScopeAndName(item.getRoleScope(), item.getRoleName()).ifPresent(roleEntity -> roleEntities.put(item.getRoleScope(), roleEntity));
            }
            MemberEntity updatedMembership = null;
            // Replace if new role to add
            RoleEntity apiRoleEntity = roleEntities.get(RoleScope.API);
            if (apiRoleEntity != null && !apiRoleEntity.equals(previousApiRole)) {
                String roleName = apiRoleEntity.getName();
                if (!hasPermission && groupEntity.isLockApiRole()) {
                    final List<RoleEntity> defaultRoles = roleService.findDefaultRoleByScopes(RoleScope.API);
                    if (defaultRoles != null && !defaultRoles.isEmpty()) {
                        roleName = defaultRoles.get(0).getName();
                    }
                }
                updatedMembership = membershipService.addRoleToMemberOnReference(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, group), new MembershipService.MembershipMember(membership.getId(), membership.getReference(), MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.API, roleName));
                if (previousApiRole != null) {
                    membershipService.removeRole(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, updatedMembership.getId(), previousApiRole.getId());
                }
                if (previousApiRole != null && previousApiRole.getName().equals(SystemRole.PRIMARY_OWNER.name())) {
                    groupService.updateApiPrimaryOwner(group, null);
                } else if (roleName.equals(SystemRole.PRIMARY_OWNER.name())) {
                    groupService.updateApiPrimaryOwner(group, updatedMembership.getId());
                }
            }
            RoleEntity applicationRoleEntity = roleEntities.get(RoleScope.APPLICATION);
            if (applicationRoleEntity != null && !applicationRoleEntity.equals(previousApplicationRole)) {
                String roleName = applicationRoleEntity.getName();
                if (!hasPermission && groupEntity.isLockApplicationRole()) {
                    final List<RoleEntity> defaultRoles = roleService.findDefaultRoleByScopes(RoleScope.APPLICATION);
                    if (defaultRoles != null && !defaultRoles.isEmpty()) {
                        roleName = defaultRoles.get(0).getName();
                    }
                }
                updatedMembership = membershipService.addRoleToMemberOnReference(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, group), new MembershipService.MembershipMember(membership.getId(), membership.getReference(), MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.APPLICATION, roleName));
                if (previousApplicationRole != null) {
                    membershipService.removeRole(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, updatedMembership.getId(), previousApplicationRole.getId());
                }
            }
            RoleEntity groupRoleEntity = roleEntities.get(RoleScope.GROUP);
            if (groupRoleEntity != null && !groupRoleEntity.equals(previousGroupRole)) {
                updatedMembership = membershipService.addRoleToMemberOnReference(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, group), new MembershipService.MembershipMember(membership.getId(), membership.getReference(), MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.GROUP, groupRoleEntity.getName()));
                if (previousGroupRole != null) {
                    membershipService.removeRole(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, updatedMembership.getId(), previousGroupRole.getId());
                }
            }
            // Delete if existing and new role is empty
            if (apiRoleEntity == null && previousApiRole != null) {
                membershipService.removeRole(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, membership.getId(), previousApiRole.getId());
            }
            if (applicationRoleEntity == null && previousApplicationRole != null) {
                membershipService.removeRole(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, membership.getId(), previousApplicationRole.getId());
            }
            if (groupRoleEntity == null && previousGroupRole != null) {
                membershipService.removeRole(MembershipReferenceType.GROUP, group, MembershipMemberType.USER, membership.getId(), previousGroupRole.getId());
            }
            // Send notification
            if (previousApiRole == null && previousApplicationRole == null && previousGroupRole == null && updatedMembership != null) {
                UserEntity userEntity = this.userService.findById(updatedMembership.getId());
                Map<String, Object> params = new HashMap<>();
                params.put("group", groupEntity);
                params.put("user", userEntity);
                this.notifierService.trigger(GROUP_INVITATION, params);
            }
        }
    }
    eventManager.publishEvent(ApplicationAlertEventType.APPLICATION_MEMBERSHIP_UPDATE, new ApplicationAlertMembershipEvent(Collections.emptySet(), Collections.singleton(group)));
    return Response.ok().build();
}
Also used : GROUP_INVITATION(io.gravitee.rest.api.service.notification.PortalHook.GROUP_INVITATION) PagedResult(io.gravitee.rest.api.management.rest.model.PagedResult) GroupMembersLimitationExceededException(io.gravitee.rest.api.service.exceptions.GroupMembersLimitationExceededException) java.util(java.util) Page(io.gravitee.common.data.domain.Page) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) ApplicationAlertEventType(io.gravitee.rest.api.model.alert.ApplicationAlertEventType) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) ApplicationAlertMembershipEvent(io.gravitee.rest.api.model.alert.ApplicationAlertMembershipEvent) Inject(javax.inject.Inject) Valid(javax.validation.Valid) GroupMembership(io.gravitee.rest.api.management.rest.model.GroupMembership) UserService(io.gravitee.rest.api.service.UserService) io.gravitee.rest.api.model(io.gravitee.rest.api.model) io.swagger.annotations(io.swagger.annotations) NotifierService(io.gravitee.rest.api.service.NotifierService) GroupInvitationForbiddenException(io.gravitee.rest.api.service.exceptions.GroupInvitationForbiddenException) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) GroupService(io.gravitee.rest.api.service.GroupService) Context(javax.ws.rs.core.Context) MembershipService(io.gravitee.rest.api.service.MembershipService) SYSTEM(io.gravitee.rest.api.service.exceptions.GroupInvitationForbiddenException.Type.SYSTEM) Pageable(io.gravitee.rest.api.management.rest.model.Pageable) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Permission(io.gravitee.rest.api.management.rest.security.Permission) Collectors.toList(java.util.stream.Collectors.toList) MediaType(io.gravitee.common.http.MediaType) ENVIRONMENT_GROUP(io.gravitee.rest.api.model.permissions.RolePermission.ENVIRONMENT_GROUP) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) EventManager(io.gravitee.common.event.EventManager) ResourceContext(javax.ws.rs.container.ResourceContext) ApplicationService(io.gravitee.rest.api.service.ApplicationService) Permissions(io.gravitee.rest.api.management.rest.security.Permissions) SystemRole(io.gravitee.rest.api.model.permissions.SystemRole) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) GroupMembership(io.gravitee.rest.api.management.rest.model.GroupMembership) ApplicationAlertMembershipEvent(io.gravitee.rest.api.model.alert.ApplicationAlertMembershipEvent) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) GroupInvitationForbiddenException(io.gravitee.rest.api.service.exceptions.GroupInvitationForbiddenException) Collectors.toList(java.util.stream.Collectors.toList) GroupMembersLimitationExceededException(io.gravitee.rest.api.service.exceptions.GroupMembersLimitationExceededException) Permissions(io.gravitee.rest.api.management.rest.security.Permissions)

Example 3 with RoleScope

use of io.gravitee.rest.api.model.permissions.RoleScope in project gravitee-management-rest-api by gravitee-io.

the class MembershipServiceImpl method getPrimaryOwner.

@Override
public MembershipEntity getPrimaryOwner(MembershipReferenceType referenceType, String referenceId) {
    RoleScope poRoleScope;
    if (referenceType == MembershipReferenceType.API) {
        poRoleScope = RoleScope.API;
    } else if (referenceType == MembershipReferenceType.APPLICATION) {
        poRoleScope = RoleScope.APPLICATION;
    } else {
        throw new RoleNotFoundException(referenceType.name() + "_PRIMARY_OWNER");
    }
    RoleEntity poRole = roleService.findPrimaryOwnerRoleByOrganization(GraviteeContext.getCurrentOrganization(), poRoleScope);
    if (poRole != null) {
        try {
            Optional<io.gravitee.repository.management.model.Membership> poMember = membershipRepository.findByReferenceAndRoleId(convert(referenceType), referenceId, poRole.getId()).stream().findFirst();
            if (poMember.isPresent()) {
                return convert(poMember.get());
            } else {
                return null;
            }
        } catch (TechnicalException ex) {
            LOGGER.error("An error occurs while trying to get primary owner for {} {} and role", referenceType, referenceId, ex);
            throw new TechnicalManagementException("An error occurs while trying to get primary owner for " + referenceType + " " + referenceId, ex);
        }
    } else {
        throw new RoleNotFoundException(referenceType.name() + "_PRIMARY_OWNER");
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope)

Example 4 with RoleScope

use of io.gravitee.rest.api.model.permissions.RoleScope in project gravitee-management-rest-api by gravitee-io.

the class GroupService_UpdateTest method shouldUpdateGroup.

@Test
public void shouldUpdateGroup() throws Exception {
    UpdateGroupEntity updatedGroupEntity = new UpdateGroupEntity();
    updatedGroupEntity.setDisableMembershipNotifications(true);
    updatedGroupEntity.setEmailInvitation(true);
    updatedGroupEntity.setEventRules(null);
    updatedGroupEntity.setLockApiRole(true);
    updatedGroupEntity.setLockApplicationRole(true);
    updatedGroupEntity.setMaxInvitation(100);
    updatedGroupEntity.setName("my-group-name");
    updatedGroupEntity.setRoles(Maps.<RoleScope, String>builder().put(RoleScope.API, "OWNER").build());
    updatedGroupEntity.setSystemInvitation(false);
    when(groupRepository.findById(GROUP_ID)).thenReturn(Optional.of(Mockito.mock(Group.class)));
    when(permissionService.hasPermission(RolePermission.ENVIRONMENT_GROUP, "DEFAULT", CREATE, UPDATE, DELETE)).thenReturn(true);
    when(membershipService.getRoles(any(), any(), any(), any())).thenReturn(Collections.emptySet());
    groupService.update(GROUP_ID, updatedGroupEntity);
    verify(groupRepository).update(argThat(group -> group.isDisableMembershipNotifications() && group.isEmailInvitation() && group.getEventRules() == null && group.isLockApiRole() && group.isLockApplicationRole() && group.getMaxInvitation() == 100 && group.getName().equals("my-group-name") && !group.isSystemInvitation()));
    verify(membershipService).addRoleToMemberOnReference(argThat(membershipReference -> membershipReference.getType() == MembershipReferenceType.API && membershipReference.getId() == null), argThat(membershipMember -> membershipMember.getMemberId().equals(GROUP_ID) && membershipMember.getReference() == null && membershipMember.getMemberType() == MembershipMemberType.GROUP), argThat(membershipRole -> membershipRole.getScope() == RoleScope.API && membershipRole.getName().equals("OWNER")));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) InjectMocks(org.mockito.InjectMocks) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) GroupRepository(io.gravitee.repository.management.api.GroupRepository) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) Group(io.gravitee.repository.management.model.Group) Test(org.junit.Test) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) Maps(io.gravitee.common.util.Maps) Mockito(org.mockito.Mockito) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) Optional(java.util.Optional) GroupServiceImpl(io.gravitee.rest.api.service.impl.GroupServiceImpl) Collections(java.util.Collections) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) UpdateGroupEntity(io.gravitee.rest.api.model.UpdateGroupEntity) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) UpdateGroupEntity(io.gravitee.rest.api.model.UpdateGroupEntity) Test(org.junit.Test)

Example 5 with RoleScope

use of io.gravitee.rest.api.model.permissions.RoleScope in project gravitee-management-rest-api by gravitee-io.

the class GroupService_UpdateTest method shouldNotUpdateDefaultRoleBecausePrimaryOwner.

@Test
public void shouldNotUpdateDefaultRoleBecausePrimaryOwner() throws Exception {
    UpdateGroupEntity updatedGroupEntity = new UpdateGroupEntity();
    updatedGroupEntity.setRoles(Maps.<RoleScope, String>builder().put(RoleScope.API, "PRIMARY_OWNER").put(RoleScope.APPLICATION, "PRIMARY_OWNER").build());
    when(groupRepository.findById(GROUP_ID)).thenReturn(Optional.of(Mockito.mock(Group.class)));
    when(permissionService.hasPermission(RolePermission.ENVIRONMENT_GROUP, "DEFAULT", CREATE, UPDATE, DELETE)).thenReturn(true);
    when(membershipService.getRoles(any(), any(), any(), any())).thenReturn(Collections.emptySet());
    groupService.update(GROUP_ID, updatedGroupEntity);
    verify(membershipService, never()).deleteReferenceMember(any(), any(), any(), any());
    verify(membershipService, never()).addRoleToMemberOnReference(any(), any(), any());
}
Also used : RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) UpdateGroupEntity(io.gravitee.rest.api.model.UpdateGroupEntity) Test(org.junit.Test)

Aggregations

RoleScope (io.gravitee.rest.api.model.permissions.RoleScope)5 MembershipReferenceType (io.gravitee.rest.api.model.MembershipReferenceType)2 UpdateGroupEntity (io.gravitee.rest.api.model.UpdateGroupEntity)2 RolePermission (io.gravitee.rest.api.model.permissions.RolePermission)2 RolePermissionAction (io.gravitee.rest.api.model.permissions.RolePermissionAction)2 MembershipService (io.gravitee.rest.api.service.MembershipService)2 Test (org.junit.Test)2 MembershipPayload (io.gravitee.cockpit.api.command.membership.MembershipPayload)1 MembershipReply (io.gravitee.cockpit.api.command.membership.MembershipReply)1 Page (io.gravitee.common.data.domain.Page)1 EventManager (io.gravitee.common.event.EventManager)1 MediaType (io.gravitee.common.http.MediaType)1 Maps (io.gravitee.common.util.Maps)1 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)1 GroupRepository (io.gravitee.repository.management.api.GroupRepository)1 Group (io.gravitee.repository.management.model.Group)1 GroupMembership (io.gravitee.rest.api.management.rest.model.GroupMembership)1 Pageable (io.gravitee.rest.api.management.rest.model.Pageable)1 PagedResult (io.gravitee.rest.api.management.rest.model.PagedResult)1 Permission (io.gravitee.rest.api.management.rest.security.Permission)1