From e333b3b9ce123714770162ddc35ab68b0171c305 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 19 Feb 2026 13:57:13 +0100 Subject: [PATCH] Saving encoded OTP instead of raw OTP with PasswordEncoder.encode() --- .../security/services/AuthenticationService.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/SuMoC/backend/security/services/AuthenticationService.java b/src/main/java/SuMoC/backend/security/services/AuthenticationService.java index d181026..9e81500 100644 --- a/src/main/java/SuMoC/backend/security/services/AuthenticationService.java +++ b/src/main/java/SuMoC/backend/security/services/AuthenticationService.java @@ -141,6 +141,8 @@ public class AuthenticationService { /** * * @param email the account for which a OTP shall be created to reset the password + * + * NOTE: OTP Code gets hashed by passwordEncoder */ @Transactional public void generateNewPasswordResetTokenForUser(String email) throws UsernameNotFoundException, MailException{ @@ -153,26 +155,23 @@ public class AuthenticationService { }); String otp = generate_six_digit_OTP(); - PasswordResetToken newToken = new PasswordResetToken(email, otp); - passwordResetTokenRepository.save(newToken); - - emailService.sendPasswordResetEmail(newToken.getEmail(), newToken.getOtp_code()); + passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp + emailService.sendPasswordResetEmail(email, otp); } @Transactional public void resetPassword(PasswordResetDTO passwordResetDTO) throws InvalidTokenException, UsernameNotFoundException { - System.out.println("## RESETING PASSWORD FOR: " + passwordResetDTO.getEmail() + " with code " + passwordResetDTO.getOtp_code() ); - PasswordResetToken token = passwordResetTokenRepository.findByEmail(passwordResetDTO.getEmail()) .orElseThrow(() -> new InvalidTokenException("Token nicht gefunden")); - if (token.getExpiryDate().isBefore(LocalDateTime.now())) { + if (LocalDateTime.now().isAfter(token.getExpiryDate())) { throw new InvalidTokenException("Code ist abgelaufen"); } - if (!token.getOtp_code().equals(passwordResetDTO.getOtp_code())) { + //use .matches() so compare raw otp to (salted!) encoded otp + if(!passwordEncoder.matches(passwordResetDTO.getOtp_code(),token.getOtp_code())){ throw new InvalidTokenException("Code ist ungültig"); }