Search in sources :

Example 11 with RoleEntity

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

the class RoleService_CreateTest method shouldCreate.

@Test
public void shouldCreate() throws TechnicalException {
    NewRoleEntity newRoleEntityMock = mock(NewRoleEntity.class);
    when(newRoleEntityMock.getName()).thenReturn("new mock role");
    when(newRoleEntityMock.getScope()).thenReturn(io.gravitee.rest.api.model.permissions.RoleScope.ENVIRONMENT);
    when(newRoleEntityMock.getPermissions()).thenReturn(Collections.singletonMap(DOCUMENTATION.getName(), new char[] { RolePermissionAction.CREATE.getId() }));
    Role roleMock = mock(Role.class);
    when(roleMock.getId()).thenReturn("new_mock_role");
    when(roleMock.getName()).thenReturn("new mock role");
    when(roleMock.getScope()).thenReturn(RoleScope.ENVIRONMENT);
    when(roleMock.getPermissions()).thenReturn(new int[] { 3008 });
    when(mockRoleRepository.create(any())).thenReturn(roleMock);
    RoleEntity entity = roleService.create(newRoleEntityMock);
    assertNotNull("no entoty created", entity);
    assertEquals("invalid id", "new_mock_role", entity.getId());
    assertEquals("invalid name", "new mock role", entity.getName());
    assertEquals("invalid scope", io.gravitee.rest.api.model.permissions.RoleScope.ENVIRONMENT, entity.getScope());
    assertFalse("no permissions found", entity.getPermissions().isEmpty());
    assertTrue("invalid Permission name", entity.getPermissions().containsKey(DOCUMENTATION.getName()));
    char[] perms = entity.getPermissions().get(DOCUMENTATION.getName());
    assertEquals("not enough permissions", 1, perms.length);
    assertEquals("not the good permission", RolePermissionAction.CREATE.getId(), perms[0]);
}
Also used : Role(io.gravitee.repository.management.model.Role) RoleEntity(io.gravitee.rest.api.model.RoleEntity) NewRoleEntity(io.gravitee.rest.api.model.NewRoleEntity) NewRoleEntity(io.gravitee.rest.api.model.NewRoleEntity) Test(org.junit.Test)

Example 12 with RoleEntity

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

the class AuthResource method login.

@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
        // JWT signer
        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()));
        }
        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(userDetails.getUsername()).withClaim(Claims.PERMISSIONS, authorities).withClaim(Claims.EMAIL, userDetails.getEmail()).withClaim(Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
        final Token tokenEntity = new Token();
        tokenEntity.setTokenType(TokenTypeEnum.BEARER);
        tokenEntity.setToken(sign);
        final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
        servletResponse.addCookie(bearerCookie);
        return ok(tokenEntity).build();
    }
    return ok().build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) 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) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) Duration(java.time.Duration) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth2AuthenticationResource(io.gravitee.rest.api.portal.rest.resource.auth.OAuth2AuthenticationResource) 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) MediaType(io.gravitee.common.http.MediaType) Response(javax.ws.rs.core.Response) ResourceContext(javax.ws.rs.container.ResourceContext) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 13 with RoleEntity

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

the class RoleServiceImpl method convert.

private RoleEntity convert(final Role role) {
    if (role == null) {
        return null;
    }
    final RoleEntity roleEntity = new RoleEntity();
    roleEntity.setId(role.getId());
    roleEntity.setName(role.getName());
    roleEntity.setDescription(role.getDescription());
    roleEntity.setScope(convert(role.getScope()));
    roleEntity.setDefaultRole(role.isDefaultRole());
    roleEntity.setSystem(role.isSystem());
    roleEntity.setPermissions(convertPermissions(roleEntity.getScope(), role.getPermissions()));
    return roleEntity;
}
Also used : UpdateRoleEntity(io.gravitee.rest.api.model.UpdateRoleEntity) NewRoleEntity(io.gravitee.rest.api.model.NewRoleEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity)

Example 14 with RoleEntity

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

the class ConfigurationResourceTest method shouldGetApplicationRoles.

@Test
public void shouldGetApplicationRoles() throws TechnicalException {
    resetAllMocks();
    RoleEntity appRoleEntity = new RoleEntity();
    appRoleEntity.setDefaultRole(true);
    appRoleEntity.setName("appRole");
    appRoleEntity.setSystem(false);
    when(roleService.findByScope(RoleScope.APPLICATION)).thenReturn(Collections.singletonList(appRoleEntity));
    final Response response = target().path("applications").path("roles").request().get();
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    final ConfigurationApplicationRolesResponse appRoles = response.readEntity(ConfigurationApplicationRolesResponse.class);
    assertNotNull(appRoles);
    @Valid List<ApplicationRole> roles = appRoles.getData();
    assertNotNull(roles);
    assertEquals(1, roles.size());
    assertEquals("appRole", roles.get(0).getId());
    assertEquals(true, roles.get(0).getDefault());
    assertEquals("appRole", roles.get(0).getName());
    assertEquals(false, roles.get(0).getSystem());
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) Response(javax.ws.rs.core.Response) Valid(javax.validation.Valid) Test(org.junit.Test)

Example 15 with RoleEntity

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

the class MembershipService_FindUserMembershipTest method shouldGetApiWithApiAndGroups.

@Test
public void shouldGetApiWithApiAndGroups() throws Exception {
    RoleEntity roleEntity = new RoleEntity();
    roleEntity.setId("role");
    roleEntity.setName("PO");
    roleEntity.setScope(RoleScope.API);
    when(mockRoleService.findByScope(any())).thenReturn(Collections.singletonList(roleEntity));
    Membership mApi = mock(Membership.class);
    when(mApi.getReferenceId()).thenReturn("api-id1");
    when(mApi.getRoleId()).thenReturn("role");
    Membership mGroup = mock(Membership.class);
    when(mGroup.getReferenceId()).thenReturn("api-id2");
    when(mApi.getRoleId()).thenReturn("role");
    when(mockMembershipRepository.findByMemberIdAndMemberTypeAndReferenceType(eq(USER_ID), eq(MembershipMemberType.USER), eq(MembershipReferenceType.API))).thenReturn(Collections.singleton(mApi));
    when(mockMembershipRepository.findByMemberIdAndMemberTypeAndReferenceType(eq("GROUP"), eq(MembershipMemberType.GROUP), eq(MembershipReferenceType.API))).thenReturn(Collections.singleton(mGroup));
    GroupEntity group1 = mock(GroupEntity.class);
    doReturn("GROUP").when(group1).getId();
    doReturn(new HashSet<>(asList(group1))).when(mockGroupService).findByUser(USER_ID);
    List<UserMembership> references = membershipService.findUserMembership(io.gravitee.rest.api.model.MembershipReferenceType.API, USER_ID);
    assertFalse(references.isEmpty());
    assertEquals(2, references.size());
    assertNotEquals(references.get(0).getReference(), references.get(1).getReference());
    assertTrue(references.get(0).getReference().equals("api-id1") || references.get(0).getReference().equals("api-id2"));
    assertTrue(references.get(1).getReference().equals("api-id1") || references.get(1).getReference().equals("api-id2"));
    assertEquals("API", references.get(0).getType());
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) GroupEntity(io.gravitee.rest.api.model.GroupEntity) Membership(io.gravitee.repository.management.model.Membership) UserMembership(io.gravitee.rest.api.model.UserMembership) UserMembership(io.gravitee.rest.api.model.UserMembership) 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