Search in sources :

Example 11 with UserNotFoundException

use of io.gravitee.rest.api.service.exceptions.UserNotFoundException in project gravitee-management-rest-api by gravitee-io.

the class TokenAuthenticationFilterTest method shouldRejectRequest_UnknownUser.

@Test
public void shouldRejectRequest_UnknownUser() throws Exception {
    final String USER_ID = "SomeId";
    final String TOKEN = "b4c6102e-6c95-464f-8610-2e6c95064f02";
    final String BEARER = "Bearer " + TOKEN;
    TokenAuthenticationFilter filter = new TokenAuthenticationFilter("JWT_SECRET_TOEKN_TEST", cookieGenerator, userService, tokenService, authoritiesProvider);
    when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(BEARER);
    final Token token = mock(Token.class);
    when(token.getReferenceId()).thenReturn(USER_ID);
    when(tokenService.findByToken(TOKEN)).thenReturn(token);
    when(userService.findById(USER_ID)).thenThrow(new UserNotFoundException(USER_ID));
    filter.doFilter(request, response, filterChain);
    verify(response).sendError(HttpStatusCode.UNAUTHORIZED_401);
    verify(authoritiesProvider, never()).retrieveAuthorities(USER_ID);
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) Token(io.gravitee.repository.management.model.Token) Test(org.junit.Test)

Example 12 with UserNotFoundException

use of io.gravitee.rest.api.service.exceptions.UserNotFoundException in project gravitee-management-rest-api by gravitee-io.

the class UserResource method getCurrentUser.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getCurrentUser() {
    final String authenticatedUser = getAuthenticatedUser();
    try {
        UserEntity userEntity = userService.findByIdWithRoles(authenticatedUser);
        User currentUser = userMapper.convert(userEntity);
        boolean withManagement = (authenticatedUser != null && permissionService.hasManagementRights(authenticatedUser));
        if (withManagement) {
            Management managementConfig = this.configService.getConsoleSettings().getManagement();
            if (managementConfig != null && managementConfig.getUrl() != null) {
                UserConfig userConfig = new UserConfig();
                userConfig.setManagementUrl(managementConfig.getUrl());
                currentUser.setConfig(userConfig);
            }
        }
        currentUser.setLinks(userMapper.computeUserLinks(userURL(uriInfo.getBaseUriBuilder()), userEntity.getUpdatedAt()));
        return Response.ok(currentUser).build();
    } catch (final UserNotFoundException unfe) {
        response.addCookie(cookieGenerator.generate(null));
        return status(Response.Status.UNAUTHORIZED).build();
    }
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) User(io.gravitee.rest.api.portal.rest.model.User) Management(io.gravitee.rest.api.model.settings.Management) UserConfig(io.gravitee.rest.api.portal.rest.model.UserConfig)

Example 13 with UserNotFoundException

use of io.gravitee.rest.api.service.exceptions.UserNotFoundException 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();
    }
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) PagedResult(io.gravitee.rest.api.management.rest.model.PagedResult) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) Duration(java.time.Duration) Response.status(javax.ws.rs.core.Response.status) AbstractResource(io.gravitee.rest.api.management.rest.resource.AbstractResource) URI(java.net.URI) UserDetailRole(io.gravitee.rest.api.idp.api.authentication.UserDetailRole) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Context(javax.ws.rs.core.Context) GroupRepository(io.gravitee.repository.management.api.GroupRepository) Instant(java.time.Instant) NotNull(javax.validation.constraints.NotNull) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) GrantedAuthority(org.springframework.security.core.GrantedAuthority) MediaType(io.gravitee.common.http.MediaType) InvalidImageException(io.gravitee.rest.api.exception.InvalidImageException) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Request(javax.ws.rs.core.Request) Authentication(org.springframework.security.core.Authentication) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) ApiResponses(io.swagger.annotations.ApiResponses) Inject(javax.inject.Inject) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) io.gravitee.rest.api.model(io.gravitee.rest.api.model) TokensResource(io.gravitee.rest.api.management.rest.resource.TokensResource) Api(io.swagger.annotations.Api) Cookie(javax.servlet.http.Cookie) Logger(org.slf4j.Logger) ImageUtils(io.gravitee.rest.api.security.utils.ImageUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) Group(io.gravitee.repository.management.model.Group) EntityTag(javax.ws.rs.core.EntityTag) Maps(io.gravitee.common.util.Maps) TimeUnit(java.util.concurrent.TimeUnit) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) ApiResponse(io.swagger.annotations.ApiResponse) ResourceContext(javax.ws.rs.container.ResourceContext) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) Group(io.gravitee.repository.management.model.Group) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserDetailRole(io.gravitee.rest.api.idp.api.authentication.UserDetailRole) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 14 with UserNotFoundException

use of io.gravitee.rest.api.service.exceptions.UserNotFoundException in project gravitee-management-rest-api by gravitee-io.

the class MembershipCommandHandlerTest method handleWithUnknownUser.

