Search in sources :

Example 16 with RoleEntity

use of io.gravitee.rest.api.model.RoleEntity 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.setRoleId("API_PRIMARY_OWNER");
    membership.setMemberId("user-id");
    membership.setMemberType(MembershipMemberType.USER);
    UserEntity userEntity = new UserEntity();
    userEntity.setId(membership.getMemberId());
    userEntity.setFirstname("John");
    userEntity.setLastname("Doe");
    RoleEntity po = mock(RoleEntity.class);
    po.setName(SystemRole.PRIMARY_OWNER.name());
    List<String> memberIds = Collections.singletonList(membership.getMemberId());
    Set<UserEntity> userEntities = Collections.singleton(userEntity);
    when(roleService.findById("API_PRIMARY_OWNER")).thenReturn(po);
    when(membershipRepository.findByReferencesAndRoleId(MembershipReferenceType.API, Collections.singletonList(API_ID), null)).thenReturn(Collections.singleton(membership));
    when(userService.findByIds(memberIds, false)).thenReturn(userEntities);
    Set<MemberEntity> members = membershipService.getMembersByReferenceAndRole(io.gravitee.rest.api.model.MembershipReferenceType.API, API_ID, null);
    Assert.assertNotNull(members);
    Assert.assertFalse("members must not be empty", members.isEmpty());
    verify(membershipRepository, times(1)).findByReferencesAndRoleId(MembershipReferenceType.API, Collections.singletonList(API_ID), null);
    verify(userService, times(1)).findByIds(memberIds, false);
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) Membership(io.gravitee.repository.management.model.Membership) MemberEntity(io.gravitee.rest.api.model.MemberEntity) Date(java.util.Date) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Example 17 with RoleEntity

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

the class AbstractAuthenticationResource method connectUser.

protected Response connectUser(String userId, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    UserEntity user = userService.connect(userId);
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    // Manage authorities, initialize it with dynamic permissions from the IDP
    List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
    // We must also load permissions from repository for configured environment role
    Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
    }
    // JWT signer
    Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
    Date issueAt = new Date();
    Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
    final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
    final Token tokenEntity = new Token();
    tokenEntity.setTokenType(TokenTypeEnum.BEARER);
    tokenEntity.setToken(sign);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) UserService(io.gravitee.rest.api.service.UserService) Duration(java.time.Duration) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) MembershipService(io.gravitee.rest.api.service.MembershipService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Token(io.gravitee.rest.api.portal.rest.model.Token) TokenTypeEnum(io.gravitee.rest.api.portal.rest.model.Token.TokenTypeEnum) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) Response(javax.ws.rs.core.Response) Environment(org.springframework.core.env.Environment) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) UserEntity(io.gravitee.rest.api.model.UserEntity) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 18 with RoleEntity

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

the class ApplicationMembersResourceTest method shouldTransferOwnerShip.

@Test
public void shouldTransferOwnerShip() {
    RoleEntity mockRoleEntity = new RoleEntity();
    TransferOwnershipInput input = new TransferOwnershipInput().newPrimaryOwnerId(MEMBER_1).primaryOwnerNewrole("OWNER");
    doReturn(Optional.of(mockRoleEntity)).when(roleService).findByScopeAndName(any(), any());
    final Response response = target(APPLICATION).path("members").path("_transfer_ownership").request().post(Entity.json(input));
    assertEquals(HttpStatusCode.NO_CONTENT_204, response.getStatus());
    ArgumentCaptor<String> applicationCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<List<RoleEntity>> roleCaptor = ArgumentCaptor.forClass(List.class);
    ArgumentCaptor<MembershipService.MembershipMember> memberShipUserCaptor = ArgumentCaptor.forClass(MembershipService.MembershipMember.class);
    Mockito.verify(membershipService).transferApplicationOwnership(applicationCaptor.capture(), memberShipUserCaptor.capture(), roleCaptor.capture());
    assertEquals(APPLICATION, applicationCaptor.getValue());
    assertEquals(mockRoleEntity, roleCaptor.getValue().get(0));
    assertEquals(MEMBER_1, memberShipUserCaptor.getValue().getMemberId());
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) Response(javax.ws.rs.core.Response) MembershipService(io.gravitee.rest.api.service.MembershipService) List(java.util.List) Test(org.junit.Test)

Example 19 with RoleEntity

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

the class MembershipCommandHandlerTest method handleWithAdminRole.

