use of io.gravitee.rest.api.model.UserEntity 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();
}
use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.
the class UserMapperTest method testConvertUserEntityWithPermissions.
@Test
public void testConvertUserEntityWithPermissions() throws Exception {
Instant now = Instant.now();
Date nowDate = Date.from(now);
// init
UserEntity userEntity = new UserEntity();
UserRoleEntity userRoleEntityOrganization = new UserRoleEntity();
userRoleEntityOrganization.setId("org-id");
userRoleEntityOrganization.setScope(RoleScope.ORGANIZATION);
HashMap<String, char[]> organizationPermissions = new HashMap<>();
organizationPermissions.put("USER", new char[] { 'C', 'R', 'U', 'D' });
organizationPermissions.put("ENVIRONMENT", new char[] { 'C', 'R', 'U', 'D' });
userRoleEntityOrganization.setPermissions(organizationPermissions);
UserRoleEntity userRoleEntityEnvironment = new UserRoleEntity();
userRoleEntityEnvironment.setScope(RoleScope.ENVIRONMENT);
userRoleEntityEnvironment.setId("env-id");
HashMap<String, char[]> environmentPermissions = new HashMap<>();
environmentPermissions.put("APPLICATION", new char[] { 'C' });
userRoleEntityEnvironment.setPermissions(environmentPermissions);
userEntity.setCreatedAt(nowDate);
userEntity.setEmail(USER_EMAIL);
userEntity.setFirstname(USER_FIRSTNAME);
userEntity.setId(USER_ID);
userEntity.setLastConnectionAt(nowDate);
userEntity.setLastname(USER_LASTNAME);
userEntity.setPassword(USER_PASSWORD);
userEntity.setPicture(USER_PICTURE);
userEntity.setRoles(new HashSet<>(Arrays.asList(userRoleEntityOrganization, userRoleEntityEnvironment)));
userEntity.setSource(USER_SOURCE);
userEntity.setSourceId(USER_SOURCE_ID);
userEntity.setStatus(USER_STATUS);
userEntity.setUpdatedAt(nowDate);
// Test
User responseUser = userMapper.convert(userEntity);
assertNotNull(responseUser);
assertEquals(USER_ID, responseUser.getId());
assertEquals(USER_EMAIL, responseUser.getEmail());
assertEquals(USER_FIRSTNAME, responseUser.getFirstName());
assertEquals(USER_LASTNAME, responseUser.getLastName());
assertEquals(USER_FIRSTNAME + ' ' + USER_LASTNAME, responseUser.getDisplayName());
assertTrue(responseUser.getPermissions().getAPPLICATION().containsAll(Arrays.asList("C")));
}
use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.
the class CockpitAuthenticationResource method tokenExchange.
@GET
public Response tokenExchange(@QueryParam(value = "token") final String token, @Context final HttpServletResponse httpResponse) {
if (!enabled) {
return Response.status(Response.Status.NOT_FOUND).build();
}
try {
// Verify and get claims from token.
final JWTClaimsSet jwtClaimsSet = jwtProcessor.process(token, null);
// Current organization must be set to those coming from cockpit token.
final String organizationId = jwtClaimsSet.getStringClaim(ORG_CLAIM);
GraviteeContext.setCurrentOrganization(organizationId);
// Retrieve the user.
final UserEntity user = userService.findBySource(COCKPIT_SOURCE, jwtClaimsSet.getSubject(), true);
// set user to Authentication Context
final String environmentId = jwtClaimsSet.getStringClaim(ENVIRONMENT_CLAIM);
final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId(), organizationId, environmentId);
UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
userDetails.setEmail(user.getEmail());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
// Cockpit user is authenticated, connect user (ie: generate cookie).
super.connectUser(user, httpResponse);
// Redirect the user.
return Response.temporaryRedirect(new URI(jwtClaimsSet.getStringClaim(REDIRECT_URI_CLAIM) + "?organization=" + jwtClaimsSet.getStringClaim(ORG_CLAIM) + "/#!/environments/" + jwtClaimsSet.getStringClaim(ENVIRONMENT_CLAIM))).build();
} catch (Exception e) {
LOGGER.error("Error occurred when trying to log user using cockpit.", e);
return Response.serverError().build();
} finally {
GraviteeContext.cleanContext();
}
}
use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.
the class UserResourceTest method shouldGetCurrentUserWithoutConfig.
@Test
public void shouldGetCurrentUserWithoutConfig() {
when(userService.findByIdWithRoles(USER_NAME)).thenReturn(new UserEntity());
when(permissionService.hasManagementRights(USER_NAME)).thenReturn(Boolean.FALSE);
final Response response = target().request().get();
assertEquals(HttpStatusCode.OK_200, response.getStatus());
ArgumentCaptor<String> userId = ArgumentCaptor.forClass(String.class);
Mockito.verify(userService).findByIdWithRoles(userId.capture());
assertEquals(USER_NAME, userId.getValue());
User user = response.readEntity(User.class);
assertNotNull(user);
assertNull(user.getConfig());
assertNotNull(user.getLinks());
}
use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.
the class UserResourceTest method shouldGetNoContent.
@Test
public void shouldGetNoContent() throws IOException {
doReturn(new UserEntity()).when(userService).findById(any());
doReturn(null).when(userService).getPicture(any());
final Response response = target().path("avatar").request().get();
assertEquals(OK_200, response.getStatus());
}
Aggregations