New password cannot be same as the current one
This commit is contained in:
@@ -33,6 +33,7 @@ public enum ApiError {
|
||||
UNAUTHORIZED(HttpStatus.FORBIDDEN, "%s"),
|
||||
PASSWORD_INCORRECT(HttpStatus.BAD_REQUEST, "Incorrect current password"),
|
||||
PASSWORD_WEAK(HttpStatus.BAD_REQUEST, "New password is not strong enough. It must be at least 8 characters long, contain an uppercase letter, a lowercase letter, a number, and a special character."),
|
||||
PASSWORD_SAME_AS_CURRENT(HttpStatus.BAD_REQUEST, "New password cannot be the same as the current password"),
|
||||
INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Invalid credentials");
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
@@ -92,13 +92,21 @@ public class UserService {
|
||||
|
||||
public void changePassword(ChangePasswordRequest changePasswordRequest) {
|
||||
BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUserEntity bookLoreUserEntity = userRepository.findById(bookLoreUser.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId()));
|
||||
BookLoreUserEntity bookLoreUserEntity = userRepository.findById(bookLoreUser.getId())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId()));
|
||||
|
||||
if (!passwordEncoder.matches(changePasswordRequest.getCurrentPassword(), bookLoreUserEntity.getPasswordHash())) {
|
||||
throw ApiError.PASSWORD_INCORRECT.createException();
|
||||
}
|
||||
|
||||
if (passwordEncoder.matches(changePasswordRequest.getNewPassword(), bookLoreUserEntity.getPasswordHash())) {
|
||||
throw ApiError.PASSWORD_SAME_AS_CURRENT.createException();
|
||||
}
|
||||
|
||||
if (!isPasswordStrong(changePasswordRequest.getNewPassword())) {
|
||||
throw ApiError.PASSWORD_WEAK.createException();
|
||||
}
|
||||
|
||||
bookLoreUserEntity.setDefaultPassword(false);
|
||||
bookLoreUserEntity.setPasswordHash(passwordEncoder.encode(changePasswordRequest.getNewPassword()));
|
||||
userRepository.save(bookLoreUserEntity);
|
||||
|
||||
Reference in New Issue
Block a user