오늘 학습한 내용
- email 인증 기능 구현
- 회원가입 validation 적용
이메일 인증 기능
오늘은 이메일 인증 기능을 추가했다.
우선 build.gradle에 의존성을 추가해준다.
//email 인증
implementation 'org.springframework.boot:spring-boot-starter-mail'
application.properties에도 다음을 추가해준다.
#email
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username= 아이디
spring.mail.password= 비밀번호
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true
아이디와 비밀번호는 다음 블로그를 참고하면 적용할 수 있다.
https://gwamssoju.tistory.com/108
인증번호 전송 기능을 구현해보자!
저번 포스팅에서 메시지 큐에 대해 알아보면서 메시지 큐가 어떤 경우에 쓰이는지 알아보던 중 메일을 보내는 로직에서 사용된다는 것을 알 수 있었다. 예전에 Hi Planner 프로젝트에서 회원 가입
gwamssoju.tistory.com
우선 인증 번호를 저장할 redis를 설정을 해줬다.
redis를 사용한 이유는 인증번호의 유효기간 동안만 저장할 수 있어서 데이터 관리에 쉽기 때문에 사용하기로 결정했다.
또한 인증번호가 변경될 경우가 없고, 조회의 기능만 수행하기에 성능적으로 더 좋을 것이라 생각했다.
private final RedisTemplate<String, Object> redisAuthNumberTemplate;
// email 인증번호 저장
public void setAuthNumber(Integer key, Object o, Long milliSeconds) {
redisAuthNumberTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(o.getClass()));
redisAuthNumberTemplate.opsForValue().set(String.valueOf(key), o, milliSeconds, TimeUnit.MILLISECONDS);
}
// email 인증번호 조회
public boolean hasAuthNumber(String key) {
return Boolean.TRUE.equals(redisAuthNumberTemplate.hasKey(key));
}
인증번호를 10분 동안 유효할 수 있도록 저장했다.
email 인증과 인증번호를 확인하는 컨트롤러는 다음과 같다.
// email 인증
@Operation(summary = "email 인증")
@PostMapping("/mail")
public ResponseEntity<ApiResponseDto> sendMail(@RequestBody MailRequestDto mailRequestDto) {
ApiResponseDto mailResponseDto = userAuthService.sendMail(mailRequestDto.getEmail());
return new ResponseEntity<>(mailResponseDto, HttpStatus.OK);
}
// email 인증번호 확인
@Operation(summary = "인증번호 확인")
@PostMapping("/mail/confirm")
public ResponseEntity<ApiResponseDto> confirmAuthNumber(@RequestBody AuthNumberRequestDto authNumberRequestDto) {
ApiResponseDto mailResponseDto = userAuthService.confirmAuthNumber(authNumberRequestDto.getAuthNumber());
return new ResponseEntity<>(mailResponseDto, HttpStatus.OK);
}
서비스는 다음과 같다.
// email 인증
private final JavaMailSender javaMailSender;
private static final String senderMail = "TravelShooting";
private static final Long expAuthNumber = 10 * 60 * 1000L; //10분
@Override
@Transactional(timeout = 15)
public ApiResponseDto sendMail(String email) {
int authNumber = (int)(Math.random() * (90000)) + 10000; // (int) Math.random() * (최댓값-최소값+1) + 최소값
// 메일 메세지
MimeMessage message = javaMailSender.createMimeMessage();
try {
message.setFrom(senderMail);
message.setRecipients(MimeMessage.RecipientType.TO, email);
message.setSubject("Travel-Shooting 이메일 인증");
String body = "";
body += "<h3>" + "안녕하세요. Travel-Shooting 입니다." + "</h3>";
body += "<h3>" + "요청하신 인증 번호입니다." + "</h3>";
body += "<h1>" + authNumber + "</h1>";
body += "<h3>" + "위의 인증 번호를 입력해주세요." + "</h3>";
message.setText(body,"UTF-8", "html");
javaMailSender.send(message); //메일을 보낸다.
//redis에 인증번호 저장 (유효기간은 10분)
redisUtil.setAuthNumber(authNumber, "AuthNumber", expAuthNumber);
} catch (MessagingException e) {
e.printStackTrace();
}
return new ApiResponseDto("인증 메일을 보냈습니다. 10분 안에 인증을 완료해주세요.", HttpStatus.OK.value());
}
@Override
public ApiResponseDto confirmAuthNumber(String authNumber) {
if (redisUtil.hasAuthNumber(authNumber)) {
return new ApiResponseDto("인증에 성공했습니다.", HttpStatus.OK.value());
}
return new ApiResponseDto("인증에 실패했습니다. 다시 시도해주세요.", HttpStatus.BAD_REQUEST.value());
}
전체 코드는 다음을 확인!
https://github.com/Travel-Shootings/Travel-Shooting/tree/hakjun
GitHub - Travel-Shootings/Travel-Shooting: 8조 최종프로젝트 Travel-Shooting
8조 최종프로젝트 Travel-Shooting. Contribute to Travel-Shootings/Travel-Shooting development by creating an account on GitHub.
github.com
'TIL&WIL' 카테고리의 다른 글
| DataFrame 속성, 메서드 (0) | 2024.03.06 |
|---|---|
| 2023-09-08 TIL (최종 프로젝트 배포) (0) | 2023.09.08 |
| 2023-09-01 TIL (0) | 2023.09.01 |
| 2023-08-25 TIL (0) | 2023.08.25 |
| 2023-08-23 TIL (0) | 2023.08.23 |