package SuMoC.backend.security.services; 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; 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.mail.MailException; 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 public class AuthenticationService { private UserRepository userRepository; private PasswordEncoder passwordEncoder; private AuthenticationManager authenticationManager; private TokenService tokenService; private UserMapper userMapper; private PasswordResetTokenRepository passwordResetTokenRepository; private EmailService emailService; @Autowired public AuthenticationService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager, TokenService tokenService, 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; } private boolean isPasswordFormatCorrect(String password) { //insert other check ups for passwords if(password.length() < 8) return false; return true; } public RegistrationResponseDTO registerUser(UserRegistrationDTO registrationDTO) { try { // check if mail is already in use if (userRepository.existsByEmail(registrationDTO.getEmail().toLowerCase())) { return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_EXISTS); } // check if public name is already in use if (userRepository.existsByPublicName(registrationDTO.getPublicName())) { return new RegistrationResponseDTO(null, null, RegistrationStatus.PUBLIC_NAME_EXISTS); } // Validate Email String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"; if (!registrationDTO.getEmail().toLowerCase().matches(emailRegex)) { return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_INVALID); } //validate Password if(!isPasswordFormatCorrect(registrationDTO.getPassword())) return new RegistrationResponseDTO(null, null, RegistrationStatus.PASSWORD_INVALID); // encode password String encodedPassword = passwordEncoder.encode(registrationDTO.getPassword()); // create and save user User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail().toLowerCase(), encodedPassword); // Sicherheitshalber nochmal explizit setzen if (user.getRoles() == null || user.getRoles().isEmpty()) { user.setRoles(new HashSet<>()); user.getRoles().add(RoleName.USER); } userRepository.save(user); // We generate the login dto to get the token right after registration LoginResponseDTO loginResponseDTO = login(new UserAuthenticationPairDTO(registrationDTO.getEmail().toLowerCase(), registrationDTO.getPassword())); // But now we return RegistrationResponseDTO for better status handling return new RegistrationResponseDTO(loginResponseDTO.getUserDTO(), loginResponseDTO.getJwt(), RegistrationStatus.SUCCESS); } catch (IllegalArgumentException e) { System.err.println("Registration error: " + e.getMessage()); return new RegistrationResponseDTO(null, null, RegistrationStatus.UNKNOWN_ERROR); } } public LoginResponseDTO login(UserAuthenticationPairDTO authPairDTO) { // System.out.println(" ##################### Login Request ##################### "); // System.out.println(authPairDTO); // System.out.println(authPairDTO.getEmail()); // System.out.println(authPairDTO.getPassword()); try { Authentication auth = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(authPairDTO.getEmail().toLowerCase(), authPairDTO.getPassword()) ); User user = userRepository.findByEmail(authPairDTO.getEmail().toLowerCase()) .orElseThrow(() -> new RuntimeException("User not found")); UserDTO userDTO = userMapper.toUserDTO(user); String token = tokenService.generateUserJwt(auth, userDTO); return new LoginResponseDTO(userDTO, token); } catch (AuthenticationException e) { //System.out.println("AuthenticationException: " + e.getMessage()); return new LoginResponseDTO(null, ""); } catch ( RuntimeException e) { return new LoginResponseDTO(null, ""); } } /** * * @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{ if (!userRepository.existsByEmail(email)) throw new UsernameNotFoundException("Es existiert kein Account mit dieser Email") ; Optional 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(); passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp emailService.sendPasswordResetEmail(email, otp); } @Transactional public void resetPassword(PasswordResetDTO passwordResetDTO) throws InvalidTokenException, UsernameNotFoundException { PasswordResetToken token = passwordResetTokenRepository.findByEmail(passwordResetDTO.getEmail()) .orElseThrow(() -> new InvalidTokenException("Token nicht gefunden")); if (LocalDateTime.now().isAfter(token.getExpiryDate())) { throw new InvalidTokenException("Code ist abgelaufen"); } //use .matches() so compare raw otp to (salted!) encoded otp if(!passwordEncoder.matches(passwordResetDTO.getOtpCode(),token.getOtpCode())){ throw new InvalidTokenException("Code ist ungültig"); } if(!isPasswordFormatCorrect(passwordResetDTO.getNewPassword())) { throw new InvalidTokenException("Passwortformat ist nicht korrekt"); } User user = userRepository.findByEmail(passwordResetDTO.getEmail()) .orElseThrow(() -> new UsernameNotFoundException("User existiert nicht")); user.setPassword(passwordEncoder.encode(passwordResetDTO.getNewPassword())); userRepository.save(user); passwordResetTokenRepository.delete(token); } private String generate_six_digit_OTP(){ SecureRandom random = new SecureRandom(); // Generiert eine Zahl von 0 bis 999.999 int code = random.nextInt(1000000); // Formatiert die Zahl auf 6 Stellen und füllt links mit 0 auf return String.format("%06d", code); } }