Saving encoded OTP instead of raw OTP with PasswordEncoder.encode()
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

This commit is contained in:
Daniel
2026-02-19 13:57:13 +01:00
parent b64eff7ae6
commit e333b3b9ce
@@ -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");
}