@Test
public void handleWithAdminRole() {
    MembershipPayload membershipPayload = new MembershipPayload();
    membershipPayload.setUserId("user#1");
    membershipPayload.setOrganizationId("orga#1");
    membershipPayload.setReferenceType(MembershipReferenceType.ENVIRONMENT.name());
    membershipPayload.setReferenceId("env#1");
    membershipPayload.setRole("ENVIRONMENT_PRIMARY_OWNER");
    MembershipCommand command = new MembershipCommand(membershipPayload);
    UserEntity user = new UserEntity();
    user.setId(UUID.random().toString());
    RoleEntity role = new RoleEntity();
    role.setId(UUID.random().toString());
    role.setScope(RoleScope.ENVIRONMENT);
    role.setName("ADMIN");
    when(userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false)).thenReturn(user);
    when(roleService.findByScopeAndName(RoleScope.ENVIRONMENT, "ADMIN")).thenReturn(Optional.of(role));
    TestObserver<MembershipReply> obs = cut.handle(command).test();
    obs.awaitTerminalEvent();
    obs.assertNoErrors();
    obs.assertValue(reply -> reply.getCommandId().equals(command.getId()) && reply.getCommandStatus().equals(CommandStatus.SUCCEEDED));
    ArgumentCaptor<MembershipService.MembershipReference> membershipReference = ArgumentCaptor.forClass(MembershipService.MembershipReference.class);
    ArgumentCaptor<MembershipService.MembershipMember> membershipMember = ArgumentCaptor.forClass(MembershipService.MembershipMember.class);
    ArgumentCaptor<List<MembershipService.MembershipRole>> membershipRoles = ArgumentCaptor.forClass(List.class);
    verify(membershipService).updateRolesToMemberOnReference(membershipReference.capture(), membershipMember.capture(), membershipRoles.capture(), eq(COCKPIT_SOURCE), eq(false));
    assertEquals(MembershipReferenceType.ENVIRONMENT, membershipReference.getValue().getType());
    assertEquals(membershipPayload.getReferenceId(), membershipReference.getValue().getId());
    assertEquals(MembershipMemberType.USER, membershipMember.getValue().getMemberType());
    assertEquals(user.getId(), membershipMember.getValue().getMemberId());
    assertTrue(membershipRoles.getValue().size() == 1 && membershipRoles.getValue().stream().allMatch(membershipRole -> membershipRole.getScope() == role.getScope() && membershipRole.getName().equals(role.getName())));
}
Also used : MembershipReply(io.gravitee.cockpit.api.command.membership.MembershipReply) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) MembershipService(io.gravitee.rest.api.service.MembershipService) MembershipPayload(io.gravitee.cockpit.api.command.membership.MembershipPayload) List(java.util.List) MembershipCommand(io.gravitee.cockpit.api.command.membership.MembershipCommand) Test(org.junit.Test)

Example 20 with RoleEntity

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

the class MembershipCommandHandlerTest method handleWithUnknownRole.

@Test
public void handleWithUnknownRole() {
    MembershipPayload membershipPayload = new MembershipPayload();
    membershipPayload.setUserId("user#1");
    membershipPayload.setOrganizationId("orga#1");
    membershipPayload.setReferenceType(MembershipReferenceType.ENVIRONMENT.name());
    membershipPayload.setReferenceId("env#1");
    membershipPayload.setRole("UNKNOWN");
    MembershipCommand command = new MembershipCommand(membershipPayload);
    UserEntity user = new UserEntity();
    user.setId(UUID.random().toString());
    RoleEntity role = new RoleEntity();
    role.setId(UUID.random().toString());
    when(userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false)).thenReturn(user);
    when(roleService.findByScopeAndName(RoleScope.ENVIRONMENT, "UNKNOWN")).thenReturn(Optional.empty());
    TestObserver<MembershipReply> obs = cut.handle(command).test();
    obs.awaitTerminalEvent();
    obs.assertNoErrors();
    obs.assertValue(reply -> reply.getCommandId().equals(command.getId()) && reply.getCommandStatus().equals(CommandStatus.ERROR));
    verifyZeroInteractions(membershipService);
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) MembershipReply(io.gravitee.cockpit.api.command.membership.MembershipReply) MembershipPayload(io.gravitee.cockpit.api.command.membership.MembershipPayload) UserEntity(io.gravitee.rest.api.model.UserEntity) MembershipCommand(io.gravitee.cockpit.api.command.membership.MembershipCommand) Test(org.junit.Test)

Aggregations

RoleEntity (io.gravitee.rest.api.model.RoleEntity)29 Test (org.junit.Test)20 UserEntity (io.gravitee.rest.api.model.UserEntity)13 Membership (io.gravitee.repository.management.model.Membership)8 MembershipService (io.gravitee.rest.api.service.MembershipService)7 Role (io.gravitee.repository.management.model.Role)6 MembershipPayload (io.gravitee.cockpit.api.command.membership.MembershipPayload)5 MembershipReply (io.gravitee.cockpit.api.command.membership.MembershipReply)5 NewRoleEntity (io.gravitee.rest.api.model.NewRoleEntity)5 UpdateRoleEntity (io.gravitee.rest.api.model.UpdateRoleEntity)5 Response (javax.ws.rs.core.Response)5 MembershipCommand (io.gravitee.cockpit.api.command.membership.MembershipCommand)4 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 MembershipReferenceType (io.gravitee.rest.api.model.MembershipReferenceType)4 Instant (java.time.Instant)4 List (java.util.List)4 JWT (com.auth0.jwt.JWT)3 Algorithm (com.auth0.jwt.algorithms.Algorithm)3 Maps (io.gravitee.common.util.Maps)3 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)3