Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save thinkmicroservices/8cf5ac8e8537a9610ef456cd428959e5 to your computer and use it in GitHub Desktop.

Select an option

Save thinkmicroservices/8cf5ac8e8537a9610ef456cd428959e5 to your computer and use it in GitHub Desktop.
AuthenticationService: changePassword().java
/**
*
* @param changePasswordRequest
* @return
* @throws ChangePasswordException
*/
public void changePassword(String accountId, String currentPassword, String newPassword, String confirmPassword) throws ChangePasswordException {
User userModel = null;
log.debug("change password accountID:{}", accountId);
// lookup the user by email address
if (accountId != null) {
// check if the user exists
log.debug("change password for account id:{}", accountId);
userModel = this.userRepository.findByAccountId(accountId);
if (userModel == null) {
throw new ChangePasswordException("error.authentication.token.isnull");
}
// check if the current password has been supplied
if ((currentPassword == null) || (currentPassword.length() == 0)) {
throw new ChangePasswordException("error.authentication.current.password.required");
}
// check if the current password supplied matches the persisted password
if (!this.bcryptEncoder.matches(currentPassword, userModel.getPassword())) {
throw new ChangePasswordException("error.authentication.current.password.does.not.match");
}
// check if they supplied a new password
if ((newPassword == null) || (newPassword.length() == 0)) {
throw new ChangePasswordException("error.changepassword.cannot.be.empty");
}
// check if the user supplied a matching confirmation password
if (!newPassword.equals(confirmPassword)) {
throw new ChangePasswordException("error.changepassword.confirmation.does.not.match");
}
// check that the new password meets the complexity requirements
if (!validator.isPasswordValid(newPassword)) {
throw new ChangePasswordException("error.changepassword.complexity.failure");
}
// save the new password
userModel.setPassword(bcryptEncoder.encode(newPassword));
userRepository.save(userModel);
// send account event "ChangePassword"
this.accountEventSource
.accountEvents()
.send(MessageBuilder.withPayload(new PasswordChangedEvent(userModel.getAccountId(), userModel.getEmail()))
.setHeader("type", "PASSWORD_CHANGED_EVENT").build());
} else {
throw new ChangePasswordException("error.authentication.token.invalid");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment