コード例 #1
0
        public IActionResult Login([FromBody] AutenticacaoClienteDTO model)
        {
            _logger.LogDebug("A executar api/cliente/login -> Post");
            if (model is null)
            {
                _logger.LogWarning("O objeto AutenticacaoDTO é null!");
                return(BadRequest(nameof(model)));
            }

            try
            {
                ServiceResult <TokenDTO> resultado = _clienteBusiness.Login(model);
                if (resultado.Sucesso)
                {
                    _logger.LogInformation($"O Cliente com Email {model.Email} efetou login com sucesso.");
                    return(Ok(resultado.Resultado));
                }
                else
                {
                    _logger.LogInformation($"Ocorreu um erro ao efetuar o login com o Email {model.Email}.");
                    return(BadRequest(resultado.Erros));
                }
            }
            catch (ArgumentNullException e)
            {
                _logger.LogError(e, e.Message);
                return(BadRequest(new { message = e.Message }));
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(StatusCode(500));
            }
        }
コード例 #2
0
        public ServiceResult <TokenDTO> Login(AutenticacaoClienteDTO model)
        {
            _logger.LogDebug("A executar [ClienteBusiness -> Login]");
            if (string.IsNullOrWhiteSpace(model.Email))
            {
                throw new ArgumentNullException("Email", "Campo não poder ser nulo!");
            }
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                throw new ArgumentNullException("Password", "Campo não poder ser nulo!");
            }

            IList <int> erros       = new List <int>();
            TokenDTO    resultToken = null;

            if (!_clienteDAO.ExisteEmail(model.Email))
            {
                _logger.LogWarning($"O Email {model.Email} não existe.");
                erros.Add((int)ErrosEnumeration.EmailNaoExiste);
            }
            else
            {
                if (!_clienteDAO.ContaConfirmada(model.Email))
                {
                    _logger.LogDebug($"O Email {model.Email} não se encontra confirmado.");
                    erros.Add((int)ErrosEnumeration.ContaNaoConfirmada);
                }


                Cliente cliente = _clienteDAO.GetContaEmail(model.Email);
                if (!erros.Any())
                {
                    if (cliente.Password.Equals(_hashPasswordService.HashPassword(model.Password)))
                    {
                        var tokenHandler    = new JwtSecurityTokenHandler();
                        var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                                new Claim(ClaimTypes.NameIdentifier, cliente.IdCliente.ToString()),
                                new Claim(ClaimTypes.Role, "Cliente")
                            }),
                            Expires            = DateTime.UtcNow.AddDays(7),
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        resultToken = new TokenDTO {
                            Token = tokenHandler.WriteToken(token)
                        };
                    }
                    else
                    {
                        _logger.LogWarning("A Password está incorreta!");
                        erros.Add((int)ErrosEnumeration.EmailPasswordIncorreta);
                    }
                }
            }

            return(new ServiceResult <TokenDTO> {
                Erros = new ErrosDTO {
                    Erros = erros
                }, Sucesso = !erros.Any(), Resultado = resultToken
            });
        }