Search in sources :

Example 1 with UserNotFoundException

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

the class OAuth2AuthenticationResourceTest method shouldNotConnectNewUserWithGroupsMappingFromUserInfoWhenGroupIsNotFound.

@Test
public void shouldNotConnectNewUserWithGroupsMappingFromUserInfoWhenGroupIsNotFound() 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.json"), Charset.defaultCharset())));
    // mock DB find user by name
    when(userService.findByUsername("janedoe@example.com", false)).thenThrow(new UserNotFoundException("janedoe@example.com"));
    // mock group search and association
    when(groupService.findByName("Example group")).thenReturn(Collections.emptyList());
    when(groupService.findByName("soft user")).thenReturn(Collections.emptyList());
    when(groupService.findByName("Others")).thenReturn(Collections.emptyList());
    when(groupService.findByName("Api consumer")).thenReturn(Collections.emptyList());
    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 2 with UserNotFoundException

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

the class AuthenticationSuccessListener method onApplicationEvent.

@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    final UserDetails details = (UserDetails) event.getAuthentication().getPrincipal();
    try {
        UserEntity registeredUser = userService.findByUsername(details.getUsername(), false);
        // Principal username is the technical identifier of the user
        details.setUsername(registeredUser.getId());
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setUsername(details.getUsername());
        newUser.setSource(details.getSource());
        newUser.setSourceId(details.getSourceId());
        newUser.setFirstname(details.getFirstname());
        newUser.setLastname(details.getLastname());
        newUser.setEmail(details.getEmail());
        boolean addDefaultRole = false;
        if (event.getAuthentication().getAuthorities() == null || event.getAuthentication().getAuthorities().isEmpty()) {
            addDefaultRole = true;
        }
        UserEntity createdUser = userService.create(newUser, addDefaultRole);
        // Principal username is the technical identifier of the user
        details.setUsername(createdUser.getId());
        if (!addDefaultRole) {
            addRole(RoleScope.MANAGEMENT, createdUser.getId(), event.getAuthentication().getAuthorities());
            addRole(RoleScope.PORTAL, createdUser.getId(), event.getAuthentication().getAuthorities());
        }
    }
    userService.connect(details.getUsername());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UserEntity(io.gravitee.management.model.UserEntity)

Example 3 with UserNotFoundException

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

the class GoogleAuthenticationResource method processUser.

private Response processUser(final Map<String, Object> userInfo) {
    String username = (String) userInfo.get("email");
    // set user to Authentication Context
    UserDetails userDetails = new UserDetails(username, "", Collections.emptyList());
    userDetails.setEmail(username);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));
    try {
        UserEntity registeredUser = userService.findByUsername(username, false);
        userDetails.setUsername(registeredUser.getId());
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setUsername(username);
        newUser.setSource(AuthenticationSource.GOOGLE.getName());
        newUser.setSourceId(userInfo.get("sub").toString());
        newUser.setFirstname(userInfo.get("given_name").toString());
        newUser.setLastname(userInfo.get("family_name").toString());
        newUser.setEmail(username);
        UserEntity createdUser = userService.create(newUser, true);
        userDetails.setUsername(createdUser.getId());
    }
    // User refresh
    UpdateUserEntity user = new UpdateUserEntity();
    user.setUsername(username);
    user.setPicture(userInfo.get("picture").toString());
    userService.update(user);
    return connectUser(userDetails.getUsername());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.management.model.UpdateUserEntity) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserEntity(io.gravitee.management.model.UserEntity) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.management.model.UpdateUserEntity)

Example 4 with UserNotFoundException

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

the class EventServiceImpl method convert.

private EventEntity convert(Event event) {
    EventEntity eventEntity = new EventEntity();
    eventEntity.setId(event.getId());
    eventEntity.setType(io.gravitee.management.model.EventType.valueOf(event.getType().toString()));
    eventEntity.setPayload(event.getPayload());
    eventEntity.setParentId(event.getParentId());
    eventEntity.setProperties(event.getProperties());
    eventEntity.setCreatedAt(event.getCreatedAt());
    eventEntity.setUpdatedAt(event.getUpdatedAt());
    if (event.getProperties() != null) {
        final String userId = event.getProperties().get(Event.EventProperties.USER.getValue());
        if (userId != null && !userId.isEmpty()) {
            try {
                eventEntity.setUser(userService.findById(userId));
            } catch (UserNotFoundException unfe) {
                UserEntity user = new UserEntity();
                user.setSource("system");
                user.setId(userId);
                user.setUsername("system");
                eventEntity.setUser(user);
            }
        }
    }
    return eventEntity;
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) EventEntity(io.gravitee.management.model.EventEntity) NewEventEntity(io.gravitee.management.model.NewEventEntity) UserEntity(io.gravitee.management.model.UserEntity)

Example 5 with UserNotFoundException

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

the class UserServiceImpl method findByUsername.

@Override
public UserEntity findByUsername(String username, boolean loadRoles) {
    try {
        LOGGER.debug("Find user by name: {}", username);
        Optional<User> optionalUser = userRepository.findByUsername(username);
        if (optionalUser.isPresent()) {
            return convert(optionalUser.get(), loadRoles);
        }
        // should never happen
        throw new UserNotFoundException(username);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find user using its username {}", username, ex);
        throw new TechnicalManagementException("An error occurs while trying to find user using its username " + username, ex);
    }
}
Also used : 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