wip: stuff

This commit is contained in:
csimonis 2025-05-15 11:19:46 +02:00 committed by Phan Huy Tran
commit 9827f81230
5 changed files with 202 additions and 2 deletions

View file

@ -43,4 +43,10 @@ public class AuthController {
return ResponseEntity.ok().build();
}
@PostMapping("/recover-password")
public ResponseEntity<Void> recoverPassword(@RequestParam("email") String email) throws MessagingException, IOException {
authService.recoverPassword(email);
return ResponseEntity.ok().build();
}
}

View file

@ -16,6 +16,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.swing.text.html.Option;
import java.io.IOException;
import java.util.Optional;
@ -46,7 +47,7 @@ public class AuthService {
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateToken(authentication);
return new AuthResponseDto(jwt);
}
@ -66,7 +67,7 @@ public class AuthService {
public Boolean verifyEmail(String token) throws MessagingException, IOException {
Optional<UserEntity> optionalUser = userService.getUserByVerificationToken(token);
if(!optionalUser.isPresent()) {
if (!optionalUser.isPresent()) {
return false;
}
@ -79,4 +80,16 @@ public class AuthService {
return true;
}
public void recoverPassword(String email) {
Optional<UserEntity> optionalUser = userService.getUserByEmail(email);
if (optionalUser.isPresent()) {
UserEntity user = optionalUser.get();
String token = jwtUtils.generateToken(user.getUsername());
user.setVerificationToken(token);
userService.saveUser(user);
this.emailService.sendPasswordRecoveryEmail(user);
}
}
}

View file

@ -87,6 +87,23 @@ public class EmailService {
mailSender.send(message);
}
public void sendPasswordRecoveryEmail(UserEntity user) throws IOException, MessagingException {
String template = loadTemplate("email/recover-password.html");
String htmlContent = template
.replace("${username}", user.getUsername())
.replace("${feUrl}", feUrl);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(mailConfig.fromAddress);
helper.setTo(user.getEmailAddress());
helper.setSubject("Zurücksetzen ihres Passworts");
helper.setText(htmlContent, true);
mailSender.send(message);
}
private String loadTemplate(String templatePath) throws IOException {
ClassPathResource resource = new ClassPathResource("templates/" + templatePath);
try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {

View file

@ -62,4 +62,8 @@ public class UserService {
return optionalUser.get().getEmailVerified();
}
public Optional<UserEntity> getUserByEmail(String email) {
return userRepository.findByEmail(email);
}
}