Search in sources :

Example 1 with UserNotFoundException

use of io.gravitee.rest.api.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.findBySource(details.getSource(), details.getSourceId(), false);
        updateRegisteredUser(registeredUser, details);
        // Principal username is the technical identifier of the user
        // Dirty hack because spring security is requiring a username...
        details.setUsername(registeredUser.getId());
        // Allows to override email of in memory users
        if ("memory".equals(details.getSource()) && registeredUser.getEmail() != null) {
            details.setEmail(registeredUser.getEmail());
            SecurityContextHolder.getContext().setAuthentication(event.getAuthentication());
        }
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setSource(details.getSource());
        newUser.setSourceId(details.getSourceId());
        newUser.setFirstname(details.getFirstname());
        newUser.setLastname(details.getLastname());
        newUser.setEmail(details.getEmail());
        byte[] pictureData = details.getPicture();
        if (pictureData != null && pictureData.length > 0) {
            String picture = computePicture(pictureData);
            newUser.setPicture(picture);
        }
        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.ENVIRONMENT, createdUser.getId(), event.getAuthentication().getAuthorities());
            addRole(RoleScope.ORGANIZATION, createdUser.getId(), event.getAuthentication().getAuthorities());
        }
    }
    userService.connect(details.getUsername());
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails)

Example 2 with UserNotFoundException

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

the class UserCommandHandler method handle.

@Override
public Single<UserReply> handle(UserCommand command) {
    UserPayload userPayload = command.getPayload();
    GraviteeContext.setCurrentOrganization(userPayload.getOrganizationId());
    try {
        final UserEntity existingUser = userService.findBySource(COCKPIT_SOURCE, userPayload.getId(), false);
        UpdateUserEntity updatedUser = new UpdateUserEntity();
        updatedUser.setFirstname(userPayload.getFirstName());
        updatedUser.setLastname(userPayload.getLastName());
        updatedUser.setEmail(userPayload.getEmail());
        updatedUser.setPicture(userPayload.getPicture());
        updatedUser.setCustomFields(new HashMap<>());
        if (userPayload.getAdditionalInformation() != null) {
            updatedUser.getCustomFields().putAll(userPayload.getAdditionalInformation());
        }
        updatedUser.getCustomFields().computeIfAbsent(PICTURE, k -> userPayload.getPicture());
        updatedUser.getCustomFields().computeIfAbsent(SUB, k -> userPayload.getUsername());
        UserEntity cockpitUserEntity = userService.update(existingUser.getId(), updatedUser);
        logger.info("User [{}] with APIM id [{}] updated.", userPayload.getUsername(), cockpitUserEntity.getId());
        return Single.just(new UserReply(command.getId(), CommandStatus.SUCCEEDED));
    } catch (UserNotFoundException unfe) {
        NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setSourceId(userPayload.getId());
        newUser.setFirstname(userPayload.getFirstName());
        newUser.setLastname(userPayload.getLastName());
        newUser.setEmail(userPayload.getEmail());
        newUser.setPicture(userPayload.getPicture());
        newUser.setSource(COCKPIT_SOURCE);
        newUser.setCustomFields(new HashMap<>());
        if (userPayload.getAdditionalInformation() != null) {
            newUser.getCustomFields().putAll(userPayload.getAdditionalInformation());
        }
        newUser.getCustomFields().computeIfAbsent(PICTURE, k -> userPayload.getPicture());
        newUser.getCustomFields().computeIfAbsent(SUB, k -> userPayload.getUsername());
        try {
            UserEntity cockpitUserEntity = userService.create(newUser, false);
            logger.info("User [{}] created with APIM id [{}].", userPayload.getUsername(), cockpitUserEntity.getId());
            return Single.just(new UserReply(command.getId(), CommandStatus.SUCCEEDED));
        } catch (Exception e) {
            logger.info("Error occurred when creating user [{}] for organization [{}].", userPayload.getUsername(), userPayload.getOrganizationId(), e);
            return Single.just(new UserReply(command.getId(), CommandStatus.ERROR));
        }
    } catch (Exception e) {
        logger.info("Error occurred when updating user [{}] for organization [{}].", userPayload.getUsername(), userPayload.getOrganizationId(), e);
        return Single.just(new UserReply(command.getId(), CommandStatus.ERROR));
    } finally {
        GraviteeContext.cleanContext();
    }
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) Logger(org.slf4j.Logger) PICTURE(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity.UserProfile.PICTURE) SUB(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity.UserProfile.SUB) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) LoggerFactory(org.slf4j.LoggerFactory) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) HashMap(java.util.HashMap) Single(io.reactivex.Single) Command(io.gravitee.cockpit.api.command.Command) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) UserReply(io.gravitee.cockpit.api.command.user.UserReply) Component(org.springframework.stereotype.Component) UserService(io.gravitee.rest.api.service.UserService) CommandHandler(io.gravitee.cockpit.api.command.CommandHandler) 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) UserEntity(io.gravitee.rest.api.model.UserEntity) UserPayload(io.gravitee.cockpit.api.command.user.UserPayload) HashMap(java.util.HashMap) NewExternalUserEntity(io.gravitee.rest.api.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) UpdateUserEntity(io.gravitee.rest.api.model.UpdateUserEntity) NewExternalUserEntity(io.gravitee.rest.api.model.NewExternalUserEntity) UserEntity(io.gravitee.rest.api.model.UserEntity) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) UserReply(io.gravitee.cockpit.api.command.user.UserReply)

