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
@@ -0,0 +1,29 @@
package SuMoC.backend.notification.services;
import SuMoC.backend.security.dtos.PasswordResetDTO;
import SuMoC.backend.security.models.PasswordResetToken;
import SuMoC.backend.security.services.AuthenticationService;
import jdk.dynalink.linker.support.SimpleLinkRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendPasswordResetEmail(String email, String otp_code){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("noreply@SuMoC.de");
message.setTo(email);
message.setSubject("Dein Passwort-Reset Code");
message.setText("Hallo!\n\nDein OTP Code lautet: " + otp_code +
"\nDieser Code ist für " + String.valueOf(PasswordResetToken.EXPIRY_TIME_MINUTES) + " Minuten gültig.");
mailSender.send(message);
}
}
@@ -1,11 +1,11 @@
package SuMoC.backend.security.controller;
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.security.dtos.*;
import SuMoC.backend.security.exceptions.InvalidTokenException;
import SuMoC.backend.security.models.PasswordResetToken;
import SuMoC.backend.security.services.AuthenticationService;
import SuMoC.backend.user.repository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -14,6 +14,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -74,4 +75,36 @@ public class UserAuthenticationController {
return new ResponseEntity<>(responseDTO, HttpStatus.OK);
}
@PostMapping("/request-password-forgot")
public ResponseEntity<String> handleForgotPasswordRequest(@RequestBody String email){
System.out.println("####################### Handle Password Reset Request #######################");
System.out.println(email);
try{
authenticationService.generateNewPasswordResetTokenForUser(email);
return ResponseEntity.ok("OTP Token erstellt");
} catch (UsernameNotFoundException e) {
return ResponseEntity.badRequest().body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.internalServerError().body("Fehler beim erstellen des OTP Tokens");
}
}
@PostMapping("/reset-password")
public ResponseEntity<String> handlePasswordResetRequest(@RequestBody PasswordResetDTO passwordResetDTO){
System.out.println("####################### Handle Password Reset Request RESET #######################");
System.out.println(passwordResetDTO.getEmail() + " | newPW: " + passwordResetDTO.getNew_password() + " | Code: " + passwordResetDTO.getOtp_code());
try {
authenticationService.resetPassword(passwordResetDTO);
return ResponseEntity.ok("Passwort erfolgreich geändert");
} catch (InvalidTokenException | UsernameNotFoundException e) {
// 400 Bad Request mit der genauen Fehlermeldung
return ResponseEntity.badRequest().body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Fehler beim Reset");
}
}
}
@@ -0,0 +1,12 @@
package SuMoC.backend.security.dtos;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PasswordResetDTO {
String otp_code;
String email;
String new_password;
}
@@ -0,0 +1,5 @@
package SuMoC.backend.security.exceptions;
public class InvalidTokenException extends RuntimeException {
public InvalidTokenException(String message) { super(message); }
}
@@ -0,0 +1,32 @@
package SuMoC.backend.security.models;
import jakarta.persistence.*;
import lombok.Getter;
import java.time.LocalDateTime;
@Entity
@Table(name = "OneTimePasswordTokens")
@Getter
public class PasswordResetToken{
public static int EXPIRY_TIME_MINUTES = 30;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String otp_code;
private LocalDateTime expiryDate;
public PasswordResetToken(String email, String code) {
this.email = email;
this.otp_code = code;
this.expiryDate = LocalDateTime.now().plusMinutes(EXPIRY_TIME_MINUTES);
}
public PasswordResetToken() {
}
}
@@ -0,0 +1,12 @@
package SuMoC.backend.security.repository;
import SuMoC.backend.security.models.PasswordResetToken;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {
Boolean existsByEmail(String email);
Optional<PasswordResetToken> findByEmail(String email);
}
@@ -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);
}
}