Search in sources :

Example 11 with UserNotFoundException

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

the class OAuth2AuthenticationResourceTest method shouldConnectNewUserWithNoMatchingGroupsMappingFromUserInfo.

@Test
public void shouldConnectNewUserWithNoMatchingGroupsMappingFromUserInfo() throws Exception {
    // -- MOCK
    // mock environment
    mockDefaultEnvironment();
    mockGroupsMapping();
    // mock oauth2 exchange authorisation code for access token
    mockExchangeAuthorizationCodeForAccessToken();
    // mock oauth2 user info call
    mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body_no_matching.json"), Charset.defaultCharset())));
    // mock DB find user by name
    when(userService.findByUsername("janedoe@example.com", false)).thenThrow(new UserNotFoundException("janedoe@example.com"));
    // mock create user
    NewExternalUserEntity newExternalUserEntity = mockNewExternalUserEntity();
    UserEntity createdUser = mockUserEntity();
    mockUserCreation(newExternalUserEntity, createdUser, true);
    // mock DB update user picture
    UpdateUserEntity updateUserEntity = mockUpdateUserPicture(createdUser);
    // mock DB user connect
    when(userService.connect("janedoe@example.com")).thenReturn(createdUser);
    // -- CALL
    AbstractAuthenticationResource.Payload payload = createPayload("the_client_id", "http://localhost/callback", "CoDe", "StAtE");
    ;
    Response response = target().request().post(json(payload));
    // -- VERIFY
    verify(userService, times(1)).findByUsername("janedoe@example.com", false);
    verify(userService, times(1)).create(refEq(newExternalUserEntity), eq(true));
    verify(userService, times(1)).update(refEq(updateUserEntity));
    verify(userService, times(1)).connect("janedoe@example.com");
    // verify group creations
    verify(membershipService, times(0)).addOrUpdateMember(any(MembershipService.MembershipReference.class), any(MembershipService.MembershipUser.class), any(MembershipService.MembershipRole.class));
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    // verify response body
    verifyUserInResponseBody(response);
    // verify jwt token
    verifyJwtToken(response);
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) Response(javax.ws.rs.core.Response) AbstractResourceTest(io.gravitee.management.rest.resource.AbstractResourceTest) Test(org.junit.Test)

Example 12 with UserNotFoundException

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

the class OAuth2AuthenticationResourceTest method shouldNotConnectNewUserWhenWrongELGroupsMapping.

@Test
public void shouldNotConnectNewUserWhenWrongELGroupsMapping() throws Exception {
    // -- MOCK
    // mock environment
    mockDefaultEnvironment();
    mockWrongELGroupsMapping();
    // mock oauth2 exchange authorisation code for access token
    mockExchangeAuthorizationCodeForAccessToken();
    // mock oauth2 user info call
    mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
    // mock DB find user by name
    when(userService.findByUsername("janedoe@example.com", false)).thenThrow(new UserNotFoundException("janedoe@example.com"));
    NewExternalUserEntity newExternalUserEntity = mockNewExternalUserEntity();
    UserEntity createdUser = mockUserEntity();
    mockUserCreation(newExternalUserEntity, createdUser, true);
    // -- CALL
    AbstractAuthenticationResource.Payload payload = createPayload("the_client_id", "http://localhost/callback", "CoDe", "StAtE");
    ;
    Response response = target().request().post(json(payload));
    // -- VERIFY
    verify(userService, times(1)).findByUsername("janedoe@example.com", false);
    verify(userService, times(0)).create(any(NewExternalUserEntity.class), anyBoolean());
    verify(userService, times(0)).update(any(UpdateUserEntity.class));
    verify(userService, times(0)).connect(anyString());
    // verify group creations
    verify(membershipService, times(0)).addOrUpdateMember(any(MembershipService.MembershipReference.class), any(MembershipService.MembershipUser.class), any(MembershipService.MembershipRole.class));
    assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR_500, response.getStatus());
    // verify jwt token
    verifyJwtTokenIsNotPresent(response);
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) Response(javax.ws.rs.core.Response) AbstractResourceTest(io.gravitee.management.rest.resource.AbstractResourceTest) Test(org.junit.Test)

Example 13 with UserNotFoundException

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

the class OAuth2AuthenticationResourceTest method shouldConnectNewUser.

@Test
public void shouldConnectNewUser() throws Exception {
    // -- MOCK
    // mock environment
    mockDefaultEnvironment();
    // mock oauth2 exchange authorisation code for access token
    mockExchangeAuthorizationCodeForAccessToken();
    // mock oauth2 user info call
    mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
    // mock DB find user by name
    when(userService.findByUsername("janedoe@example.com", false)).thenThrow(new UserNotFoundException("janedoe@example.com"));
    // mock create user
    NewExternalUserEntity newExternalUserEntity = mockNewExternalUserEntity();
    UserEntity createdUser = mockUserEntity();
    mockUserCreation(newExternalUserEntity, createdUser, true);
    // mock DB update user picture
    UpdateUserEntity user = mockUpdateUserPicture(createdUser);
    // mock DB user connect
    when(userService.connect("janedoe@example.com")).thenReturn(createdUser);
    // -- CALL
    AbstractAuthenticationResource.Payload payload = createPayload("the_client_id", "http://localhost/callback", "CoDe", "StAtE");
    ;
    Response response = target().request().post(json(payload));
    // -- VERIFY
    verify(userService, times(1)).findByUsername("janedoe@example.com", false);
    verify(userService, times(1)).create(refEq(newExternalUserEntity), eq(true));
    verify(userService, times(1)).update(refEq(user));
    verify(userService, times(1)).connect("janedoe@example.com");
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    // verify response body
    verifyUserInResponseBody(response);
    // verify jwt token
    verifyJwtToken(response);
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) Response(javax.ws.rs.core.Response) AbstractResourceTest(io.gravitee.management.rest.resource.AbstractResourceTest) Test(org.junit.Test)

