|
| 1 | +using System.IdentityModel.Tokens.Jwt; |
| 2 | +using System.Security.Claims; |
| 3 | +using System.Text; |
| 4 | +using Kairos.Account.Configuration; |
| 5 | +using Kairos.Account.Domain; |
| 6 | +using Kairos.Account.Infra; |
| 7 | +using Kairos.Shared.Contracts; |
| 8 | +using Kairos.Shared.Contracts.Account.AccessAccount; |
| 9 | +using MediatR; |
| 10 | +using Microsoft.AspNetCore.Identity; |
| 11 | +using Microsoft.EntityFrameworkCore; |
| 12 | +using Microsoft.Extensions.Logging; |
| 13 | +using Microsoft.Extensions.Options; |
| 14 | +using Microsoft.IdentityModel.Tokens; |
| 15 | + |
| 16 | +namespace Kairos.Account.Business.UseCases; |
| 17 | + |
| 18 | +internal sealed class AccessAccountUseCase( |
| 19 | + IOptions<Settings> config, |
| 20 | + ILogger<AccessAccountUseCase> logger, |
| 21 | + SignInManager<Investor> identity, |
| 22 | + AccountContext db |
| 23 | +) : IRequestHandler<AccessAccountCommand, Output<string>> |
| 24 | +{ |
| 25 | + readonly JwtOptions _settings = config.Value.Jwt; |
| 26 | + |
| 27 | + public async Task<Output<string>> Handle( |
| 28 | + AccessAccountCommand input, |
| 29 | + CancellationToken cancellationToken) |
| 30 | + { |
| 31 | + var enrichers = new Dictionary<string, object?> |
| 32 | + { |
| 33 | + ["Identifier"] = input.Identifier.Value, |
| 34 | + ["CorrelationId"] = input.CorrelationId |
| 35 | + }; |
| 36 | + |
| 37 | + using (logger.BeginScope(enrichers)) |
| 38 | + { |
| 39 | + try |
| 40 | + { |
| 41 | + var id = input.Identifier; |
| 42 | + |
| 43 | + var account = await db.Investors.FirstOrDefaultAsync( |
| 44 | + i => |
| 45 | + (id.Type == AccountIdentifier.Document && i.Document == id.Value) || |
| 46 | + (id.Type == AccountIdentifier.Email && i.Email == id.Value) || |
| 47 | + (id.Type == AccountIdentifier.PhoneNumber && i.PhoneNumber == id.Value) || |
| 48 | + (id.Type == AccountIdentifier.AccountNumber && i.Id.ToString() == id.Value), |
| 49 | + cancellationToken); |
| 50 | + |
| 51 | + if (account is null) |
| 52 | + { |
| 53 | + logger.LogWarning("Sign-in failed. Account not found."); |
| 54 | + return Output<string>.PolicyViolation(["Identificador ou senha inválidos."]); |
| 55 | + } |
| 56 | + |
| 57 | + var result = await identity.CheckPasswordSignInAsync( |
| 58 | + account, |
| 59 | + input.Password, |
| 60 | + lockoutOnFailure: true); |
| 61 | + |
| 62 | + if (result.IsLockedOut) |
| 63 | + { |
| 64 | + logger.LogWarning("Sign-in failed. Account is locked out."); |
| 65 | + return Output<string>.PolicyViolation(["Esta conta está bloqueada. Tente novamente após 5 minutos."]); |
| 66 | + } |
| 67 | + |
| 68 | + if (result.IsNotAllowed) |
| 69 | + { |
| 70 | + logger.LogWarning("Sign-in failed. Email not confirmed."); |
| 71 | + return Output<string>.PolicyViolation(["Confirme seu e-mail antes de acessar a conta."]); |
| 72 | + } |
| 73 | + |
| 74 | + if (result.Succeeded is false) |
| 75 | + { |
| 76 | + logger.LogWarning("Sign-in failed. Invalid password."); |
| 77 | + return Output<string>.PolicyViolation(["Identificador ou senha inválidos."]); |
| 78 | + } |
| 79 | + |
| 80 | + logger.LogInformation("Sign-in successful. Generating token."); |
| 81 | + |
| 82 | + var token = GenerateJwtToken(account); |
| 83 | + |
| 84 | + return Output<string>.Ok(token, ["Autenticação realizada com sucesso!"]); |
| 85 | + } |
| 86 | + catch (Exception ex) |
| 87 | + { |
| 88 | + logger.LogError(ex, "An unexpected error occurred during sign-in."); |
| 89 | + return Output<string>.UnexpectedError([ex.Message]); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + string GenerateJwtToken(Investor account) |
| 95 | + { |
| 96 | + var tokenHandler = new JwtSecurityTokenHandler(); |
| 97 | + var key = Encoding.ASCII.GetBytes(_settings.Secret); |
| 98 | + |
| 99 | + var claims = new List<Claim> |
| 100 | + { |
| 101 | + new(JwtRegisteredClaimNames.Sub, account.Id.ToString()), |
| 102 | + new(JwtRegisteredClaimNames.Email, account.Email!), |
| 103 | + new(JwtRegisteredClaimNames.Name, account.Name), |
| 104 | + new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) |
| 105 | + }; |
| 106 | + |
| 107 | + var tokenDescriptor = new SecurityTokenDescriptor |
| 108 | + { |
| 109 | + Subject = new ClaimsIdentity(claims), |
| 110 | + Expires = DateTime.UtcNow.AddMinutes(_settings.ExpiryMinutes), |
| 111 | + Issuer = _settings.Issuer, |
| 112 | + Audience = _settings.Audience, |
| 113 | + SigningCredentials = new SigningCredentials( |
| 114 | + new SymmetricSecurityKey(key), |
| 115 | + SecurityAlgorithms.HmacSha256Signature) |
| 116 | + }; |
| 117 | + |
| 118 | + var token = tokenHandler.CreateToken(tokenDescriptor); |
| 119 | + |
| 120 | + return tokenHandler.WriteToken(token); |
| 121 | + } |
| 122 | +} |
0 commit comments