Skip to content

Commit

Permalink
[COZY-440] fix: 사용자 탈퇴시 탈퇴사유 요청받아서 메일 보내기 (#213)
Browse files Browse the repository at this point in the history
* [COZY-440] feat : 관리자에게 메일 보내는 기능 추가

* [COZY-440] feat : 탈퇴 Request dto 생성

* [COZY-440] feat : 관리자 토큰 발급시 https 추가 cors 해결

* [COZY-440] fix : 탈퇴 시 탈퇴사유 메일 보내는 로직 추가

* [COZY-440] fix : 메일 주소 변경
  • Loading branch information
genius00hwan authored Dec 6, 2024
1 parent 8225f14 commit 92acacf
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.cozymate.cozymate_server.global.response.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -20,6 +21,7 @@
@RestController
@RequiredArgsConstructor
@RequestMapping("/members/mail")
@Slf4j
public class MailController {

private final MailService mailService;
Expand Down Expand Up @@ -62,4 +64,14 @@ public ResponseEntity<ApiResponse<String>> isVerified(
ApiResponse.onSuccess(mailService.isVerified(memberDetails.member())));
}

@PostMapping("/test")
@Operation(summary = "[말즈] 관리자 메일 테스트", description = "관리자에게 메일 보내기 테스트")
@Deprecated
public ResponseEntity<ApiResponse<Boolean>> testMail(
) {
log.info("controller 진입 성공");
mailService.sendCustomMailToAdmin("제목", "내용");
return ResponseEntity.ok(ApiResponse.onSuccess(true));
}

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


import com.cozymate.cozymate_server.domain.auth.dto.TokenResponseDTO;
import com.cozymate.cozymate_server.domain.auth.service.AuthService;
import com.cozymate.cozymate_server.domain.auth.userdetails.MemberDetails;
import com.cozymate.cozymate_server.domain.mail.MailAuthentication;
import com.cozymate.cozymate_server.domain.mail.converter.MailConverter;
Expand All @@ -10,7 +11,7 @@
import com.cozymate.cozymate_server.domain.mail.dto.response.VerifyResponseDTO;
import com.cozymate.cozymate_server.domain.mail.repository.MailRepository;
import com.cozymate.cozymate_server.domain.member.Member;
import com.cozymate.cozymate_server.domain.member.service.MemberCommandService;
import com.cozymate.cozymate_server.domain.member.repository.MemberRepository;
import com.cozymate.cozymate_server.domain.university.University;
import com.cozymate.cozymate_server.domain.university.repository.UniversityRepository;
import com.cozymate.cozymate_server.global.response.code.status.ErrorStatus;
Expand All @@ -26,6 +27,7 @@
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
Expand All @@ -40,8 +42,15 @@ public class MailService {
private static final Integer MAIL_AUTHENTICATION_EXPIRED_TIME = 30;
private final JavaMailSender mailSender;
private final MailRepository mailRepository;
private final MemberCommandService memberCommandService;
private final MemberRepository memberRepository;
private final UniversityRepository universityRepository;
private final AuthService authService;

@Value("${spring.mail.username}")
private static final String ADMIN_MAIL_USERNAME = "cozymate0";

private static final String ADMIN_MAIL_DOMAIN = "@gmail.com"; // 관리자 이메일 주소


@Transactional
public void sendUniversityAuthenticationCode(MemberDetails memberDetails,
Expand All @@ -61,26 +70,41 @@ public void sendUniversityAuthenticationCode(MemberDetails memberDetails,
@Transactional
public VerifyResponseDTO verifyMemberUniversity(MemberDetails memberDetails,
VerifyRequestDTO verifyDTO) {
Member member = memberDetails.member();
University memberUniversity = universityRepository.findById(verifyDTO.universityId())
.orElseThrow(() -> new GeneralException(ErrorStatus._UNIVERSITY_NOT_FOUND));

verifyAuthenticationCode(member, verifyDTO.code());
memberDetails.member().verifyMemberUniversity(memberUniversity, verifyDTO.majorName());
memberRepository.save(memberDetails.member());

TokenResponseDTO tokenResponseDTO = memberCommandService.verifyMemberUniversity(
memberDetails,
verifyDTO.universityId(),
verifyDTO.majorName());
TokenResponseDTO tokenResponseDTO = authService.generateMemberTokenDTO(memberDetails);
return MailConverter.toVerifyResponseDTO(tokenResponseDTO);
}

public String isVerified(Member member) {
Optional<MailAuthentication> mailAuthentication = mailRepository.findById(member.getId());

if (mailAuthentication.isPresent() && Boolean.TRUE.equals(mailAuthentication.get().getIsVerified())) {
if (mailAuthentication.isPresent() && Boolean.TRUE.equals(
mailAuthentication.get().getIsVerified())) {
return mailAuthentication.get().getMailAddress();
}
return "";
}

public void sendCustomMailToAdmin(String subject, String content) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

helper.setTo(ADMIN_MAIL_USERNAME + ADMIN_MAIL_DOMAIN);
helper.setSubject(subject);
helper.setText(content, true); // 전달받은 content를 그대로 전송
mailSender.send(message);

} catch (MessagingException e) {
throw new GeneralException(ErrorStatus._MAIL_SEND_FAIL);
}
}

private void verifyAuthenticationCode(Member member, String requestCode) {

MailAuthentication mailAuthentication = mailRepository.findById(member.getId())
Expand All @@ -101,13 +125,14 @@ private void verifyAuthenticationCode(Member member, String requestCode) {
mailAuthentication.verify();
}

private MailAuthentication createAndSendMail(Long memberId, String mailAddress, String universityName) {
private MailAuthentication createAndSendMail(Long memberId, String mailAddress,
String universityName) {

String authenticationCode = Base64.getEncoder()
.encodeToString(UUID.randomUUID().toString().getBytes())
.substring(0, 6);

String emailBody = makeMailBody(authenticationCode,universityName);
String emailBody = makeMailBody(authenticationCode, universityName);

try {
MimeMessage message = mailSender.createMimeMessage();
Expand All @@ -120,7 +145,7 @@ private MailAuthentication createAndSendMail(Long memberId, String mailAddress,

return MailConverter.toMailAuthenticationWithParams(memberId, mailAddress,
authenticationCode, false);
}catch (MessagingException e){
} catch (MessagingException e) {
throw new GeneralException(ErrorStatus._MAIL_SEND_FAIL);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.cozymate.cozymate_server.domain.auth.userdetails.MemberDetails;
import com.cozymate.cozymate_server.domain.member.dto.request.SignInRequestDTO;
import com.cozymate.cozymate_server.domain.member.dto.request.SignUpRequestDTO;
import com.cozymate.cozymate_server.domain.member.dto.request.WithdrawRequestDTO;
import com.cozymate.cozymate_server.domain.member.dto.response.MemberDetailResponseDTO;
import com.cozymate.cozymate_server.domain.member.dto.response.SignInResponseDTO;
import com.cozymate.cozymate_server.domain.member.service.MemberCommandService;
Expand Down Expand Up @@ -171,8 +172,9 @@ ResponseEntity<ApiResponse<Boolean>> updateMajorName(
@Operation(summary = "[말즈] 회원 탈퇴 API", description = "현재 로그인한 사용자를 탈퇴시킵니다.")
@DeleteMapping("/withdraw")
public ResponseEntity<ApiResponse<String>> withdraw(
@AuthenticationPrincipal MemberDetails memberDetails) {
memberCommandService.withdraw(memberDetails);
@AuthenticationPrincipal MemberDetails memberDetails,
@Valid WithdrawRequestDTO withdrawRequestDTO) {
memberCommandService.withdraw(withdrawRequestDTO,memberDetails);

return ResponseEntity.ok(ApiResponse.onSuccess("회원 탈퇴가 완료되었습니다."));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.cozymate.cozymate_server.domain.member.dto.request;

import org.hibernate.validator.constraints.Length;

public record WithdrawRequestDTO(
@Length(max = 100, message = "탈퇴 사유는 최대 100자")
String withdrawReason
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import com.cozymate.cozymate_server.domain.auth.service.AuthService;
import com.cozymate.cozymate_server.domain.auth.userdetails.MemberDetails;
import com.cozymate.cozymate_server.domain.auth.utils.ClientIdMaker;
import com.cozymate.cozymate_server.domain.mail.service.MailService;
import com.cozymate.cozymate_server.domain.member.Member;
import com.cozymate.cozymate_server.domain.member.converter.MemberConverter;
import com.cozymate.cozymate_server.domain.member.dto.request.SignInRequestDTO;
import com.cozymate.cozymate_server.domain.member.dto.request.SignUpRequestDTO;
import com.cozymate.cozymate_server.domain.member.dto.request.WithdrawRequestDTO;
import com.cozymate.cozymate_server.domain.member.dto.response.MemberDetailResponseDTO;
import com.cozymate.cozymate_server.domain.member.dto.response.SignInResponseDTO;
import com.cozymate.cozymate_server.domain.member.enums.SocialType;
Expand Down Expand Up @@ -36,6 +38,8 @@ public class MemberCommandService {

private final MemberWithdrawService memberWithdrawService;

private final MailService mailService;

/**
* 닉네임 유효성 검사 메서드
*
Expand Down Expand Up @@ -111,17 +115,6 @@ public MemberDetailResponseDTO getMemberDetailInfo(MemberDetails memberDetails)
return MemberConverter.toMemberDetailResponseDTOFromEntity(memberDetails.member());
}

@Transactional
public TokenResponseDTO verifyMemberUniversity(MemberDetails memberDetails, Long universityId,
String majorName) {
University memberUniversity = universityRepository.findById(universityId)
.orElseThrow(() -> new GeneralException(ErrorStatus._UNIVERSITY_NOT_FOUND));

memberDetails.member().verifyMemberUniversity(memberUniversity, majorName);
memberRepository.save(memberDetails.member());

return authService.generateMemberTokenDTO(memberDetails);
}

@Transactional
public void updateNickname(Member member, String nickname) {
Expand Down Expand Up @@ -160,7 +153,11 @@ public void updateMajor(Member member, String majorName) {
*
* @param memberDetails 사용자 세부 정보
*/
public void withdraw(MemberDetails memberDetails) {
public void withdraw(WithdrawRequestDTO withdrawRequestDTO, MemberDetails memberDetails) {
String withdrawReason = withdrawRequestDTO.withdrawReason();
String mailSubject = memberDetails.member().getNickname() + "탈퇴 사유";

mailService.sendCustomMailToAdmin(mailSubject, withdrawReason);
memberWithdrawService.withdraw(memberDetails.member());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
}
Cookie cookie = new Cookie("JWT", jwtUtil.generateAdminToken()); // 쿠키 이름 및 값 설정
cookie.setHttpOnly(true); // 클라이언트 측 스크립트에서 쿠키를 접근하지 못하게 함
cookie.setSecure(true);
cookie.setPath("/"); // 쿠키의 유효 범위 설정
cookie.setMaxAge(3600); // 쿠키의 만료 시간 설정 (예: 1시간)
httpResponse.addCookie(cookie); // 응답에 쿠키 추가
Expand Down

0 comments on commit 92acacf

Please sign in to comment.