Example 14 with UserNotFoundException

use of io.gravitee.management.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")
public Response getCurrentUser() {
    if (isAuthenticated()) {
        final UserDetails details = getAuthenticatedUserDetails();
        final String userId = details.getUsername();
        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);
            }
            return logout();
        }
        List<GrantedAuthority> authorities = new ArrayList<>(details.getAuthorities());
        UserDetails userDetails = new UserDetails(userEntity.getId(), details.getPassword(), authorities);
        userDetails.setId(userEntity.getId());
        userDetails.setFirstname(details.getFirstname());
        userDetails.setLastname(details.getLastname());
        userDetails.setUsername(userEntity.getUsername());
        userDetails.setEmail(details.getEmail());
        // 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()));
        return Response.ok(userDetails, MediaType.APPLICATION_JSON).build();
    } else {
        return Response.ok().build();
    }
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) UserDetailRole(io.gravitee.management.idp.api.authentication.UserDetailRole) ApiOperation(io.swagger.annotations.ApiOperation)

Example 15 with UserNotFoundException

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

the class UserServiceImpl method findByIds.

@Override
public Set<UserEntity> findByIds(List<String> ids) {
    try {
        LOGGER.debug("Find users by ID: {}", ids);
        Set<User> users = userRepository.findByIds(ids);
        if (!users.isEmpty()) {
            return users.stream().map(u -> this.convert(u, false)).collect(Collectors.toSet());
        }
        Optional<String> idsAsString = ids.stream().reduce((a, b) -> a + '/' + b);
        if (idsAsString.isPresent()) {
            throw new UserNotFoundException(idsAsString.get());
        } else {
            throw new UserNotFoundException("?");
        }
    } catch (TechnicalException ex) {
        Optional<String> idsAsString = ids.stream().reduce((a, b) -> a + '/' + b);
        LOGGER.error("An error occurs while trying to find users using their ID {}", idsAsString, ex);
        throw new TechnicalManagementException("An error occurs while trying to find users using their ID " + idsAsString, ex);
    }
}
Also used : RoleScope(io.gravitee.repository.management.model.RoleScope) java.util(java.util) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) MembershipDefaultReferenceId(io.gravitee.repository.management.model.MembershipDefaultReferenceId) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) EmailNotificationBuilder(io.gravitee.management.service.builder.EmailNotificationBuilder) StringUtils(org.apache.commons.lang3.StringUtils) Value(org.springframework.beans.factory.annotation.Value) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.management.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) JWTVerifier(com.auth0.jwt.JWTVerifier) UUID(io.gravitee.common.utils.UUID) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) io.gravitee.management.model(io.gravitee.management.model) UserRepository(io.gravitee.repository.management.api.UserRepository) JWTSigner(com.auth0.jwt.JWTSigner) DEFAULT_JWT_ISSUER(io.gravitee.management.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) Claims(io.gravitee.management.service.common.JWTHelper.Claims) MembershipReferenceType(io.gravitee.repository.management.model.MembershipReferenceType) UsernameAlreadyExistsException(io.gravitee.management.service.exceptions.UsernameAlreadyExistsException) Logger(org.slf4j.Logger) DefaultRoleNotFoundException(io.gravitee.management.service.exceptions.DefaultRoleNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PortalHook(io.gravitee.management.service.notification.PortalHook) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) USER(io.gravitee.repository.management.model.Audit.AuditProperties.USER) io.gravitee.management.service(io.gravitee.management.service) User(io.gravitee.repository.management.model.User) io.gravitee.common.utils(io.gravitee.common.utils) DatatypeConverter(javax.xml.bind.DatatypeConverter) UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) User(io.gravitee.repository.management.model.User) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Aggregations

UserNotFoundException (io.gravitee.management.service.exceptions.UserNotFoundException)17 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)6 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)6 User (io.gravitee.repository.management.model.User)6 UserDetails (io.gravitee.management.idp.api.authentication.UserDetails)5 AbstractResourceTest (io.gravitee.management.rest.resource.AbstractResourceTest)5 Response (javax.ws.rs.core.Response)5 Test (org.junit.Test)5 UserEntity (io.gravitee.management.model.UserEntity)4 NewExternalUserEntity (io.gravitee.management.model.NewExternalUserEntity)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 UpdateUserEntity (io.gravitee.management.model.UpdateUserEntity)2 JWTSigner (com.auth0.jwt.JWTSigner)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 io.gravitee.common.utils (io.gravitee.common.utils)1 UUID (io.gravitee.common.utils.UUID)1 UserDetailRole (io.gravitee.management.idp.api.authentication.UserDetailRole)1 io.gravitee.management.model (io.gravitee.management.model)1 EventEntity (io.gravitee.management.model.EventEntity)1 NewEventEntity (io.gravitee.management.model.NewEventEntity)1