@Test
public void handleWithUnknownUser() {
    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);
    when(userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false)).thenThrow(new UserNotFoundException(membershipPayload.getUserId()));
    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(roleService);
    verifyZeroInteractions(membershipService);
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) MembershipReply(io.gravitee.cockpit.api.command.membership.MembershipReply) MembershipPayload(io.gravitee.cockpit.api.command.membership.MembershipPayload) MembershipCommand(io.gravitee.cockpit.api.command.membership.MembershipCommand) Test(org.junit.Test)

Example 15 with UserNotFoundException

use of io.gravitee.rest.api.service.exceptions.UserNotFoundException in project gravitee-management-rest-api by gravitee-io.

the class UserCommandHandlerTest method handleCreation.

@Test
public void handleCreation() {
    UserPayload userPayload = new UserPayload();
    UserCommand command = new UserCommand(userPayload);
    final String sourceId = "user#1";
    userPayload.setId(sourceId);
    userPayload.setOrganizationId("orga#1");
    userPayload.setUsername("Username");
    userPayload.setFirstName("Firstname");
    userPayload.setLastName("Lastname");
    userPayload.setPicture("https://gravitee.io/my-picture");
    userPayload.setEmail("email@gravitee.io");
    HashMap<String, Object> additionalInformation = new HashMap<>();
    additionalInformation.put("info1", "value1");
    additionalInformation.put("info2", "value2");
    userPayload.setAdditionalInformation(additionalInformation);
    when(userService.findBySource("cockpit", sourceId, false)).thenThrow(new UserNotFoundException(sourceId));
    when(userService.create(argThat(newUser -> newUser.getSourceId().equals(userPayload.getId()) && newUser.getSource().equals("cockpit") && newUser.getFirstname().equals(userPayload.getFirstName()) && newUser.getLastname().equals(userPayload.getLastName()) && newUser.getEmail().equals(userPayload.getEmail()) && newUser.getPicture().equals(userPayload.getPicture()) && newUser.getCustomFields().get("info1").equals(additionalInformation.get("info1")) && newUser.getCustomFields().get("info2").equals(additionalInformation.get("info2")) && newUser.getCustomFields().get(PICTURE).equals(userPayload.getPicture()) && newUser.getCustomFields().get(SUB).equals(userPayload.getUsername())), eq(false))).thenReturn(new UserEntity());
    TestObserver<UserReply> obs = cut.handle(command).test();
    obs.awaitTerminalEvent();
    obs.assertValue(reply -> reply.getCommandId().equals(command.getId()) && reply.getCommandStatus().equals(CommandStatus.SUCCEEDED));
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) ArgumentMatchers(org.mockito.ArgumentMatchers) PICTURE(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity.UserProfile.PICTURE) SUB(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity.UserProfile.SUB) Mock(org.mockito.Mock) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) RunWith(org.junit.runner.RunWith) TestObserver(io.reactivex.observers.TestObserver) HashMap(java.util.HashMap) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Command(io.gravitee.cockpit.api.command.Command) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) UserReply(io.gravitee.cockpit.api.command.user.UserReply) UserService(io.gravitee.rest.api.service.UserService) NewExternalUserEntity(io.gravitee.rest.api.model.NewExternalUserEntity) CommandStatus(io.gravitee.cockpit.api.command.CommandStatus) UserCommand(io.gravitee.cockpit.api.command.user.UserCommand) UserPayload(io.gravitee.cockpit.api.command.user.UserPayload) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Assert.assertEquals(org.junit.Assert.assertEquals) UserEntity(io.gravitee.rest.api.model.UserEntity) Before(org.junit.Before) UserCommand(io.gravitee.cockpit.api.command.user.UserCommand) UserPayload(io.gravitee.cockpit.api.command.user.UserPayload) HashMap(java.util.HashMap) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) NewExternalUserEntity(io.gravitee.rest.api.model.NewExternalUserEntity) UserEntity(io.gravitee.rest.api.model.UserEntity) UserReply(io.gravitee.cockpit.api.command.user.UserReply) Test(org.junit.Test)

Aggregations

UserNotFoundException (io.gravitee.rest.api.service.exceptions.UserNotFoundException)15 Test (org.junit.Test)8 Response (javax.ws.rs.core.Response)5 UserCommand (io.gravitee.cockpit.api.command.user.UserCommand)3 UserPayload (io.gravitee.cockpit.api.command.user.UserPayload)3 UserReply (io.gravitee.cockpit.api.command.user.UserReply)3 AbstractResourceTest (io.gravitee.rest.api.management.rest.resource.AbstractResourceTest)3 NewExternalUserEntity (io.gravitee.rest.api.model.NewExternalUserEntity)3 UserEntity (io.gravitee.rest.api.model.UserEntity)3 UuidString (io.gravitee.rest.api.service.common.UuidString)3 Command (io.gravitee.cockpit.api.command.Command)2 CommandStatus (io.gravitee.cockpit.api.command.CommandStatus)2 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)2 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)2 io.gravitee.rest.api.model (io.gravitee.rest.api.model)2 UpdateUserEntity (io.gravitee.rest.api.model.UpdateUserEntity)2 PICTURE (io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity.UserProfile.PICTURE)2 SUB (io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity.UserProfile.SUB)2 TechnicalManagementException (io.gravitee.rest.api.service.exceptions.TechnicalManagementException)2 Logger (org.slf4j.Logger)2