Search in sources :

Example 6 with Permission

use of io.gravitee.rest.api.management.rest.security.Permission in project gravitee-management-rest-api by gravitee-io.

the class PlatformAnalyticsResource method getPlatformAnalytics.

@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get platform analytics", notes = "User must have the MANAGEMENT_PLATFORM[READ] permission to use this service")
@ApiResponses({ @ApiResponse(code = 200, message = "Platform analytics"), @ApiResponse(code = 500, message = "Internal server error") })
@Permissions({ @Permission(value = ENVIRONMENT_PLATFORM, acls = READ) })
public Response getPlatformAnalytics(@BeanParam AnalyticsParam analyticsParam) {
    analyticsParam.validate();
    Analytics analytics = null;
    // add filter by Apis or Applications
    String extraFilter = null;
    if (!isAdmin()) {
        String fieldName;
        List<String> ids;
        if ("application".equals(analyticsParam.getField())) {
            fieldName = "application";
            ids = applicationService.findByUser(getAuthenticatedUser()).stream().filter(app -> permissionService.hasPermission(APPLICATION_ANALYTICS, app.getId(), READ)).map(ApplicationListItem::getId).collect(Collectors.toList());
        } else {
            fieldName = "api";
            ids = apiService.findByUser(getAuthenticatedUser(), null, false).stream().filter(api -> permissionService.hasPermission(API_ANALYTICS, api.getId(), READ)).map(ApiEntity::getId).collect(Collectors.toList());
        }
        if (ids.isEmpty()) {
            return Response.noContent().build();
        }
        extraFilter = getExtraFilter(fieldName, ids);
    }
    if (analyticsParam.getQuery() != null) {
        analyticsParam.setQuery(analyticsParam.getQuery().replaceAll("\\?", "1"));
    }
    switch(analyticsParam.getTypeParam().getValue()) {
        case DATE_HISTO:
            analytics = executeDateHisto(analyticsParam, extraFilter);
            break;
        case GROUP_BY:
            analytics = executeGroupBy(analyticsParam, extraFilter);
            break;
        case COUNT:
            analytics = executeCount(analyticsParam, extraFilter);
            break;
        case STATS:
            analytics = executeStats(analyticsParam, extraFilter);
            break;
    }
    return Response.ok(analytics).build();
}
Also used : Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiResponses(io.swagger.annotations.ApiResponses) Function(java.util.function.Function) ApiService(io.gravitee.rest.api.service.ApiService) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) Aggregation(io.gravitee.rest.api.management.rest.resource.param.Aggregation) Map(java.util.Map) PermissionService(io.gravitee.rest.api.service.PermissionService) Analytics(io.gravitee.rest.api.model.analytics.Analytics) Api(io.swagger.annotations.Api) io.gravitee.rest.api.model.analytics.query(io.gravitee.rest.api.model.analytics.query) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) READ(io.gravitee.rest.api.model.permissions.RolePermissionAction.READ) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Collectors(java.util.stream.Collectors) BeanParam(javax.ws.rs.BeanParam) Permission(io.gravitee.rest.api.management.rest.security.Permission) List(java.util.List) MediaType(io.gravitee.common.http.MediaType) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) AnalyticsParam(io.gravitee.rest.api.management.rest.resource.param.AnalyticsParam) ApplicationService(io.gravitee.rest.api.service.ApplicationService) Range(io.gravitee.rest.api.management.rest.resource.param.Range) AnalyticsService(io.gravitee.rest.api.service.AnalyticsService) Permissions(io.gravitee.rest.api.management.rest.security.Permissions) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Analytics(io.gravitee.rest.api.model.analytics.Analytics) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) Permissions(io.gravitee.rest.api.management.rest.security.Permissions) ApiResponses(io.swagger.annotations.ApiResponses)

Example 7 with Permission

use of io.gravitee.rest.api.management.rest.security.Permission 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 8 with Permission

use of io.gravitee.rest.api.management.rest.security.Permission in project gravitee-management-rest-api by gravitee-io.

the class PoliciesResource method getSwaggerPolicy.

@GET
@Path("swagger")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "List policies which are handling Swagger / OAI definition", notes = "These policies are used when importing an OAI to create an API")
@Permissions({ @Permission(value = RolePermission.ENVIRONMENT_API, acls = RolePermissionAction.READ) })
public List<PolicyListItem> getSwaggerPolicy() {
    return policyOperationVisitorManager.getPolicyVisitors().stream().filter(operationVisitor -> operationVisitor.display()).map(operationVisitor -> {
        PolicyListItem item = new PolicyListItem();
        item.setId(operationVisitor.getId());
        item.setName(operationVisitor.getName());
        return item;
    }).sorted(Comparator.comparing(PolicyListItem::getName)).collect(Collectors.toList());
}
Also used : RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) Context(javax.ws.rs.core.Context) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) PolicyDevelopmentEntity(io.gravitee.rest.api.model.PolicyDevelopmentEntity) Collection(java.util.Collection) Path(javax.ws.rs.Path) PolicyService(io.gravitee.rest.api.service.PolicyService) PolicyOperationVisitorManager(io.gravitee.rest.api.service.impl.swagger.policy.PolicyOperationVisitorManager) Collectors(java.util.stream.Collectors) Permission(io.gravitee.rest.api.management.rest.security.Permission) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) List(java.util.List) MediaType(io.gravitee.common.http.MediaType) Stream(java.util.stream.Stream) QueryParam(javax.ws.rs.QueryParam) ResourceContext(javax.ws.rs.container.ResourceContext) PolicyEntity(io.gravitee.rest.api.model.PolicyEntity) Api(io.swagger.annotations.Api) Comparator(java.util.Comparator) Permissions(io.gravitee.rest.api.management.rest.security.Permissions) PolicyListItem(io.gravitee.rest.api.model.PolicyListItem) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) PolicyListItem(io.gravitee.rest.api.model.PolicyListItem) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) Permissions(io.gravitee.rest.api.management.rest.security.Permissions)

Example 9 with Permission

use of io.gravitee.rest.api.management.rest.security.Permission in project gravitee-management-rest-api by gravitee-io.

the class PermissionFilterTest method initManagementMocks.

/**
 * ENVIRONMENT Tests
 */
private void initManagementMocks() {
    Principal user = () -> USERNAME;
    when(securityContext.getUserPrincipal()).thenReturn(user);
    Permission perm = mock(Permission.class);
    when(perm.value()).thenReturn(RolePermission.ENVIRONMENT_API);
    when(perm.acls()).thenReturn(new RolePermissionAction[] { RolePermissionAction.UPDATE });
    when(permissions.value()).thenReturn(new Permission[] { perm });
    UriInfo uriInfo = mock(UriInfo.class);
    when(containerRequestContext.getUriInfo()).thenReturn(uriInfo);
}
Also used : Permission(io.gravitee.rest.api.management.rest.security.Permission) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) Principal(java.security.Principal) UriInfo(javax.ws.rs.core.UriInfo)

Example 10 with Permission

use of io.gravitee.rest.api.management.rest.security.Permission in project gravitee-management-rest-api by gravitee-io.

the class PermissionFilterTest method initApiMocks.

/**
 * API Tests
 */
private ApiEntity initApiMocks() {
    ApiEntity api = new ApiEntity();
    api.setId(API_ID);
    Principal user = () -> USERNAME;
    when(apiService.findById(api.getId())).thenReturn(api);
    when(securityContext.getUserPrincipal()).thenReturn(user);
    Permission perm = mock(Permission.class);
    when(perm.value()).thenReturn(RolePermission.API_ANALYTICS);
    when(perm.acls()).thenReturn(new RolePermissionAction[] { RolePermissionAction.UPDATE });
    when(permissions.value()).thenReturn(new Permission[] { perm });
    UriInfo uriInfo = mock(UriInfo.class);
    MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
    map.put("api", Collections.singletonList(api.getId()));
    when(uriInfo.getPathParameters()).thenReturn(map);
    when(containerRequestContext.getUriInfo()).thenReturn(uriInfo);
    return api;
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Permission(io.gravitee.rest.api.management.rest.security.Permission) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Principal(java.security.Principal) UriInfo(javax.ws.rs.core.UriInfo)

Aggregations

Permission (io.gravitee.rest.api.management.rest.security.Permission)10 RolePermission (io.gravitee.rest.api.model.permissions.RolePermission)9 MediaType (io.gravitee.common.http.MediaType)6 Permissions (io.gravitee.rest.api.management.rest.security.Permissions)6 Collectors (java.util.stream.Collectors)6 Inject (javax.inject.Inject)6 ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)5 RolePermissionAction (io.gravitee.rest.api.model.permissions.RolePermissionAction)5 io.swagger.annotations (io.swagger.annotations)4 Principal (java.security.Principal)4 List (java.util.List)4 ResourceContext (javax.ws.rs.container.ResourceContext)4 Context (javax.ws.rs.core.Context)4 ApplicationEntity (io.gravitee.rest.api.model.ApplicationEntity)3 javax.ws.rs (javax.ws.rs)3 GET (javax.ws.rs.GET)3 Produces (javax.ws.rs.Produces)3 Response (javax.ws.rs.core.Response)3 UriInfo (javax.ws.rs.core.UriInfo)3 Page (io.gravitee.common.data.domain.Page)2