Skip to content

Commit

Permalink
#2 #43 - Refactor: EmailSenderService 로 클래스명 변경, 서비스단에서 메일 전송 호출하도록 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
ahah525 committed Nov 29, 2022
1 parent 6d323a8 commit a3e1882
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 77 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.example.mutbooks.app.mail.service;

import lombok.RequiredArgsConstructor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class EmailSenderService {
private final JavaMailSender javaMailSender;

/**
* 메일 발송
* @param to 수신자(email)
* @param subject 메일 제목
* @param text 메일 내용
*/
@Async
public void send(String to, String subject, String text) {
// 단순 텍스트 구성 메일 메시지 생성
SimpleMailMessage message = new SimpleMailMessage();
// message.setFrom(""); from 값을 설정하지 않으면 application-base-addi.yml 의 spring.mail.username 값이 설정된다.
message.setTo(to);
message.setSubject(subject);
message.setText(text);

javaMailSender.send(message); // 메일 발송
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package com.example.mutbooks.app.member.controller;

import com.example.mutbooks.app.security.dto.MemberContext;
import com.example.mutbooks.app.mail.service.MailService;
import com.example.mutbooks.app.member.entity.Member;
import com.example.mutbooks.app.member.form.JoinForm;
import com.example.mutbooks.app.member.form.WithdrawAccountForm;
import com.example.mutbooks.app.member.form.ModifyForm;
import com.example.mutbooks.app.member.form.PwdModifyForm;
import com.example.mutbooks.app.member.form.WithdrawAccountForm;
import com.example.mutbooks.app.member.service.MemberService;
import com.example.mutbooks.app.member.validator.PwdModifyFormValidator;
import com.example.mutbooks.app.security.dto.MemberContext;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
Expand All @@ -28,7 +27,6 @@
@RequestMapping("/member")
public class MemberController {
private final MemberService memberService;
private final MailService mailService;
private final PwdModifyFormValidator pwdModifyFormValidator;

// 회원가입 폼
Expand Down Expand Up @@ -56,17 +54,13 @@ public String join(@Valid JoinForm joinForm, BindingResult bindingResult, HttpSe
}

Member member = memberService.join(joinForm);
// TODO: 테스트를 위해 잠시 주석 처리
// 가입 축하 이메일 전송
// mailService.sendJoinCongrats(member.getUsername(), member.getEmail());

// 회원가입 완료 후, 자동 로그인 처리
try {
request.login(joinForm.getUsername(), joinForm.getPassword());
} catch (ServletException e) {
throw new RuntimeException(e);
}

return "redirect:/";
}

Expand Down Expand Up @@ -216,4 +210,11 @@ public String registerWithdrawAccount(
// 출금 게좌 관리 페이지로 리다이렉트
return "redirect:/member/manageWithdrawAccount";
}

// 이메일 인증
// @GetMapping("/verifyEmail")
// public String verifyEmail(@RequestParam String email, Model model) {
// memberService.verifyEmail(email);
// return "redirect:/member/login";
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ public class Member extends BaseEntity {
@Column(unique = true)
private String email;

private Boolean emailVerified; // 이메일 인증여부

private String authKey; // 이메일 인증키

@Convert(converter = AuthLevelConverter.class)
private AuthLevel authLevel; // 권한레벨(3 = 일반, 7 = 관리자)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.example.mutbooks.app.cash.entity.CashLog;
import com.example.mutbooks.app.cash.service.CashService;
import com.example.mutbooks.app.mail.service.MailService;
import com.example.mutbooks.app.mail.service.EmailSenderService;
import com.example.mutbooks.app.member.entity.AuthLevel;
import com.example.mutbooks.app.member.entity.Member;
import com.example.mutbooks.app.member.entity.MemberExtra;
Expand All @@ -14,6 +14,7 @@
import com.example.mutbooks.app.member.repository.MemberRepository;
import com.example.mutbooks.app.security.dto.MemberContext;
import com.example.mutbooks.app.security.jwt.JwtProvider;
import com.example.mutbooks.util.Ut;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
Expand All @@ -24,15 +25,14 @@
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class MemberService {
private final MemberRepository memberRepository;
private final PasswordEncoder passwordEncoder;
private final MailService mailService;
private final EmailSenderService emailSenderService;
private final CashService cashService;
private final JwtProvider jwtProvider;

Expand All @@ -43,17 +43,28 @@ public Member join(JoinForm joinForm) {
if(joinForm.getUsername().equals("admin")) {
authLevel = AuthLevel.ADMIN;
}

String authKey = Ut.genEmailAuthKey(); // 이메일 인증키 생성
// 기본 권한 = 일반
Member member = Member.builder()
.username(joinForm.getUsername())
.password(passwordEncoder.encode(joinForm.getPassword()))
.email(joinForm.getEmail())
.emailVerified(false)
.authKey(authKey)
.nickname(joinForm.getNickname())
.authLevel(authLevel)
.build();

memberRepository.save(member);
// TODO: 테스트를 위해 잠시 주석 처리
// 가입 축하 이메일 전송
String subject = "[MUTBooks] %s 회원님 환영합니다.".formatted(member.getUsername());
String text = """
%s 님의 MUTBooks 가입을 축하합니다.
아래 '메일 인증' 버튼을 클릭하여 회원가입을 완료해주세요.
<a href='http://localhost:8010/member/verifyEmail?email=%s&key=%s' target='_blank'>메일 인증</a>
""".formatted(member.getUsername(), member.getEmail(), authKey);
emailSenderService.send(member.getEmail(), subject, text);

return member;
}
Expand Down Expand Up @@ -98,11 +109,14 @@ public Member findByUsernameAndEmail(String username, String email) {
Member member = memberRepository.findByUsernameAndEmail(username, email).orElse(null);
// 임시 비번 발급 후, 비밀번호 업데이트
if(member != null) {
// 1. 임시 비밀번호 생성(UUID이용)
String tempPwd= UUID.randomUUID().toString().replace("-", "");//-를 제거
tempPwd = tempPwd.substring(0,10); //tempPwd를 앞에서부터 10자리 잘라줌
// 1. 임시 비밀번호 생성
String tempPwd = Ut.genTempPassword();
String subject = "[MUTBooks] 회원님의 임시 비밀번호입니다.";
String text = """
%S 님의 임시 비밀번호는 %s 입니다.
""".formatted(username, tempPwd);
// 2. 메일 전송
mailService.sendTempPassword(username, email, tempPwd);
emailSenderService.send(email, subject, text);
// 3. 회원 비밀번호 -> 임시 비밀번호로 변경
modifyPassword(member, tempPwd);
}
Expand Down Expand Up @@ -182,4 +196,11 @@ public String genAccessToken(Member member) {
public boolean verifyWithWhiteList(Member member, String token) {
return member.getAccessToken().equals(token);
}

// 이메일 인증
@Transactional
public void verifyEmail(String email) {
Member member = memberRepository.findByEmail(email).orElse(null);
member.setEmailVerified(true);
}
}
20 changes: 20 additions & 0 deletions mutbooks/src/main/java/com/example/mutbooks/util/Ut.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

public class Ut {
private static final int TEMP_PASSWORD_LENGTH = 10;
private static final int EMAIL_AUTHKEY_LENGTH = 20;

// jwt 관련
private static ObjectMapper getObjectMapper() {
return (ObjectMapper) AppConfig.getContext().getBean("objectMapper");
Expand Down Expand Up @@ -132,4 +136,20 @@ public static String format(LocalDateTime datetime) {
return format("yyyy-MM-dd HH:mm:ss.SSSSSS", datetime);
}
}

// 랜덤 문자열 생성
public static String genRandomUUID(int length) {
return UUID.randomUUID().toString()
.replace("-", "").substring(0, length);
}

// 임시 비밀번호 발급
public static String genTempPassword() {
return genRandomUUID(TEMP_PASSWORD_LENGTH);
}

// 이메일 인증키 발급
public static String genEmailAuthKey() {
return genRandomUUID(EMAIL_AUTHKEY_LENGTH);
}
}

0 comments on commit a3e1882

Please sign in to comment.