Example 3 with UserNotFoundException

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

the class UserCommandHandlerTest method handleWithCreateException.

@Test
public void handleWithCreateException() {
    UserPayload userPayload = new UserPayload();
    UserCommand command = new UserCommand(userPayload);
    final String sourceId = "user#1";
    userPayload.setId(sourceId);
    userPayload.setOrganizationId("orga#1");
    when(userService.findBySource("cockpit", sourceId, false)).thenThrow(new UserNotFoundException(sourceId));
    when(userService.create(any(NewExternalUserEntity.class), eq(false))).thenThrow(new RuntimeException("fake error"));
    TestObserver<UserReply> obs = cut.handle(command).test();
    obs.awaitTerminalEvent();
    obs.assertValue(reply -> reply.getCommandId().equals(command.getId()) && reply.getCommandStatus().equals(CommandStatus.ERROR));
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) UserCommand(io.gravitee.cockpit.api.command.user.UserCommand) UserPayload(io.gravitee.cockpit.api.command.user.UserPayload) NewExternalUserEntity(io.gravitee.rest.api.model.NewExternalUserEntity) UserReply(io.gravitee.cockpit.api.command.user.UserReply) Test(org.junit.Test)

Example 4 with UserNotFoundException

use of io.gravitee.rest.api.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
    final String userInfo = IOUtils.toString(read("/oauth2/json/user_info_response_body_no_matching.json"), Charset.defaultCharset());
    mockUserInfo(okJson(userInfo));
    // mock DB find user by name
    when(userService.findBySource(USER_SOURCE_OAUTH2, "janedoe@example.com", false)).thenThrow(new UserNotFoundException("janedoe@example.com"));
    // mock create user
    NewExternalUserEntity newExternalUserEntity = mockNewExternalUserEntity();
    UserEntity createdUser = mockUserEntity();
    mockUserCreation(identityProvider, userInfo, createdUser);
    // 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 = orgTarget().request().post(json(payload));
    // -- VERIFY
    verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(refEq(identityProvider), anyString());
    verify(userService, times(1)).connect("janedoe@example.com");
    // verify group creations
    verify(membershipService, times(0)).addRoleToMemberOnReference(any(MembershipService.MembershipReference.class), any(MembershipService.MembershipMember.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.rest.api.service.exceptions.UserNotFoundException) Response(javax.ws.rs.core.Response) Test(org.junit.Test) AbstractResourceTest(io.gravitee.rest.api.management.rest.resource.AbstractResourceTest)

Example 5 with UserNotFoundException

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

the class OAuth2AuthenticationResourceTest method shouldConnectNewUserWithGroupsMappingFromUserInfoWhenGroupIsNotFound.

@Test
public void shouldConnectNewUserWithGroupsMappingFromUserInfoWhenGroupIsNotFound() throws Exception {
    // -- MOCK
    // mock environment
    mockDefaultEnvironment();
    mockGroupsMapping();
    // mock oauth2 exchange authorisation code for access token
    mockExchangeAuthorizationCodeForAccessToken();
    // mock oauth2 user info call
    final String userInfo = IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset());
    mockUserInfo(okJson(userInfo));
    // mock DB find user by name
    when(userService.findBySource(USER_SOURCE_OAUTH2, "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(identityProvider, userInfo, createdUser);
    // mock DB user connect
    when(userService.connect(createdUser.getId())).thenReturn(createdUser);
    // -- CALL
    AbstractAuthenticationResource.Payload payload = createPayload("the_client_id", "http://localhost/callback", "CoDe", "StAtE");
    Response response = orgTarget().request().post(json(payload));
    // -- VERIFY
    verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(refEq(identityProvider), anyString());
    verify(userService, times(0)).update(any(String.class), any(UpdateUserEntity.class));
    verify(userService, times(1)).connect(anyString());
    // verify group creations
    verify(membershipService, times(0)).addRoleToMemberOnReference(any(MembershipService.MembershipReference.class), any(MembershipService.MembershipMember.class), any(MembershipService.MembershipRole.class));
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    // verify jwt token
    verifyJwtToken(response);
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) Response(javax.ws.rs.core.Response) Test(org.junit.Test) AbstractResourceTest(io.gravitee.rest.api.management.rest.resource.AbstractResourceTest)

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