use of io.gravitee.rest.api.service.exceptions.UserNotFoundException in project gravitee-management-rest-api by gravitee-io.
the class UsersResourceTest method shouldHaveNoContentResponseWithUnexistingUser.
@Test
public void shouldHaveNoContentResponseWithUnexistingUser() {
doThrow(new UserNotFoundException("my@email.com")).when(userService).resetPasswordFromSourceId("my@email.com", "HTTP://MY-RESET-PAGE");
ResetUserPasswordInput input = new ResetUserPasswordInput().username("my@email.com").resetPageUrl("HTTP://MY-RESET-PAGE");
final Response response = target().path("_reset_password").request().post(Entity.json(input));
assertEquals(HttpStatusCode.NO_CONTENT_204, response.getStatus());
}
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));
}
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());
}
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();
}
}
use of io.gravitee.rest.api.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();
mockRolesMapping();
// mock oauth2 exchange authorisation code for access token
mockExchangeAuthorizationCodeForAccessToken();
// mock oauth2 user info call
final String userInfoBody = IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset());
mockUserInfo(okJson(userInfoBody));
// 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, userInfoBody, createdUser);
// mock group search and association
when(groupService.findById("Example group")).thenReturn(mockGroupEntity("group_id_1", "Example group"));
when(groupService.findById("soft user")).thenReturn(mockGroupEntity("group_id_2", "soft user"));
when(groupService.findById("Others")).thenReturn(mockGroupEntity("group_id_3", "Others"));
when(groupService.findById("Api consumer")).thenReturn(mockGroupEntity("group_id_4", "Api consumer"));
// mock role to add from roleMapping
doAnswer(invocation -> {
((Set) invocation.getArguments()[3]).add(mockRoleEntity(RoleScope.ORGANIZATION, "USER"));
return null;
}).when(userService).computeRolesToAddUser(eq("janedoe@example.com"), eq(identityProvider.getRoleMappings()), eq(userInfoBody), any(Set.class), any(Map.class));
RoleEntity roleApiUser = mockRoleEntity(io.gravitee.rest.api.model.permissions.RoleScope.API, "USER");
RoleEntity roleApplicationAdmin = mockRoleEntity(io.gravitee.rest.api.model.permissions.RoleScope.APPLICATION, "ADMIN");
when(roleService.findDefaultRoleByScopes(RoleScope.API, RoleScope.APPLICATION)).thenReturn(Arrays.asList(roleApiUser, roleApplicationAdmin));
// 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");
assertEquals(HttpStatusCode.OK_200, response.getStatus());
// verify response body
// verifyUserInResponseBody(response);
// verify jwt token
verifyJwtToken(response);
}
Aggregations