Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thinkmicroservices/cc6b119576ef6a78999907c59155021c to your computer and use it in GitHub Desktop.
Save thinkmicroservices/cc6b119576ef6a78999907c59155021c to your computer and use it in GitHub Desktop.
AuthenticationService:resetPassword().java
/**
*
* @param email
* @param recoveryCode
* @param newPassword
* @param passwordConfirm
* @throws ResetPasswordException
*/
public void resetPassword(String email, String recoveryCode, String newPassword,
String passwordConfirm) throws ResetPasswordException {
log.debug("reset password");
// check if the email is a registered user
User userModel = userRepository.findByUsername(email);
if (userModel == null) {
throw new ResetPasswordException("error.passwordreset.invalid.user", email);
}
long currentTime = System.currentTimeMillis();
if (userModel.getRecoveryExpiresAt() != null) {
log.debug("difference -{}", userModel.getRecoveryExpiresAt().getTime() - currentTime);
}
// check if the recovery code exists for the user
String persistedRecoveryCode = userModel.getRecoveryCode();
if ((persistedRecoveryCode == null) || (!persistedRecoveryCode.equals(recoveryCode))) {
throw new ResetPasswordException(I18NResourceBundle.translateForLocale("error.passwordreset.invalid.code"));
}
// check if the recovery code expiration is set
if (userModel.getRecoveryExpiresAt() == null) {
log.debug("no recovery expiration date");
throw new ResetPasswordException("error.passwordreset.invalid.code");
}
// check the recovery code hasn't expired
if (currentTime > userModel.getRecoveryExpiresAt().getTime()) {
log.debug("recovery code expired");
throw new ResetPasswordException("error.passwordreset.recovery.code.expired");
}
// check if the new password meets the complexity requirements
if ((newPassword == null) || (!this.validator.isPasswordValid(newPassword))) {
throw new ResetPasswordException("error.passwordreset.password.complexity.failure");
}
// check if the confirmation password matches
if (!newPassword.equals(passwordConfirm)) {
throw new ResetPasswordException("error.passwordreset.password.does.not.match");
}
// ok- change the password
userModel.setPassword(bcryptEncoder.encode(newPassword));
userRepository.save(userModel);
// send account event "ResetPassword"
this.accountEventSource
.accountEvents()
.send(MessageBuilder.withPayload(new PasswordRecoveryCompletedEvent(userModel.getAccountId(), userModel.getEmail()))
.setHeader("type", "PASSWORD_RECOVERY_COMPLETED_EVENT").build());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment