Search in sources :

Example 1 with Membership

use of io.gravitee.repository.management.model.Membership in project gravitee-management-rest-api by gravitee-io.

the class MembershipService_GetMembersTest method shouldGetMembersWithMembership.

@Test
public void shouldGetMembersWithMembership() throws Exception {
    Membership membership = new Membership();
    membership.setReferenceId(API_ID);
    membership.setCreatedAt(new Date());
    membership.setUpdatedAt(membership.getCreatedAt());
    membership.setReferenceType(MembershipReferenceType.API);
    membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
    membership.setUserId("user-id");
    UserEntity userEntity = new UserEntity();
    userEntity.setUsername(membership.getUserId());
    userEntity.setFirstname("John");
    userEntity.setLastname("Doe");
    RoleEntity po = mock(RoleEntity.class);
    po.setScope(io.gravitee.management.model.permissions.RoleScope.API);
    po.setName(SystemRole.PRIMARY_OWNER.name());
    when(membershipRepository.findByReferenceAndRole(MembershipReferenceType.API, API_ID, RoleScope.API, SystemRole.PRIMARY_OWNER.name())).thenReturn(Collections.singleton(membership));
    when(userService.findById(membership.getUserId())).thenReturn(userEntity);
    when(membershipRepository.findById(userEntity.getUsername(), MembershipReferenceType.API, API_ID)).thenReturn(of(membership));
    when(roleService.findById(RoleScope.API, SystemRole.PRIMARY_OWNER.name())).thenReturn(po);
    Set<MemberEntity> members = membershipService.getMembers(MembershipReferenceType.API, API_ID, RoleScope.API, SystemRole.PRIMARY_OWNER.name());
    Assert.assertNotNull(members);
    Assert.assertFalse("members must not be empty", members.isEmpty());
    verify(membershipRepository, times(1)).findByReferenceAndRole(MembershipReferenceType.API, API_ID, RoleScope.API, SystemRole.PRIMARY_OWNER.name());
    verify(userService, times(1)).findById(membership.getUserId());
}
Also used : RoleEntity(io.gravitee.management.model.RoleEntity) Membership(io.gravitee.repository.management.model.Membership) MemberEntity(io.gravitee.management.model.MemberEntity) Date(java.util.Date) UserEntity(io.gravitee.management.model.UserEntity) Test(org.junit.Test)

Example 2 with Membership

use of io.gravitee.repository.management.model.Membership in project gravitee-management-rest-api by gravitee-io.

the class MembershipService_GetMembersTest method shouldGetMembersWithoutMembership.

@Test
public void shouldGetMembersWithoutMembership() throws Exception {
    Membership membership = new Membership();
    membership.setReferenceId(API_ID);
    membership.setCreatedAt(new Date());
    membership.setUpdatedAt(membership.getCreatedAt());
    membership.setReferenceType(MembershipReferenceType.API);
    membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
    membership.setUserId("user-id");
    UserEntity userEntity = new UserEntity();
    userEntity.setUsername(membership.getUserId());
    userEntity.setFirstname("John");
    userEntity.setLastname("Doe");
    RoleEntity po = mock(RoleEntity.class);
    po.setScope(io.gravitee.management.model.permissions.RoleScope.API);
    po.setName(SystemRole.PRIMARY_OWNER.name());
    when(membershipRepository.findByReferenceAndRole(MembershipReferenceType.API, API_ID, RoleScope.API, null)).thenReturn(Collections.singleton(membership));
    when(userService.findById(membership.getUserId())).thenReturn(userEntity);
    when(membershipRepository.findById(userEntity.getUsername(), MembershipReferenceType.API, API_ID)).thenReturn(of(membership));
    when(roleService.findById(RoleScope.API, SystemRole.PRIMARY_OWNER.name())).thenReturn(po);
    Set<MemberEntity> members = membershipService.getMembers(MembershipReferenceType.API, API_ID, RoleScope.API);
    Assert.assertNotNull(members);
    Assert.assertFalse("members must not be empty", members.isEmpty());
    verify(membershipRepository, times(1)).findByReferenceAndRole(MembershipReferenceType.API, API_ID, RoleScope.API, null);
    verify(userService, times(1)).findById(membership.getUserId());
}
Also used : RoleEntity(io.gravitee.management.model.RoleEntity) Membership(io.gravitee.repository.management.model.Membership) MemberEntity(io.gravitee.management.model.MemberEntity) Date(java.util.Date) UserEntity(io.gravitee.management.model.UserEntity) Test(org.junit.Test)

