use of io.gravitee.rest.api.idp.api.authentication.UserDetailRole in project gravitee-management-rest-api by gravitee-io.
the class CurrentUserResource method getCurrentUser.
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get the authenticated user")
@ApiResponses({ @ApiResponse(code = 200, message = "Authenticated user", response = UserDetails.class), @ApiResponse(code = 401, message = "Unauthorized user"), @ApiResponse(code = 500, message = "Internal server error") })
public Response getCurrentUser() {
if (isAuthenticated()) {
final UserDetails details = getAuthenticatedUserDetails();
final String userId = details.getUsername();
final String password = details.getPassword() != null ? details.getPassword() : "";
UserEntity userEntity;
try {
userEntity = userService.findByIdWithRoles(userId);
} catch (final UserNotFoundException unfe) {
final String unfeMessage = "User '{}' does not exist.";
if (LOG.isDebugEnabled()) {
LOG.info(unfeMessage, userId, unfe);
} else {
LOG.info(unfeMessage, userId);
}
response.addCookie(cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, null));
return status(Response.Status.UNAUTHORIZED).build();
}
List<GrantedAuthority> authorities = new ArrayList<>(details.getAuthorities());
UserDetails userDetails = new UserDetails(userEntity.getId(), password, authorities);
userDetails.setId(userEntity.getId());
// in case of memory user, look at the repository layer to get value updated by the user through the MyAccount page
userDetails.setFirstname(IDP_SOURCE_MEMORY.equals(userEntity.getSource()) && userEntity.getFirstname() != null ? userEntity.getFirstname() : details.getFirstname());
userDetails.setLastname(IDP_SOURCE_MEMORY.equals(userEntity.getSource()) && userEntity.getLastname() != null ? userEntity.getLastname() : details.getLastname());
userDetails.setSource(userEntity.getSource());
userDetails.setSourceId(userEntity.getSourceId());
userDetails.setPrimaryOwner(userEntity.isPrimaryOwner());
userDetails.setCreatedAt(userEntity.getCreatedAt());
userDetails.setUpdatedAt(userEntity.getUpdatedAt());
userDetails.setLastConnectionAt(userEntity.getLastConnectionAt());
if (details.getEmail() == null && IDP_SOURCE_MEMORY.equals(userEntity.getSource()) && userEntity.getEmail() != null) {
userDetails.setEmail(userEntity.getEmail());
} else {
userDetails.setEmail(details.getEmail());
}
boolean newsletterEnabled = environment.getProperty("newsletter.enabled", boolean.class, true);
if (newsletterEnabled && userEntity.getNewsletterSubscribed() == null && userEntity.getFirstConnectionAt() != null) {
long diffInMs = Math.abs(new Date().getTime() - userEntity.getFirstConnectionAt().getTime());
long diff = TimeUnit.DAYS.convert(diffInMs, TimeUnit.MILLISECONDS);
userDetails.setDisplayNewsletterSubscription(diff >= 7);
} else {
userDetails.setDisplayNewsletterSubscription(false);
}
// convert UserEntityRoles to UserDetailsRoles
userDetails.setRoles(userEntity.getRoles().stream().map(userEntityRole -> {
UserDetailRole userDetailRole = new UserDetailRole();
userDetailRole.setScope(userEntityRole.getScope().name());
userDetailRole.setName(userEntityRole.getName());
userDetailRole.setPermissions(userEntityRole.getPermissions());
return userDetailRole;
}).collect(Collectors.toList()));
final Set<MembershipEntity> memberships = membershipService.getMembershipsByMemberAndReference(MembershipMemberType.USER, userId, MembershipReferenceType.GROUP);
if (!memberships.isEmpty()) {
final Map<String, Set<String>> userGroups = new HashMap<>();
environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()).forEach(environment -> {
try {
final Set<Group> groups = groupRepository.findAllByEnvironment(environment.getId());
userGroups.put(environment.getId(), new HashSet<>());
memberships.stream().map(MembershipEntity::getReferenceId).forEach(groupId -> {
final Optional<Group> optionalGroup = groups.stream().filter(group -> groupId.equals(group.getId())).findFirst();
optionalGroup.ifPresent(entity -> userGroups.get(environment.getId()).add(entity.getName()));
});
userDetails.setGroupsByEnvironment(userGroups);
} catch (TechnicalException e) {
LOG.error("Error while trying to get groups of the user " + userId, e);
}
});
}
userDetails.setFirstLogin(1 == userEntity.getLoginCount());
if (userEntity.getCustomFields() != null) {
userDetails.setCustomFields(userEntity.getCustomFields());
}
return ok(userDetails, MediaType.APPLICATION_JSON).build();
} else {
return ok().build();
}
}
Aggregations