Skip to content
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

[COZY-440] fix: 사용자 탈퇴시 탈퇴사유 요청받아서 메일 보내기 #213

Merged
merged 6 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

관리자에게 메일 보내는 test api 하나 만들어서 메일을 보내봤습니다. 테스트 성공후 바로 @Deprecated처리 했습니다.

}
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";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 @value 설정되어있는데, 값이 직접 주입되어있는건 먼가용

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메일고도화하면서 메일 주소 확정 나면 바꾸려구여


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);
}
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

관리자에게 메일 보내는 함수입니다 일단 제 개인메일주소로 메일을 보냅니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

눈꽃 요구로 cozymate0으로 수정했습니다

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
) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

탈퇴시 사용되는 dto입니다. 탈퇴사유는 줄글이라 body로 받습니다.

}
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);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

관리자 토큰 발급할때 Https로 바꿉니다

cookie.setPath("/"); // 쿠키의 유효 범위 설정
cookie.setMaxAge(3600); // 쿠키의 만료 시간 설정 (예: 1시간)
httpResponse.addCookie(cookie); // 응답에 쿠키 추가
Expand Down
Loading