Example 3 with Membership

use of io.gravitee.repository.management.model.Membership in project gravitee-management-rest-api by gravitee-io.

the class MembershipServiceImpl method addOrUpdateMember.

@Override
public MemberEntity addOrUpdateMember(MembershipReference reference, MembershipUser user, MembershipRole role) {
    try {
        LOGGER.debug("Add a new member for {} {}", reference.getType(), reference.getId());
        RoleEntity roleEntity = roleService.findById(role.getScope(), role.getName());
        if (API.equals(reference.getType()) && !io.gravitee.management.model.permissions.RoleScope.API.equals(roleEntity.getScope())) {
            throw new NotAuthorizedMembershipException(role.getName());
        } else if (MembershipReferenceType.APPLICATION.equals(reference.getType()) && !io.gravitee.management.model.permissions.RoleScope.APPLICATION.equals(roleEntity.getScope())) {
            throw new NotAuthorizedMembershipException(role.getName());
        } else if (MembershipReferenceType.GROUP.equals(reference.getType()) && !io.gravitee.management.model.permissions.RoleScope.APPLICATION.equals(roleEntity.getScope()) && !io.gravitee.management.model.permissions.RoleScope.API.equals(roleEntity.getScope())) {
            throw new NotAuthorizedMembershipException(role.getName());
        }
        UserEntity userEntity;
        if (user.getId() != null) {
            userEntity = userService.findById(user.getId());
        } else {
            // We have a user reference, meaning that the user is coming from an external system
            // User does not exist so we are looking into defined providers
            Optional<io.gravitee.management.model.providers.User> providerUser = identityService.findByReference(user.getReference());
            if (providerUser.isPresent()) {
                try {
                    userEntity = userService.findByUsername(providerUser.get().getUsername(), false);
                } catch (UserNotFoundException unfe) {
                    User identityUser = providerUser.get();
                    // The user is not yet registered in repository
                    // Information will be updated after the first connection of the user
                    NewExternalUserEntity newUser = new NewExternalUserEntity();
                    newUser.setUsername(identityUser.getUsername());
                    newUser.setFirstname(identityUser.getFirstname());
                    newUser.setLastname(identityUser.getLastname());
                    newUser.setSource(identityUser.getSource());
                    newUser.setEmail(identityUser.getEmail());
                    newUser.setSourceId(identityUser.getSourceId());
                    userEntity = userService.create(newUser, true);
                }
            } else {
                throw new UserNotFoundException(user.getReference());
            }
        }
        Optional<Membership> optionalMembership = membershipRepository.findById(userEntity.getId(), reference.getType(), reference.getId());
        Date updateDate = new Date();
        Membership returnedMembership;
        if (optionalMembership.isPresent()) {
            Membership updatedMembership = optionalMembership.get();
            Membership previousMembership = new Membership(updatedMembership);
            updatedMembership.getRoles().put(role.getScope().getId(), role.getName());
            updatedMembership.setUpdatedAt(updateDate);
            returnedMembership = membershipRepository.update(optionalMembership.get());
            createAuditLog(MEMBERSHIP_UPDATED, updatedMembership.getUpdatedAt(), previousMembership, updatedMembership);
        } else {
            Membership membership = new Membership(userEntity.getId(), reference.getId(), reference.getType());
            membership.setRoles(Collections.singletonMap(role.getScope().getId(), role.getName()));
            membership.setCreatedAt(updateDate);
            membership.setUpdatedAt(updateDate);
            returnedMembership = membershipRepository.create(membership);
            createAuditLog(MEMBERSHIP_CREATED, membership.getCreatedAt(), null, membership);
            if (userEntity.getEmail() != null && !userEntity.getEmail().isEmpty()) {
                EmailNotification emailNotification = buildEmailNotification(userEntity, reference.getType(), reference.getId());
                if (emailNotification != null) {
                    emailService.sendAsyncEmailNotification(emailNotification);
                }
            }
        }
        return convert(returnedMembership, role.getScope());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to add member for {} {}", reference.getType(), reference.getId(), ex);
        throw new TechnicalManagementException("An error occurs while trying to add member for " + reference.getType() + " " + reference.getId(), ex);
    }
}
Also used : User(io.gravitee.management.model.providers.User) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Membership(io.gravitee.repository.management.model.Membership) io.gravitee.management.model(io.gravitee.management.model)

