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);
}
}
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);
}
}
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());
}
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());
}
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);
}
Aggregations