Handler.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Messaging;
  4. using Application.Abstractions.Messaging.Email;
  5. using Application.Common;
  6. using Application.Features.Config.Get;
  7. using Application.Helpers;
  8. using SharedKernel.Results;
  9. using Microsoft.EntityFrameworkCore;
  10. namespace Application.Features.Api.Auth.Registration;
  11. internal sealed class Handler(
  12. IAppDbContext db,
  13. ICacheService cache,
  14. IMailService mailService
  15. ) : ICommandHandler<Command, Result>
  16. {
  17. public async Task<Result> Handle(Command request, CancellationToken ct)
  18. {
  19. // 이메일 유효성 검사
  20. if (string.IsNullOrWhiteSpace(request.Email))
  21. {
  22. return Result.Failure(Error.Problem("Auth.EmailRequired", "이메일은 필수입니다."));
  23. }
  24. var email = request.Email.Trim().ToLower();
  25. // 회원 조회
  26. var member = await db.Member.FirstOrDefaultAsync(m => m.Email == email, ct);
  27. if (member is null)
  28. {
  29. return Result.Failure(Error.NotFound("Auth.MemberNotFound", "등록된 회원 정보를 찾을 수 없습니다."));
  30. }
  31. // Config에서 IsRegisterEmailAuth 설정 조회
  32. var isRegisterEmailAuth = false;
  33. var config = await cache.GetAsync<Response>(CacheKeys.Config, ct);
  34. if (config is not null)
  35. {
  36. isRegisterEmailAuth = config.Account.IsRegisterEmailAuth;
  37. }
  38. else
  39. {
  40. var configEntity = await db.Config.AsNoTracking().OrderByDescending(x => x.ID).FirstOrDefaultAsync(ct);
  41. if (configEntity is not null)
  42. {
  43. isRegisterEmailAuth = configEntity.Account.IsRegisterEmailAuth;
  44. }
  45. }
  46. // 이메일 인증이 필요한 경우 쿠키 확인 및 이메일 인증 처리
  47. if (isRegisterEmailAuth)
  48. {
  49. if (string.IsNullOrWhiteSpace(request.CookieValue) || request.CookieValue != "true")
  50. {
  51. return Result.Failure(Error.Problem("Auth.VerificationRequired", "사전 인증을 먼저 수행하세요."));
  52. }
  53. // 이메일 인증 완료 처리
  54. member.MarkEmailVerified();
  55. await db.SaveChangesAsync(ct);
  56. }
  57. // 가입 완료 환영 이메일 발송
  58. var emailTpl = await AccountConfigLoader.GetEmailTemplateAsync(cache, db, ct);
  59. var subject = string.IsNullOrWhiteSpace(emailTpl.RegistrationEmailFormTitle)
  60. ? "회원가입을 환영합니다"
  61. : emailTpl.RegistrationEmailFormTitle;
  62. var content = string.IsNullOrWhiteSpace(emailTpl.RegistrationEmailFormContent)
  63. ? $"<p>회원가입이 완료되었습니다.</p><p>서비스를 이용해 주셔서 감사합니다.</p>"
  64. : emailTpl.RegistrationEmailFormContent.Render(("Email", email), ("Nickname", member.Name ?? string.Empty), ("CreatedAt", member.CreatedAt.AddHours(9).ToString("yyyy-MM-dd HH:mm")));
  65. await mailService.SendAsync(new SendData(email, subject, content), ct);
  66. return Result.Success();
  67. }
  68. }