Skip to content
This repository was archived by the owner on Apr 5, 2024. It is now read-only.

Commit 25b1811

Browse files
committed
Refactored UserBusinessService.updateUser
1 parent 1b469f7 commit 25b1811

File tree

2 files changed

+81
-43
lines changed

2 files changed

+81
-43
lines changed

src/main/java/de/filefighter/rest/domain/user/business/UserBusinessService.java

Lines changed: 56 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -161,75 +161,90 @@ public void updateUser(long userId, UserRegisterForm userToUpdate, User authenti
161161
throw new UserNotUpdatedException("Only Admins are allowed to update other users.");
162162

163163
UserEntity userEntityToUpdate = userRepository.findByUserId(userId);
164+
if (null == userEntityToUpdate)
165+
throw new UserNotUpdatedException("User does not exist, use register endpoint.");
166+
164167
Update newUpdate = new Update();
165-
boolean changesWereMade = false;
166168

167-
// username
168-
String username = userToUpdate.getUsername();
169-
if (null != username) {
170-
if (!stringIsValid(username))
171-
throw new UserNotUpdatedException("Wanted to change username, but username was not valid.");
169+
boolean changesWereMade = updateUserName(newUpdate, userToUpdate.getUsername());
172170

173-
User user = null;
171+
boolean usernameIsValid = stringIsValid(userToUpdate.getUsername());
172+
String lowerCaseUsername = usernameIsValid ? userToUpdate.getUsername().toLowerCase() : userEntityToUpdate.getLowercaseUsername();
173+
boolean passwordWasUpdated = updatePassword(newUpdate, userToUpdate.getPassword(), userToUpdate.getConfirmationPassword(), lowerCaseUsername);
174+
changesWereMade = passwordWasUpdated || changesWereMade;
175+
176+
boolean userGroupsWereUpdated = updateGroups(newUpdate, userToUpdate.getGroupIds(), authenticatedUserIsAdmin);
177+
changesWereMade = userGroupsWereUpdated || changesWereMade;
178+
179+
if (!changesWereMade)
180+
throw new UserNotUpdatedException("No changes were made.");
181+
182+
Query query = new Query();
183+
query.addCriteria(Criteria.where("userId").is(userId));
184+
mongoTemplate.findAndModify(query, newUpdate, UserEntity.class);
185+
}
186+
187+
private boolean updateGroups(Update newUpdate, long[] groupIds, boolean authenticatedUserIsAdmin) {
188+
if (null != groupIds) {
174189
try {
175-
user = this.findUserByUsername(username);
176-
} catch (UserNotFoundException ignored) {
177-
LOG.info("Username '{}' is free to use.", username);
190+
for (Groups group : groupRepository.getGroupsByIds(groupIds)) {
191+
if (group == Groups.ADMIN && !authenticatedUserIsAdmin)
192+
throw new UserNotUpdatedException("Only admins can add users to group " + Groups.ADMIN.getDisplayName() + ".");
193+
}
194+
} catch (IllegalArgumentException exception) {
195+
throw new UserNotUpdatedException("One or more groups do not exist.");
178196
}
179197

180-
if (null != user)
181-
throw new UserNotUpdatedException("Username already taken.");
182-
183-
changesWereMade = true;
184-
newUpdate.set("username", username);
198+
newUpdate.set("groupIds", groupIds);
199+
return true;
185200
}
201+
return false;
202+
}
186203

187-
// pw
188-
if (null != userToUpdate.getPassword()) {
189-
String password = userToUpdate.getPassword();
190-
String confirmation = userToUpdate.getConfirmationPassword();
204+
private boolean updatePassword(Update newUpdate, String password, String confirmationPassword, String lowercaseUserName) {
205+
if (null != password) {
191206

192-
if (!stringIsValid(password) || !stringIsValid(confirmation))
207+
if (!stringIsValid(password) || !stringIsValid(confirmationPassword))
193208
throw new UserNotUpdatedException("Wanted to change password, but password was not valid.");
194209

195210
if (!passwordIsValid(password))
196211
throw new UserNotUpdatedException("Password needs to be at least 8 characters long and, contains at least one uppercase and lowercase letter and a number.");
197212

198-
if (!password.contentEquals(confirmation))
213+
if (!password.contentEquals(confirmationPassword))
199214
throw new UserNotUpdatedException("Passwords do not match.");
200215

201-
if (password.toLowerCase().contains(userEntityToUpdate.getLowercaseUsername()))
216+
if (password.toLowerCase().contains(lowercaseUserName))
202217
throw new UserNotUpdatedException("Username must not appear in password.");
203218

204-
changesWereMade = true;
205219
newUpdate.set("password", password);
206-
207220
//update refreshToken
208221
String newRefreshToken = AccessTokenBusinessService.generateRandomTokenValue();
209222
newUpdate.set("refreshToken", newRefreshToken);
223+
224+
return true;
210225
}
226+
return false;
227+
}
228+
229+
private boolean updateUserName(Update update, String username) {
230+
if (null != username) {
231+
if (!stringIsValid(username))
232+
throw new UserNotUpdatedException("Wanted to change username, but username was not valid.");
211233

212-
// groups
213-
if (null != userToUpdate.getGroupIds()) {
234+
User user = null;
214235
try {
215-
for (Groups group : groupRepository.getGroupsByIds(userToUpdate.getGroupIds())) {
216-
if (group == Groups.ADMIN && !authenticatedUserIsAdmin)
217-
throw new UserNotUpdatedException("Only admins can add users to group " + Groups.ADMIN.getDisplayName() + ".");
218-
}
219-
} catch (IllegalArgumentException exception) {
220-
throw new UserNotUpdatedException("One or more groups do not exist.");
236+
user = this.findUserByUsername(username);
237+
} catch (UserNotFoundException ignored) {
238+
LOG.info("Username '{}' is free to use.", username);
221239
}
222240

223-
changesWereMade = true;
224-
newUpdate.set("groupIds", userToUpdate.getGroupIds());
225-
}
226-
227-
if (!changesWereMade)
228-
throw new UserNotUpdatedException("No changes were made.");
241+
if (null != user)
242+
throw new UserNotUpdatedException("Username already taken.");
229243

230-
Query query = new Query();
231-
query.addCriteria(Criteria.where("userId").is(userId));
232-
mongoTemplate.findAndModify(query, newUpdate, UserEntity.class);
244+
update.set("username", username);
245+
return true;
246+
}
247+
return false;
233248
}
234249

235250
public long generateRandomUserId() {

src/test/java/de/filefighter/rest/domain/user/business/UserBusinessServiceUnitTest.java

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,19 @@ class UserBusinessServiceUnitTest {
2727
private final MongoTemplate mongoTemplateMock = mock(MongoTemplate.class);
2828
private UserBusinessService userBusinessService;
2929

30+
private static UserEntity userEntityMock;
31+
3032
@BeforeEach
3133
void setUp() {
3234
userBusinessService = new UserBusinessService(userRepositoryMock, userDtoServiceMock, groupRepositoryMock, mongoTemplateMock);
35+
userEntityMock = UserEntity.builder()
36+
.lowercaseUsername("username")
37+
.userId(420)
38+
.username("Username")
39+
.password("password")
40+
.refreshToken("refreshToken")
41+
.groupIds(new long[0])
42+
.build();
3343
}
3444

3545
@Test
@@ -55,7 +65,7 @@ void getRefreshTokenForUserWithoutUser() {
5565
UserNotFoundException ex = assertThrows(UserNotFoundException.class, () ->
5666
userBusinessService.getRefreshTokenForUser(dummyUser)
5767
);
58-
assertEquals("Could not find user with userId " + userId+".", ex.getMessage());
68+
assertEquals("Could not find user with userId " + userId + ".", ex.getMessage());
5969
}
6070

6171
@Test
@@ -99,7 +109,7 @@ void getUserByIdThrowsExceptions() {
99109
UserNotFoundException ex = assertThrows(UserNotFoundException.class, () ->
100110
userBusinessService.getUserById(id));
101111

102-
assertEquals("Could not find user with userId " + id+".", ex.getMessage());
112+
assertEquals("Could not find user with userId " + id + ".", ex.getMessage());
103113
}
104114

105115
@Test
@@ -274,7 +284,13 @@ void updateUserThrows() {
274284
userBusinessService.updateUser(userId, userRegisterForm1, authenticatedUser));
275285
assertEquals("User could not get updated. Only Admins are allowed to update other users.", ex.getMessage());
276286

287+
//user not found with id.
277288
authenticatedUser.setGroups(new Groups[]{Groups.ADMIN});
289+
ex = assertThrows(UserNotUpdatedException.class, () ->
290+
userBusinessService.updateUser(userId, userRegisterForm1, authenticatedUser));
291+
assertEquals("User could not get updated. User does not exist, use register endpoint.", ex.getMessage());
292+
293+
when(userRepositoryMock.findByUserId(userId)).thenReturn(userEntityMock);
278294
ex = assertThrows(UserNotUpdatedException.class, () ->
279295
userBusinessService.updateUser(userId, userRegisterForm1, authenticatedUser));
280296
assertEquals("User could not get updated. No changes were made.", ex.getMessage());
@@ -287,6 +303,8 @@ void updateUserNameThrows() {
287303
User authenticatedUser = User.builder().id(userId).groups(new Groups[]{Groups.FAMILY}).build();
288304
UserEntity dummyEntity = UserEntity.builder().build();
289305

306+
when(userRepositoryMock.findByUserId(userId)).thenReturn(userEntityMock);
307+
290308
userRegisterForm.setUsername("");
291309
UserNotUpdatedException ex = assertThrows(UserNotUpdatedException.class, () ->
292310
userBusinessService.updateUser(userId, userRegisterForm, authenticatedUser));
@@ -307,6 +325,8 @@ void updateUserNameWorks() {
307325
long userId = 420;
308326
User authenticatedUser = User.builder().id(userId).groups(new Groups[]{Groups.FAMILY}).build();
309327

328+
when(userRepositoryMock.findByUserId(userId)).thenReturn(userEntityMock);
329+
310330
assertDoesNotThrow(() -> userBusinessService.updateUser(userId, userRegisterForm, authenticatedUser));
311331
}
312332

@@ -317,11 +337,14 @@ void updatePasswordThrows() {
317337
User authenticatedUser = User.builder().id(userId).groups(new Groups[]{Groups.FAMILY}).build();
318338
UserEntity dummyEntity = UserEntity.builder().userId(userId).lowercaseUsername("password").build();
319339

340+
when(userRepositoryMock.findByUserId(userId)).thenReturn(userEntityMock);
341+
320342
userRegisterForm.setPassword("");
321343
UserNotUpdatedException ex = assertThrows(UserNotUpdatedException.class, () ->
322344
userBusinessService.updateUser(userId, userRegisterForm, authenticatedUser));
323345
assertEquals("User could not get updated. Wanted to change password, but password was not valid.", ex.getMessage());
324346

347+
userRegisterForm.setPassword("somepw");
325348
userRegisterForm.setConfirmationPassword("");
326349
ex = assertThrows(UserNotUpdatedException.class, () ->
327350
userBusinessService.updateUser(userId, userRegisterForm, authenticatedUser));

0 commit comments

Comments
 (0)