-
Notifications
You must be signed in to change notification settings - Fork 2
[BE] 이메일 전송 및 인증로직 추가 #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
The head ref may contain hidden characters: "SISC1-20251104-\uC774\uBA54\uC77C\uC778\uC99D\uAE30\uB2A5\uCD94\uAC00"
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
backend/src/main/java/org/sejongisc/backend/auth/config/EmailProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package org.sejongisc.backend.auth.config; | ||
|
|
||
| import java.time.Duration; | ||
| import lombok.Getter; | ||
| import lombok.Setter; | ||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| @ConfigurationProperties(prefix = "email") | ||
| @Getter | ||
| @Setter | ||
| @Configuration | ||
| public class EmailProperties { | ||
| private Duration codeExpire; | ||
| private Duration verifiedExpire; | ||
| private KeyPrefix keyPrefix; | ||
| private Code code; | ||
|
|
||
| @Setter | ||
| @Getter | ||
| public static class KeyPrefix { | ||
| private String verify; | ||
| private String verified; | ||
| } | ||
|
|
||
| @Setter | ||
| @Getter | ||
| public static class Code { | ||
| private String charset; // 문자 세트 | ||
| private int length; // 기본 길이 | ||
| } | ||
|
|
||
| } |
74 changes: 74 additions & 0 deletions
74
backend/src/main/java/org/sejongisc/backend/auth/controller/EmailController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| package org.sejongisc.backend.auth.controller; | ||
|
|
||
|
|
||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.sejongisc.backend.auth.service.EmailService; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RequestParam; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| @Tag( | ||
| name = "메일 API", | ||
| description = "메일 관련 API 제공" | ||
| ) | ||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/api/email") | ||
| public class EmailController { | ||
| private final EmailService emailService; | ||
|
|
||
| @Operation( | ||
| summary = "메일전송", | ||
| description = """ | ||
| ## 인증(JWT): **불필요** | ||
|
|
||
| ## 요청 파라미터 (String) | ||
| - **`email`**: 회원 이메일 | ||
|
|
||
| ## 반환값 (ResponseEntity<String>) | ||
| - **`message`**: 전송완료 메세지 | ||
|
|
||
| ## 에러코드 | ||
| - **`EMAIL_INVALID_EMAIL`**: 유효하지 않은 이메일입니다 | ||
| - **`DUPLICATE_EMAIL`**: 이미 존재하는 이메일입니다 | ||
| - **`EMAIL_ALREADY_VERIFIED`**: 24시간 내에 인증된 이메일입니다 | ||
| """ | ||
| ) | ||
| @PostMapping("/send") | ||
| public ResponseEntity<String> sendEmail(@RequestParam String email) { | ||
| emailService.sendEmail(email); | ||
| return ResponseEntity.ok("메일 전송을 요청하였습니다."); | ||
| } | ||
|
|
||
|
|
||
| @Operation( | ||
| summary = "이메일 인증", | ||
| description = """ | ||
| ## 인증(JWT): **불필요** | ||
|
|
||
| ## 요청 파라미터 (String) | ||
| - **`email`**: 회원 이메일 | ||
| - **`code`**: 이메일 인증 코드 | ||
|
|
||
| ## 반환값 (ResponseEntity<String>) | ||
| - **`message`**: 인증 완료 메시지 | ||
|
|
||
| ## 에러코드 | ||
| - **`EMAIL_CODE_MISMATCH`**: 이메일 인증 코드가 일치하지 않습니다 | ||
| - **`EMAIL_CODE_NOT_FOUND`**: 이메일 인증 코드를 찾을 수 없습니다 | ||
| """ | ||
| ) | ||
| @PostMapping("/verify") | ||
| public ResponseEntity<String> verifyEmail(@RequestParam String email, @RequestParam String code) { | ||
| emailService.verifyEmail(email, code); | ||
| return ResponseEntity.ok("이메일 인증이 완료되었습니다."); | ||
| } | ||
|
|
||
|
|
||
|
|
||
| } |
134 changes: 134 additions & 0 deletions
134
backend/src/main/java/org/sejongisc/backend/auth/service/EmailService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| package org.sejongisc.backend.auth.service; | ||
|
|
||
| import jakarta.mail.Message; | ||
| import jakarta.mail.MessagingException; | ||
| import jakarta.mail.internet.InternetAddress; | ||
| import jakarta.mail.internet.MimeMessage; | ||
| import jakarta.validation.constraints.Email; | ||
| import java.security.SecureRandom; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.apache.commons.validator.routines.EmailValidator; | ||
| import org.sejongisc.backend.auth.config.EmailProperties; | ||
| import org.sejongisc.backend.common.exception.CustomException; | ||
| import org.sejongisc.backend.common.exception.ErrorCode; | ||
| import org.sejongisc.backend.user.dao.UserRepository; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.mail.MailSendException; | ||
| import org.springframework.mail.javamail.JavaMailSender; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.validation.annotation.Validated; | ||
| import org.thymeleaf.context.Context; | ||
| import org.thymeleaf.spring6.SpringTemplateEngine; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Validated | ||
| public class EmailService { | ||
| private final JavaMailSender mailSender; | ||
| private final RedisTemplate<String, String> redisTemplate; | ||
discipline24 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| private final SpringTemplateEngine templateEngine; | ||
| private final UserRepository userRepository; | ||
| private final EmailProperties emailProperties; | ||
|
|
||
| // 메일 발신자 | ||
| @Value("${spring.mail.username}") | ||
discipline24 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| private String from; | ||
|
|
||
| // 메세지 만들기 | ||
| private MimeMessage createMessage(String email, String code) throws MessagingException { | ||
| MimeMessage message = mailSender.createMimeMessage(); | ||
| message.setFrom(new InternetAddress(from)); | ||
| message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); | ||
| message.setSubject("세투연 이메일 인증 메일입니다."); | ||
|
|
||
| Context context = new Context(); | ||
| context.setVariable("email", email); | ||
| context.setVariable("code", code); | ||
|
|
||
| String body = templateEngine.process("mail/verificationEmail", context); | ||
| message.setText(body, "UTF-8", "html"); | ||
|
|
||
| return message; | ||
|
|
||
| } | ||
|
|
||
| // 메일 발송 | ||
| public void sendEmail(@Email String email) { | ||
|
|
||
| // 이미 24시간 내 인증된 이메일인지 확인 | ||
| String verifiedKey = emailProperties.getKeyPrefix().getVerified() + email; | ||
| if (Boolean.TRUE.equals(redisTemplate.hasKey(verifiedKey))) { | ||
| throw new CustomException(ErrorCode.EMAIL_ALREADY_VERIFIED); | ||
| } | ||
|
|
||
| // 이메일 형식 검증 | ||
| if (!EmailValidator.getInstance().isValid(email)) { | ||
| throw new CustomException(ErrorCode.EMAIL_INVALID_EMAIL); | ||
| } | ||
|
|
||
| // 중복 이메일 검증 | ||
| if (userRepository.existsByEmail(email)) { | ||
| throw new CustomException(ErrorCode.DUPLICATE_EMAIL); | ||
| } | ||
|
|
||
| // 인증코드 생성 | ||
| String code = generateCode(); | ||
|
|
||
| // Redis에 인증 코드 저장 (유효시간: 3분) | ||
| redisTemplate.opsForValue().set(emailProperties.getKeyPrefix().getVerify() + email, code, emailProperties.getCodeExpire()); | ||
|
|
||
| // 메일 발송 | ||
| try { | ||
| MimeMessage message = createMessage(email, code); | ||
| mailSender.send(message); | ||
| } catch (MessagingException e) { | ||
| log.error("메일전송이 실패하였습니다", e); | ||
| throw new MailSendException("failed to send mail", e); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| // 코드확인 | ||
| public void verifyEmail(String email, String code) { | ||
| String key = emailProperties.getKeyPrefix().getVerify()+ email; | ||
|
|
||
| String storedCode = redisTemplate.opsForValue().get(key); | ||
| if (storedCode == null) throw new CustomException(ErrorCode.EMAIL_CODE_NOT_FOUND); | ||
| if (!storedCode.equals(code)) throw new CustomException(ErrorCode.EMAIL_CODE_MISMATCH); | ||
daye200 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| // 인증 성공 시 Redis에서 코드 삭제 | ||
| redisTemplate.delete(key); | ||
|
|
||
| // 인증 완료 상태 저장 (24시간 유효) | ||
| redisTemplate.opsForValue().set( | ||
| emailProperties.getKeyPrefix().getVerified() + email, | ||
| "true", | ||
| emailProperties.getVerifiedExpire() | ||
| ); | ||
|
|
||
|
|
||
| } | ||
|
|
||
| // 이메일 인증 코드 생성 | ||
| private String generateCode() { | ||
| String charset = emailProperties.getCode().getCharset(); | ||
| int len = emailProperties.getCode().getLength(); | ||
|
|
||
| SecureRandom rnd = new SecureRandom(); | ||
| StringBuilder sb = new StringBuilder(len); | ||
|
|
||
| for (int i = 0; i < len; i++) { | ||
| sb.append(charset.charAt(rnd.nextInt(charset.length()))); | ||
| } | ||
| return sb.toString(); | ||
| } | ||
|
|
||
|
|
||
|
|
||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.