Skip to content
This repository has been archived by the owner on Nov 27, 2024. It is now read-only.

Commit

Permalink
refactor UserMailSendService.java
Browse files Browse the repository at this point in the history
CompletableFuture 삭제
secure random 문자열 생성으로 변경
  • Loading branch information
ori0o0p committed Mar 20, 2024
1 parent e6ca973 commit 49ee908
Showing 1 changed file with 12 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
import reactor.core.scheduler.Scheduler;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

@Service
public class UserMailSendService implements UserMailSendUsecase {
Expand All @@ -41,23 +41,21 @@ public UserMailSendService(SaveAuthCodePort saveAuthCodePort, JavaMailSender jav
@Value("${admin.mail}")
private String admin;

private static final Random rand = new Random();

@Override
public Mono<Void> send(AuthCodeRequest request) {
String mail = request.mail();

return getUserPort.findByEmail(mail)
.flatMap(user -> {
if (Objects.equals(request.type(), MailType.CHANGE_PW.getType())) {
return Mono.empty();
} else {
if (Objects.equals(request.type(), MailType.SIGNUP.getType())) {
return Mono.error(EmailAlreadyExistsException.EXCEPTION);
} else {
return Mono.empty();
}
})
.then(Mono.defer(() -> {
String authCode = getRandomCode();

sendMail(mail, authCode)
.subscribeOn(scheduler)
.subscribe();
Expand All @@ -67,7 +65,7 @@ public Mono<Void> send(AuthCodeRequest request) {
}

private Mono<Void> sendMail(String to, String authCode) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
return Mono.fromRunnable(() -> {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
Expand All @@ -84,11 +82,7 @@ private Mono<Void> sendMail(String to, String authCode) {
} catch (MessagingException | UnsupportedEncodingException e) {
throw MailSendFailedException.EXCEPTION;
}
});

return Mono.fromFuture(future)
.onErrorMap(e -> MailSendFailedException.EXCEPTION)
.then();
}).onErrorMap(e -> MailSendFailedException.EXCEPTION).then();
}

private Mono<Void> saveAuthCode(String to, String authCode) {
Expand All @@ -108,8 +102,10 @@ private String getMailTemplate(String key) {
}

private String getRandomCode() {
int num = rand.nextInt(900000) + 100000;
return String.valueOf(num);
SecureRandom secureRandom = new SecureRandom();
byte[] randomBytes = new byte[6];
secureRandom.nextBytes(randomBytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(randomBytes);
}

}

0 comments on commit 49ee908

Please sign in to comment.