Exemple #1
0
        public ICommandResult <Notificacao> Handler(LoginUsuarioCommand command)
        {
            try
            {
                string login = command.Login;
                string senha = command.Senha;

                if (!_repository.CheckLogin(login))
                {
                    AddNotificacao("Login", "Login incorreto! Esse login de usuário não existe");
                }

                if (Invalido)
                {
                    return(new CommandResult <Notificacao>("Inconsistência(s) no(s) dado(s)", Notificacoes));
                }

                UsuarioQueryResult usuario = _repository.Logar(login, senha);

                if (usuario != null)
                {
                    return(new CommandResult <Notificacao>("Usuário logado com sucesso!", usuario));
                }
                else
                {
                    AddNotificacao("Senha", "Senha incorreta!");
                    return(new CommandResult <Notificacao>("Inconsistência(s) no(s) dado(s)", Notificacoes));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        public ActionResult <ApiResponse <UsuarioQueryResult, Notificacao> > UsuarioLogin([FromBody] LoginUsuarioCommand command)
        {
            try
            {
                if (Request.Headers["ChaveAPI"].ToString() != _ChaveAPI)
                {
                    return(StatusCode(StatusCodes.Status401Unauthorized, new ApiResponse <object, Notificacao>("Acesso negado", new List <Notificacao>()
                    {
                        new Notificacao("Chave da API", "ChaveAPI não corresponde com a chave esperada")
                    })));
                }

                if (command == null)
                {
                    return(StatusCode(StatusCodes.Status400BadRequest, new ApiResponse <object, Notificacao>("Parâmentros inválidos", new List <Notificacao>()
                    {
                        new Notificacao("Parâmetros de entrada", "Parâmetros de entrada estão nulos")
                    })));
                }

                if (!command.ValidarCommand())
                {
                    return(StatusCode(StatusCodes.Status400BadRequest, new ApiResponse <object, Notificacao>("Parâmentros inválidos", command.Notificacoes)));
                }

                var result = _handler.Handler(command);

                if (result.Sucesso)
                {
                    UsuarioQueryResult usuarioQR = (UsuarioQueryResult)result.Dados;

                    string token = _tokenService.GenerateToken(usuarioQR);

                    UsuarioTokenQueryResult usuarioTokenQR = new UsuarioTokenQueryResult()
                    {
                        Id         = usuarioQR.Id,
                        Login      = usuarioQR.Login,
                        Senha      = usuarioQR.Senha,
                        Privilegio = usuarioQR.Privilegio,
                        Token      = token
                    };

                    return(StatusCode(StatusCodes.Status200OK, new ApiResponse <object, Notificacao>(result.Mensagem, usuarioTokenQR)));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status400BadRequest, new ApiResponse <object, Notificacao>(result.Mensagem, result.Erros)));
                }
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new ApiResponse <object, Notificacao>("Erro", new List <Notificacao>()
                {
                    new Notificacao("Erro", e.Message)
                })));
            }
        }
        public override bool ValidateUser(string username, string password)
        {
            var result = UsuarioQueryResult.ValidarUsuario(username, password);

            if (result != null && result.Resultado == "S")
            {
                return(true);
            }
            return(false);
        }
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            var cacheKey = string.Format("UserData_{0}", username);

            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return((CustomMembershipUser)HttpRuntime.Cache[cacheKey]);
            }


            var resultado = UsuarioQueryResult.ObtenerDataUsuario(username);
            var usuario   = new Usuario(resultado);

            SessionWrapper.Usuario = usuario;
            var membershipUser = new CustomMembershipUser(usuario);

            HttpRuntime.Cache.Insert(cacheKey, membershipUser, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinutes), Cache.NoSlidingExpiration);

            return(membershipUser);
        }
Exemple #5
0
        public string GenerateToken(UsuarioQueryResult usuarioQR)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_ChaveJWT);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, usuarioQR.Login),
                    new Claim(ClaimTypes.Role, "User")
                }),
                Expires            = DateTime.UtcNow.AddHours(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }