Handler.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Application.Abstractions.Messaging.Email;
  4. using Application.Common;
  5. using Domain.Entities.EmailVerification;
  6. using Domain.Entities.EmailVerification.ValueObject;
  7. using SharedKernel.Results;
  8. using Microsoft.EntityFrameworkCore;
  9. namespace Application.Features.Api.MyPage.Withdraw.RequestCode;
  10. internal sealed class Handler(
  11. IAppDbContext db,
  12. IMailService mailService
  13. ) : ICommandHandler<Command, Result>
  14. {
  15. public async Task<Result> Handle(Command request, CancellationToken ct)
  16. {
  17. var member = await db.Member.FirstOrDefaultAsync(m => m.ID == request.MemberID, ct);
  18. if (member is null)
  19. {
  20. return Result.Failure(Error.NotFound("MyPage.MemberNotFound", "회원 정보를 찾을 수 없습니다."));
  21. }
  22. if (member.IsWithdraw)
  23. {
  24. return Result.Failure(Error.Problem("MyPage.AlreadyWithdrawn", "이미 탈퇴한 회원입니다."));
  25. }
  26. if (member.IsDenied)
  27. {
  28. return Result.Failure(Error.Problem("MyPage.MemberDenied", "차단된 회원은 이용할 수 없습니다."));
  29. }
  30. var email = member.Email;
  31. // 기존 미인증 코드 제거
  32. var existing = await db.EmailVerifyNumber.Where(e => e.Email == email && e.Type == VerificationType.Withdraw && !e.IsVerified).ToListAsync(ct);
  33. db.EmailVerifyNumber.RemoveRange(existing);
  34. // 6자리 코드 발급 (10분 만료)
  35. var code = Random.Shared.Next(100000, 999999).ToString();
  36. var verifyNumber = EmailVerifyNumber.Create(
  37. VerificationType.Withdraw,
  38. email,
  39. code,
  40. DateTime.UtcNow.AddMinutes(10)
  41. );
  42. await db.EmailVerifyNumber.AddAsync(verifyNumber, ct);
  43. await db.SaveChangesAsync(ct);
  44. // 이메일 발송 — WithdrawVerify 템플릿 우선, 없으면 hardcoded fallback
  45. var emailTpl = (await db.Config.AsNoTracking().FirstOrDefaultAsync(ct))?.EmailTemplate;
  46. var subject = string.IsNullOrWhiteSpace(emailTpl?.WithdrawVerifyEmailFormTitle)
  47. ? "회원탈퇴 인증번호"
  48. : emailTpl!.WithdrawVerifyEmailFormTitle!;
  49. var content = string.IsNullOrWhiteSpace(emailTpl?.WithdrawVerifyEmailFormContent)
  50. ? $"<p>회원탈퇴 인증번호입니다.</p><p><strong>{code}</strong></p><p>이 코드는 10분간 유효합니다.</p>"
  51. : emailTpl!.WithdrawVerifyEmailFormContent!.Render(("Code", code), ("Email", email));
  52. await mailService.SendAsync(new SendData(email, subject, content), ct);
  53. return Result.Success();
  54. }
  55. }