| | 1 | | using AutoMapper; |
| | 2 | | using Despesas.Application.Abstractions; |
| | 3 | | using Despesas.Application.Authentication; |
| | 4 | | using Despesas.Application.Authentication.Abstractions; |
| | 5 | | using Despesas.Application.Dtos; |
| | 6 | | using Despesas.Application.Dtos.Abstractions; |
| | 7 | | using Despesas.Application.Dtos.Core; |
| | 8 | | using Despesas.GlobalException.CustomExceptions.Acesso; |
| | 9 | | using Despesas.GlobalException.CustomExceptions.Core; |
| | 10 | | using Despesas.Infrastructure.Email.Abstractions; |
| | 11 | | using Domain.Entities; |
| | 12 | | using EasyCryptoSalt; |
| | 13 | | using Microsoft.AspNetCore.Http; |
| | 14 | | using Repository.Persistency.Abstractions; |
| | 15 | | using System.IdentityModel.Tokens.Jwt; |
| | 16 | | using System.Security.Claims; |
| | 17 | | using System.Text.RegularExpressions; |
| | 18 | | using static Domain.Core.ValueObject.PerfilUsuario; |
| | 19 | |
|
| | 20 | | namespace Despesas.Application.Implementations; |
| | 21 | |
|
| | 22 | | public class AcessoBusinessImpl<DtoCa, DtoLogin> : IAcessoBusiness<DtoCa, DtoLogin> where DtoCa : AcessoDto where DtoLog |
| | 23 | | { |
| | 24 | | private readonly ICrypto _crypto; |
| | 25 | | private readonly IMapper _mapper; |
| | 26 | | private readonly IAcessoRepositorioImpl _repositorio; |
| | 27 | | private readonly IEmailSender _emailSender; |
| | 28 | | private readonly ISigningConfigurations _singingConfiguration; |
| | 29 | |
|
| | 30 | | private AuthenticationDto AuthenticationException(string message, int statusCode = 400) |
| 0 | 31 | | { |
| 0 | 32 | | throw new CustomException(message, statusCode); |
| | 33 | | } |
| | 34 | |
|
| | 35 | | private Task<AuthenticationDto> AuthenticationSuccess(Acesso acesso) |
| 1 | 36 | | { |
| 1 | 37 | | ClaimsIdentity identity = new ClaimsIdentity(new[] |
| 1 | 38 | | { |
| 1 | 39 | | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), |
| 1 | 40 | | new Claim("role", ((Perfil)acesso.Usuario.PerfilUsuario.Id).ToString()), |
| 1 | 41 | | new Claim(JwtRegisteredClaimNames.Sub, acesso.UsuarioId.ToString()), |
| 1 | 42 | | new Claim(JwtRegisteredClaimNames.AuthTime, acesso.RefreshTokenExpiry == null ? DateTimeOffset.UtcNow.ToUnix |
| 1 | 43 | | new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()), |
| 1 | 44 | | }); |
| | 45 | |
|
| 1 | 46 | | DateTime createDate = DateTime.Now; |
| 1 | 47 | | DateTime expirationDate = createDate + TimeSpan.FromSeconds(_singingConfiguration.TokenConfiguration.Seconds); |
| 1 | 48 | | string token = _singingConfiguration.CreateAccessToken(identity); |
| | 49 | |
|
| 1 | 50 | | var dto = new AuthenticationDto |
| 1 | 51 | | { |
| 1 | 52 | | Authenticated = true, |
| 1 | 53 | | Created = createDate.ToString("yyyy-MM-dd HH:mm:ss"), |
| 1 | 54 | | Expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"), |
| 1 | 55 | | AccessToken = token, |
| 1 | 56 | | RefreshToken = acesso.RefreshToken |
| 1 | 57 | | }; |
| | 58 | |
|
| 1 | 59 | | return Task.FromResult(dto); |
| 1 | 60 | | } |
| | 61 | |
|
| | 62 | | private static void IsValidEmail(string email) |
| 0 | 63 | | { |
| 0 | 64 | | if (string.IsNullOrEmpty(email) || string.IsNullOrWhiteSpace(email)) |
| 0 | 65 | | throw new CampoObrigatorioException("Email não pode ser em branco ou nulo!"); |
| | 66 | |
|
| 0 | 67 | | if (email.Length > 256) |
| 0 | 68 | | throw new EmailInvalidoException(); |
| | 69 | |
|
| 0 | 70 | | string pattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"; |
| 0 | 71 | | Regex regex = new Regex(pattern); |
| | 72 | |
|
| 0 | 73 | | if (!regex.IsMatch(email)) |
| 0 | 74 | | throw new EmailInvalidoException(); |
| 0 | 75 | | } |
| | 76 | |
|
| | 77 | | private void CheckIfUserIsTeste(Guid userIdentity) |
| 1 | 78 | | { |
| 1 | 79 | | var isUserTeste = _repositorio.Find(accout => accout.Login.Contains("teste@teste.com") && accout.UsuarioId == us |
| 1 | 80 | | if (isUserTeste is not null) |
| 0 | 81 | | throw new CampoObrigatorioException("Senha deste usuário não pode ser atualizada"); |
| 1 | 82 | | } |
| | 83 | |
|
| 12 | 84 | | public AcessoBusinessImpl(IMapper mapper, IAcessoRepositorioImpl repositorio, SigningConfigurations singingConfigura |
| 12 | 85 | | { |
| 12 | 86 | | _mapper = mapper; |
| 12 | 87 | | _repositorio = repositorio; |
| 12 | 88 | | _singingConfiguration = singingConfiguration; |
| 12 | 89 | | _emailSender = emailSender; |
| 12 | 90 | | _crypto = crypto; |
| 12 | 91 | | } |
| | 92 | |
|
| | 93 | | public async Task Create(DtoCa acessoDto) |
| 1 | 94 | | { |
| 1 | 95 | | var usuario = _mapper.Map<Usuario>(acessoDto); |
| 1 | 96 | | usuario = new Usuario().CreateUsuario(usuario); |
| 1 | 97 | | Acesso acesso = _mapper.Map<Acesso>(acessoDto); |
| 1 | 98 | | acesso.CreateAccount(usuario, _crypto.Encrypt(acessoDto.Senha)); |
| 1 | 99 | | await _repositorio.Create(acesso); |
| 1 | 100 | | } |
| | 101 | |
|
| | 102 | | public async Task<AuthenticationDto> ValidateCredentials(DtoLogin loginDto) |
| 4 | 103 | | { |
| 4 | 104 | | Acesso baseLogin = await _repositorio.Find(c => c.Login.Equals(loginDto.Email)) |
| 4 | 105 | | ?? throw new UsuarioInexistenteException(); |
| | 106 | |
|
| 1 | 107 | | if (baseLogin?.Usuario?.StatusUsuario == StatusUsuario.Inativo) |
| 1 | 108 | | throw new UsuarioInativoException(); |
| | 109 | |
|
| 0 | 110 | | if (!_crypto.Verify(loginDto?.Senha ?? "", baseLogin?.Senha ?? "")) |
| 0 | 111 | | throw new SenhaInvalidaException(); |
| | 112 | |
|
| 0 | 113 | | bool credentialsValid = baseLogin is not null && loginDto?.Email == baseLogin.Login; |
| 0 | 114 | | if (credentialsValid) |
| 0 | 115 | | { |
| 0 | 116 | | baseLogin.RefreshToken = _singingConfiguration.GenerateRefreshToken(); |
| 0 | 117 | | baseLogin.RefreshTokenExpiry = DateTime.UtcNow.AddDays(_singingConfiguration.TokenConfiguration.DaysToExpiry |
| 0 | 118 | | await _repositorio.RefreshTokenInfo(baseLogin); |
| 0 | 119 | | return await AuthenticationSuccess(baseLogin); |
| | 120 | | } |
| | 121 | |
|
| 0 | 122 | | throw new CustomException("Usuário Inválido!", StatusCodes.Status401Unauthorized); |
| 0 | 123 | | } |
| | 124 | |
|
| | 125 | | public async Task<AuthenticationDto> ValidateExternalCredentials(GoogleAuthenticationDto authenticationDto) |
| 0 | 126 | | { |
| 0 | 127 | | Acesso? baseLogin = await _repositorio.Find(c => (c.ExternalProvider == authenticationDto.ExternalProvider |
| 0 | 128 | | && c.ExternalId == authenticationDto.ExternalId) |
| 0 | 129 | | && c.Login.Equals(authenticationDto.Email)); |
| | 130 | |
|
| 0 | 131 | | if (baseLogin == null && !string.IsNullOrEmpty(authenticationDto.ExternalProvider)) |
| 0 | 132 | | { |
| 0 | 133 | | var dtoCa = this._mapper.Map<DtoCa>(authenticationDto); |
| 0 | 134 | | dtoCa.Senha = Guid.NewGuid().ToString("N"); |
| 0 | 135 | | await Create(dtoCa); |
| | 136 | |
|
| 0 | 137 | | baseLogin = await _repositorio.Find(c => c.Login.Equals(dtoCa.Email)); |
| 0 | 138 | | } |
| | 139 | |
|
| 0 | 140 | | bool credentialsValid = baseLogin is not null && authenticationDto.Email == baseLogin.Login; |
| 0 | 141 | | if (credentialsValid && baseLogin is not null) |
| 0 | 142 | | { |
| 0 | 143 | | baseLogin.RefreshToken = _singingConfiguration.GenerateRefreshToken(); |
| 0 | 144 | | baseLogin.RefreshTokenExpiry = DateTime.UtcNow.AddDays(_singingConfiguration.TokenConfiguration.DaysToExpiry |
| 0 | 145 | | await _repositorio.RefreshTokenInfo(baseLogin); |
| 0 | 146 | | return await AuthenticationSuccess(baseLogin); |
| | 147 | | } |
| 0 | 148 | | return AuthenticationException("Usuário Inválido!"); |
| 0 | 149 | | } |
| | 150 | |
|
| | 151 | | public async Task<AuthenticationDto> ValidateCredentials(string refreshToken) |
| 4 | 152 | | { |
| 4 | 153 | | var baseLogin = await _repositorio.FindByRefreshToken(refreshToken); |
| | 154 | |
|
| 4 | 155 | | var credentialsValid = baseLogin is not null && |
| 4 | 156 | | baseLogin.RefreshTokenExpiry >= DateTime.UtcNow && |
| 4 | 157 | | refreshToken.Equals(baseLogin.RefreshToken) && |
| 4 | 158 | | _singingConfiguration.ValidateRefreshToken(refreshToken); |
| | 159 | |
|
| 4 | 160 | | if (credentialsValid) |
| 1 | 161 | | return await AuthenticationSuccess(baseLogin); |
| 3 | 162 | | else if (baseLogin is not null) |
| 2 | 163 | | await RevokeToken(baseLogin.Id); |
| | 164 | |
|
| 3 | 165 | | throw new RefreshTokenInvalidoException(); |
| 1 | 166 | | } |
| | 167 | |
|
| | 168 | | public Task RevokeToken(Guid idUsuario) |
| 2 | 169 | | { |
| 2 | 170 | | return _repositorio.RevokeRefreshToken(idUsuario); |
| 2 | 171 | | } |
| | 172 | |
|
| | 173 | | public async Task RecoveryPassword(string email) |
| 0 | 174 | | { |
| 0 | 175 | | IsValidEmail(email); |
| | 176 | |
|
| 0 | 177 | | var acesso = await _repositorio.Find(account => account.Login.Equals(email)) |
| 0 | 178 | | ?? throw new UsuarioInexistenteException(); |
| 0 | 179 | | CheckIfUserIsTeste(acesso.Id); |
| | 180 | |
|
| 0 | 181 | | string newPassword = Guid.NewGuid().ToString("N").Substring(0, 8); |
| | 182 | | try |
| 0 | 183 | | { |
| 0 | 184 | | await _repositorio.RecoveryPassword(email, newPassword); |
| 0 | 185 | | _emailSender.SendEmailPassword(acesso.Usuario, newPassword); |
| 0 | 186 | | } |
| 0 | 187 | | catch |
| 0 | 188 | | { |
| 0 | 189 | | throw new EmailException(); |
| | 190 | | } |
| 0 | 191 | | } |
| | 192 | |
|
| | 193 | | public async Task ChangePassword(Guid idUsuario, string password) |
| 1 | 194 | | { |
| 1 | 195 | | CheckIfUserIsTeste(idUsuario); |
| 1 | 196 | | await _repositorio.ChangePassword(idUsuario, _crypto.Encrypt(password)); |
| 1 | 197 | | } |
| | 198 | | } |