|
| 1 | +using System; |
| 2 | +using Kairos.Account.Domain; |
| 3 | +using Kairos.Shared.Contracts; |
| 4 | +using Kairos.Shared.Contracts.Account; |
| 5 | +using MediatR; |
| 6 | +using Microsoft.AspNetCore.Identity; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | + |
| 9 | +namespace Kairos.Account.Business.UseCases; |
| 10 | + |
| 11 | +internal sealed class ConfirmEmailUseCase( |
| 12 | + ILogger<ConfirmEmailUseCase> logger, |
| 13 | + UserManager<Investor> identity |
| 14 | +) : IRequestHandler<ConfirmEmailCommand, Output> |
| 15 | +{ |
| 16 | + public async Task<Output> Handle(ConfirmEmailCommand input, CancellationToken cancellationToken) |
| 17 | + { |
| 18 | + var enrichers = new Dictionary<string, object?> |
| 19 | + { |
| 20 | + ["CorrelationId"] = input.CorrelationId, |
| 21 | + ["AccountId"] = input.AccountId, |
| 22 | + }; |
| 23 | + |
| 24 | + using (logger.BeginScope(enrichers)) |
| 25 | + { |
| 26 | + try |
| 27 | + { |
| 28 | + return await ConfirmEmail(input); |
| 29 | + } |
| 30 | + catch (Exception ex) |
| 31 | + { |
| 32 | + logger.LogError(ex, "An unexpected error occurred"); |
| 33 | + return Output.UnexpectedError([ |
| 34 | + "Algum erro inesperado ocorreu... tente novamente mais tarde.", |
| 35 | + ex.Message]); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + async Task<Output> ConfirmEmail(ConfirmEmailCommand input) |
| 41 | + { |
| 42 | + if (input.AccountId is 0 || string.IsNullOrEmpty(input.ConfirmationToken)) |
| 43 | + { |
| 44 | + return Output.InvalidInput(["A conta e seu token de confirmação devem ser especificados."]); |
| 45 | + } |
| 46 | + |
| 47 | + var account = await identity.FindByIdAsync(input.AccountId.ToString()); |
| 48 | + |
| 49 | + if (account is null) |
| 50 | + { |
| 51 | + logger.LogWarning("Account not found"); |
| 52 | + return Output.PolicyViolation([$"A conta {input.AccountId} não existe."]); |
| 53 | + } |
| 54 | + |
| 55 | + var confirmationResult = await identity.ConfirmEmailAsync( |
| 56 | + account, |
| 57 | + input.ConfirmationToken); |
| 58 | + |
| 59 | + if (confirmationResult.Succeeded is false) |
| 60 | + { |
| 61 | + var errors = confirmationResult.Errors |
| 62 | + .Select(e => e.Description) |
| 63 | + .ToList(); |
| 64 | + |
| 65 | + logger.LogWarning("E-mail confirmation failed. Errors: {@Errors}", errors); |
| 66 | + return Output.PolicyViolation(errors); |
| 67 | + } |
| 68 | + |
| 69 | + return Output.Ok(["E-mail confirmado com sucesso!"]); |
| 70 | + } |
| 71 | +} |
0 commit comments