Working Implementation for resetting passwords based on a One Time Passcode (OTP). first request Token by stating your email to /request-password-forgot. OTP will be sent via email. Then just type in email, the OTP and a new password to /reset-password.
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

IMPORTANT - EMAIL SETUP in application.properties (if gmail):
#mail provider
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<email>
# Nutze bei Gmail ein "App-Passwort", nicht dein normales (16 stellig)
spring.mail.password=xxxx xxxx xxxx xxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
This commit is contained in:
Daniel
2026-02-17 18:56:59 +01:00
parent 2c0dfaf77b
commit 3d4f6a4d26
7 changed files with 194 additions and 9 deletions
@@ -1,10 +1,11 @@
package SuMoC.backend.security.services;
import SuMoC.backend.security.dtos.LoginResponseDTO;
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
import SuMoC.backend.security.dtos.UserRegistrationDTO;
import SuMoC.backend.notification.services.EmailService;
import SuMoC.backend.security.dtos.*;
import SuMoC.backend.security.enums.RegistrationStatus;
import SuMoC.backend.security.exceptions.InvalidTokenException;
import SuMoC.backend.security.models.PasswordResetToken;
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
import SuMoC.backend.user.dtos.UserDTO;
import SuMoC.backend.user.enums.RoleName;
import SuMoC.backend.user.mapper.UserMapper;
@@ -12,14 +13,20 @@ import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Optional;
@Service
@Transactional
@@ -35,15 +42,20 @@ public class AuthenticationService {
private UserMapper userMapper;
private PasswordResetTokenRepository passwordResetTokenRepository;
private EmailService emailService;
@Autowired
public AuthenticationService(UserRepository userRepository, PasswordEncoder passwordEncoder,
AuthenticationManager authenticationManager, TokenService tokenService,
UserMapper userMapper) {
UserMapper userMapper, PasswordResetTokenRepository passwordResetTokenRepository, EmailService emailService) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authenticationManager = authenticationManager;
this.tokenService = tokenService;
this.userMapper = userMapper;
this.passwordResetTokenRepository = passwordResetTokenRepository;
this.emailService = emailService;
}
public RegistrationResponseDTO registerUser(UserRegistrationDTO registrationDTO) {
@@ -114,4 +126,54 @@ public class AuthenticationService {
return new LoginResponseDTO(null, "");
}
}
/**
*
* @param email the account for which a OTP shall be created to reset the password
*/
@Transactional
public void generateNewPasswordResetTokenForUser(String email) throws UsernameNotFoundException{
if (!userRepository.existsByEmail(email)) throw new UsernameNotFoundException("Es existiert kein Account mit dieser Email") ;
Optional<PasswordResetToken> token = passwordResetTokenRepository.findByEmail(email);
token.ifPresent(passwordResetToken -> {
System.out.println("Found token for this account...Deleting token...");
passwordResetTokenRepository.delete(passwordResetToken);
});
String otp = generate_six_digit_OTP();
PasswordResetToken newToken = new PasswordResetToken(email, otp);
passwordResetTokenRepository.save(newToken);
emailService.sendPasswordResetEmail(newToken.getEmail(), newToken.getOtp_code());
}
@Transactional
public void resetPassword(PasswordResetDTO passwordResetDTO) throws InvalidTokenException, UsernameNotFoundException {
PasswordResetToken token = passwordResetTokenRepository.findByEmail(passwordResetDTO.getEmail())
.orElseThrow(() -> new InvalidTokenException("Token nicht gefunden"));
if (token.getExpiryDate().isBefore(LocalDateTime.now())) {
throw new InvalidTokenException("Code ist abgelaufen");
}
if (!token.getOtp_code().equals(passwordResetDTO.getOtp_code())) {
throw new InvalidTokenException("Code ist ungültig");
}
User user = userRepository.findByEmail(passwordResetDTO.getEmail())
.orElseThrow(() -> new UsernameNotFoundException("User existiert nicht"));
user.setPassword(passwordEncoder.encode(passwordResetDTO.getNew_password()));
userRepository.save(user);
passwordResetTokenRepository.delete(token);
}
private String generate_six_digit_OTP(){
SecureRandom random = new SecureRandom();
int code = 10000 + random.nextInt(90000);
return String.valueOf(code);
}
}