Example 4 with Membership

use of io.gravitee.repository.management.model.Membership in project gravitee-management-rest-api by gravitee-io.

the class MembershipServiceImpl method deleteMember.

@Override
public void deleteMember(MembershipReferenceType referenceType, String referenceId, String userId) {
    try {
        LOGGER.debug("Delete member {} for {} {}", userId, referenceType, referenceId);
        if (!MembershipReferenceType.GROUP.equals(referenceType)) {
            RoleScope roleScope = getScopeByMembershipReferenceType(referenceType);
            RoleEntity roleEntity = this.getRole(referenceType, referenceId, userId, roleScope);
            if (roleEntity != null && PRIMARY_OWNER.name().equals(roleEntity.getName())) {
                throw new SinglePrimaryOwnerException(referenceType.equals(API) ? RoleScope.API : RoleScope.APPLICATION);
            }
        }
        Membership membership = new Membership(userId, referenceId, referenceType);
        membershipRepository.delete(membership);
        createAuditLog(MEMBERSHIP_DELETED, new Date(), membership, null);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to delete member {} for {} {}", userId, referenceType, referenceId, ex);
        throw new TechnicalManagementException("An error occurs while trying to delete member " + userId + " for " + referenceType + " " + referenceId, ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) RoleScope(io.gravitee.repository.management.model.RoleScope) Membership(io.gravitee.repository.management.model.Membership)

Example 5 with Membership

use of io.gravitee.repository.management.model.Membership in project gravitee-management-rest-api by gravitee-io.

the class ApiService_ExportAsJsonTest method setUp.

@Before
public void setUp() throws TechnicalException {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
    Api api = new Api();
    api.setId(API_ID);
    api.setDescription("Gravitee.io");
    when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
    PageEntity page = new PageEntity();
    page.setName("My Title");
    page.setOrder(1);
    page.setType(PageType.MARKDOWN.toString());
    page.setContent("Read the doc");
    when(pageService.findApiPagesByApi(API_ID)).thenReturn(Collections.singletonList(new PageListItem()));
    when(pageService.findById(any())).thenReturn(page);
    Membership membership = new Membership();
    membership.setUserId("johndoe");
    membership.setReferenceId(API_ID);
    membership.setReferenceType(MembershipReferenceType.API);
    membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
    when(membershipRepository.findByReferenceAndRole(eq(MembershipReferenceType.API), eq(API_ID), any(), any())).thenReturn(Collections.singleton(membership));
    MemberEntity memberEntity = new MemberEntity();
    memberEntity.setUsername(membership.getUserId());
    memberEntity.setRole(SystemRole.PRIMARY_OWNER.name());
    when(membershipService.getMembers(eq(MembershipReferenceType.API), eq(API_ID), eq(RoleScope.API))).thenReturn(Collections.singleton(memberEntity));
    UserEntity userEntity = new UserEntity();
    userEntity.setUsername(memberEntity.getId());
    when(userService.findByUsername(memberEntity.getId(), false)).thenReturn(userEntity);
    api.setGroups(Collections.singleton("my-group"));
    GroupEntity groupEntity = new GroupEntity();
    groupEntity.setId("my-group");
    groupEntity.setName("My Group");
    when(groupService.findByIds(api.getGroups())).thenReturn(Collections.singleton(groupEntity));
    PlanEntity publishedPlan = new PlanEntity();
    publishedPlan.setId("plan-id");
    publishedPlan.setApis(Collections.singleton(API_ID));
    publishedPlan.setDescription("free plan");
    publishedPlan.setType(PlanType.API);
    publishedPlan.setSecurity(PlanSecurityType.API_KEY);
    publishedPlan.setValidation(PlanValidationType.AUTO);
    publishedPlan.setStatus(PlanStatus.PUBLISHED);
    Map<String, Path> paths = new HashMap<>();
    Path path = new Path();
    path.setPath("/");
    io.gravitee.definition.model.Rule rule = new io.gravitee.definition.model.Rule();
    rule.setEnabled(true);
    rule.setMethods(Collections.singletonList(HttpMethod.GET));
    Policy policy = new Policy();
    policy.setName("rate-limit");
    String ls = System.lineSeparator();
    policy.setConfiguration("{" + ls + "          \"rate\": {" + ls + "            \"limit\": 1," + ls + "            \"periodTime\": 1," + ls + "            \"periodTimeUnit\": \"SECONDS\"" + ls + "          }" + ls + "        }");
    rule.setPolicy(policy);
    path.setRules(Collections.singletonList(rule));
    paths.put("/", path);
    publishedPlan.setPaths(paths);
    PlanEntity closedPlan = new PlanEntity();
    closedPlan.setId("closedPlan-id");
    closedPlan.setApis(Collections.singleton(API_ID));
    closedPlan.setDescription("free closedPlan");
    closedPlan.setType(PlanType.API);
    closedPlan.setSecurity(PlanSecurityType.API_KEY);
    closedPlan.setValidation(PlanValidationType.AUTO);
    closedPlan.setStatus(PlanStatus.CLOSED);
    closedPlan.setPaths(paths);
    Set<PlanEntity> set = new HashSet<>();
    set.add(publishedPlan);
    set.add(closedPlan);
    when(planService.findByApi(API_ID)).thenReturn(set);
}
Also used : Path(io.gravitee.definition.model.Path) Policy(io.gravitee.definition.model.Policy) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Membership(io.gravitee.repository.management.model.Membership) PropertyFilter(com.fasterxml.jackson.databind.ser.PropertyFilter) ApiPermissionFilter(io.gravitee.management.service.jackson.filter.ApiPermissionFilter) io.gravitee.management.model(io.gravitee.management.model) Api(io.gravitee.repository.management.model.Api) Before(org.junit.Before)

Aggregations

Membership (io.gravitee.repository.management.model.Membership)20 Test (org.junit.Test)15 UserEntity (io.gravitee.management.model.UserEntity)8 ApplicationEntity (io.gravitee.management.model.ApplicationEntity)6 RoleEntity (io.gravitee.management.model.RoleEntity)4 MemberEntity (io.gravitee.management.model.MemberEntity)3 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)3 Proxy (io.gravitee.definition.model.Proxy)2 io.gravitee.management.model (io.gravitee.management.model)2 ApiEntity (io.gravitee.management.model.ApiEntity)2 GroupEntity (io.gravitee.management.model.GroupEntity)2 UpdateApplicationEntity (io.gravitee.management.model.UpdateApplicationEntity)2 Application (io.gravitee.repository.management.model.Application)2 Date (java.util.Date)2 ArgumentMatcher (org.mockito.ArgumentMatcher)2 PropertyFilter (com.fasterxml.jackson.databind.ser.PropertyFilter)1 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)1 Path (io.gravitee.definition.model.Path)1 Policy (io.gravitee.definition.model.Policy)1 UpdateApiEntity (io.gravitee.management.model.UpdateApiEntity)1