Search in sources :

Example 6 with UserNotFoundException

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

the class UserServiceImpl method update.

@Override
public UserEntity update(UpdateUserEntity updateUserEntity) {
    try {
        LOGGER.debug("Updating {}", updateUserEntity);
        Optional<User> checkUser = userRepository.findByUsername(updateUserEntity.getUsername());
        if (!checkUser.isPresent()) {
            throw new UserNotFoundException(updateUserEntity.getUsername());
        }
        User user = checkUser.get();
        User previousUser = new User(user);
        // Set date fields
        user.setUpdatedAt(new Date());
        // Set variant fields
        user.setPicture(updateUserEntity.getPicture());
        user.setFirstname(updateUserEntity.getFirstname());
        user.setLastname(updateUserEntity.getLastname());
        User updatedUser = userRepository.update(user);
        auditService.createPortalAuditLog(Collections.singletonMap(USER, user.getUsername()), User.AuditEvent.USER_UPDATED, user.getUpdatedAt(), previousUser, user);
        return convert(updatedUser, true);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to update {}", updateUserEntity, ex);
        throw new TechnicalManagementException("An error occurs while trying update " + updateUserEntity, 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)

Example 7 with UserNotFoundException

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

the class UserServiceImpl method connect.

@Override
public UserEntity connect(String userId) {
    try {
        LOGGER.debug("Connection of {}", userId);
        Optional<User> checkUser = userRepository.findById(userId);
        if (!checkUser.isPresent()) {
            throw new UserNotFoundException(userId);
        }
        User user = checkUser.get();
        User previousUser = new User(user);
        // First connection: create default application for user
        if (defaultApplicationForFirstConnection && user.getLastConnectionAt() == null) {
            LOGGER.debug("Create a default application for {}", userId);
            NewApplicationEntity defaultApp = new NewApplicationEntity();
            defaultApp.setName("Default application");
            defaultApp.setDescription("My default application");
            applicationService.create(defaultApp, userId);
        }
        // Set date fields
        user.setLastConnectionAt(new Date());
        user.setUpdatedAt(user.getLastConnectionAt());
        User updatedUser = userRepository.update(user);
        auditService.createPortalAuditLog(Collections.singletonMap(USER, userId), User.AuditEvent.USER_CONNECTED, user.getUpdatedAt(), previousUser, user);
        return convert(updatedUser, true);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to connect {}", userId, ex);
        throw new TechnicalManagementException("An error occurs while trying to connect " + userId, 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)

Example 8 with UserNotFoundException

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

the class GitHubAuthenticationResource method processUser.

private Response processUser(final Map<String, Object> userInfo) {
    String username = (String) userInfo.get("email");
    if (username == null) {
        throw new BadRequestException("No public email linked to your GitHub account");
    }
    // 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.GITHUB.getName());
        newUser.setSourceId(userInfo.get("id").toString());
        String[] partNames = userInfo.get("name").toString().split(" ");
        newUser.setLastname(partNames[0]);
        newUser.setFirstname(partNames[1]);
        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("avatar_url").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) BadRequestException(javax.ws.rs.BadRequestException) 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 9 with UserNotFoundException

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

the class OAuth2AuthenticationResource method processUser.

private Response processUser(String userInfo) throws IOException {
    HashMap<String, String> attrs = getUserProfileAttrs(userInfo);
    List<ExpressionMapping> mappings = serverConfiguration.getGroupsMapping();
    String username = attrs.get(UserProfile.EMAIL);
    if (username == null) {
        throw new BadRequestException("No public email linked to your account");
    }
    // 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.setEmail(username);
        newUser.setSource(AuthenticationSource.OAUTH2.getName());
        if (attrs.get(UserProfile.ID) != null) {
            newUser.setSourceId(attrs.get(UserProfile.ID));
        }
        if (attrs.get(UserProfile.LASTNAME) != null) {
            newUser.setLastname(attrs.get(UserProfile.LASTNAME));
        }
        if (attrs.get(UserProfile.FIRSTNAME) != null) {
            newUser.setFirstname(attrs.get(UserProfile.FIRSTNAME));
        }
        if (attrs.get(UserProfile.PICTURE) != null) {
            newUser.setPicture(attrs.get(UserProfile.PICTURE));
        }
        if (!mappings.isEmpty()) {
            // can fail if a group in config does not exist in gravitee --> HTTP 500
            Set<GroupEntity> groupsToAdd = getGroupsToAddUser(username, mappings, userInfo);
            UserEntity createdUser = userService.create(newUser, true);
            userDetails.setUsername(createdUser.getId());
            addUserToApiAndAppGroupsWithDefaultRole(createdUser.getId(), groupsToAdd);
        } else {
            UserEntity createdUser = userService.create(newUser, true);
            userDetails.setUsername(createdUser.getId());
        }
    }
    // User refresh
    UpdateUserEntity user = new UpdateUserEntity();
    user.setUsername(username);
    if (attrs.get(UserProfile.LASTNAME) != null) {
        user.setLastname(attrs.get(UserProfile.LASTNAME));
    }
    if (attrs.get(UserProfile.FIRSTNAME) != null) {
        user.setFirstname(attrs.get(UserProfile.FIRSTNAME));
    }
    if (attrs.get(UserProfile.PICTURE) != null) {
        user.setPicture(attrs.get(UserProfile.PICTURE));
    }
    UserEntity updatedUser = userService.update(user);
    return connectUser(updatedUser.getId());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) ExpressionMapping(io.gravitee.management.rest.resource.auth.oauth2.ExpressionMapping) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 10 with UserNotFoundException

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

the class OAuth2AuthenticationResourceTest method shouldConnectNewUserWithGroupsMappingFromUserInfo.

@Test
public void shouldConnectNewUserWithGroupsMappingFromUserInfo() 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 create user
    NewExternalUserEntity newExternalUserEntity = mockNewExternalUserEntity();
    UserEntity createdUser = mockUserEntity();
    mockUserCreation(newExternalUserEntity, createdUser, true);
    // mock group search and association
    when(groupService.findByName("Example group")).thenReturn(Collections.singletonList(mockGroupEntity("group_id_1", "Example group")));
    when(groupService.findByName("soft user")).thenReturn(Collections.singletonList(mockGroupEntity("group_id_2", "soft user")));
    when(groupService.findByName("Others")).thenReturn(Collections.singletonList(mockGroupEntity("group_id_3", "Others")));
    when(groupService.findByName("Api consumer")).thenReturn(Collections.singletonList(mockGroupEntity("group_id_4", "Api consumer")));
    RoleEntity roleApiUser = mockRoleEntity(io.gravitee.management.model.permissions.RoleScope.API, "USER");
    RoleEntity roleApplicationAdmin = mockRoleEntity(io.gravitee.management.model.permissions.RoleScope.APPLICATION, "ADMIN");
    when(roleService.findDefaultRoleByScopes(RoleScope.API, RoleScope.APPLICATION)).thenReturn(Arrays.asList(roleApiUser, roleApplicationAdmin));
    when(membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"))).thenReturn(mockMemberEntity());
    when(membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"))).thenReturn(mockMemberEntity());
    when(membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))).thenReturn(mockMemberEntity());
    when(membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"))).thenReturn(mockMemberEntity());
    when(membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"))).thenReturn(mockMemberEntity());
    // 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(1)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"));
    verify(membershipService, times(1)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_1"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"));
    verify(membershipService, times(1)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"));
    verify(membershipService, times(1)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_2"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"));
    verify(membershipService, times(0)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_3"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"));
    verify(membershipService, times(0)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_3"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"));
    verify(membershipService, times(1)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.API, "USER"));
    verify(membershipService, times(1)).addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.GROUP, "group_id_4"), new MembershipService.MembershipUser("janedoe@example.com", null), new MembershipService.MembershipRole(RoleScope.APPLICATION, "ADMIN"));
    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) MembershipService(io.gravitee.management.service.MembershipService) AbstractResourceTest(io.gravitee.management.rest.resource.AbstractResourceTest) Test(org.junit.Test)

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