Пример #1
0
        public async Task <IActionResult> GetLogin([FromBody] Login logins)
        {
            if (logins == null)
            {
                return(StatusCode(400, new GenericError
                {
                    Code = "400",
                    Message = "Login incorrecto"
                }));
            }

            if (logins.Nombre == null || logins.Apellido == null || logins.Password == null)
            {
                return(StatusCode(400, new GenericError
                {
                    Code = "400",
                    Message = "Login incorrecto"
                }));
            }

            UsuariosOutputViewModel ModelReturn = new UsuariosOutputViewModel();
            UsuariosFilter          Filter      = new UsuariosFilter()
            {
                Nombre = logins.Nombre, Apellido = logins.Apellido, Password = logins.Password
            };
            QueryParameter Parameter = new QueryParameter()
            {
                AllowPaging = false
            };

            System.Threading.CancellationToken Ct = new System.Threading.CancellationToken();
            ModelReturn = _UsersManager.GetAllAsync(Parameter, Filter, Ct).Result.Item1.FirstOrDefault();

            if (ModelReturn == null)
            {
                return(StatusCode(400, new GenericError
                {
                    Code = "400",
                    Message = "Login incorrecto"
                }));
            }


            if (ModelReturn.Nombre == null)
            {
                return(StatusCode(400, new GenericError
                {
                    Code = "400",
                    Message = "Login incorrecto"
                }));
            }


            var TokenH          = new JwtSecurityTokenHandler();
            var Key             = _Configuration["key"]; //var Key = Encoding.ASCII.GetBytes(_Configuration.GetValue<string>("AppSecret"));
            var key             = Encoding.ASCII.GetBytes(Key);
            var TokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, ModelReturn.Nombre),
                    new Claim(ClaimTypes.Email, logins.Apellido),
                    new Claim("UserID", ModelReturn.IdUser.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
            };
            //ModelReturn.ExpiresIn = (60 * 60) * 24;
            var Token = TokenH.CreateToken(TokenDescriptor);

            ModelReturn.Token = TokenH.WriteToken(Token);
            return(new ObjectResult(ModelReturn));
        }
Пример #2
0
        public async Task <JsonResult> Login(Login model)
        {
            BaseResponse response = new BaseResponse();

            UsuariosOutputViewModel Usuario = new UsuariosOutputViewModel();
            CancellationToken       ct      = default(CancellationToken);
            var responseBody = String.Empty;

            try
            {
                using (var Client = new HttpClient())
                {
                    string UriAddres = _Configuration["URLServicio"];
                    Client.BaseAddress = new Uri(UriAddres);
                    //Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Ikp1YW4gTWFudWVsIEFsdmFyYWRvIFJvc2FzIiwiZW1haWwiOiJqdWFuYWx2YXJhZG9ybUBnbWFpbC5jb20iLCJVc2VySUQiOiIxIiwibmJmIjoxNTkxODE2NTg0LCJleHAiOjE1OTE5MDI5ODMsImlhdCI6MTU5MTgxNjU4NH0.zRDaNAd7hM9z15n8HX1kQkKx4FsZxbp6RD4jKlJCgDfodZcU80dwobOxqi5PO21Jg2eiASCAlZ89PjIsxhZ0qw");
                    HttpContent Content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
                    Task <HttpResponseMessage> response1 = Client.PostAsync(new Uri(UriAddres + "api/Security/logins"), Content);
                    response1.Result.EnsureSuccessStatusCode();
                    responseBody = await response1.Result.Content.ReadAsStringAsync();

                    Usuario = JsonConvert.DeserializeObject <UsuariosOutputViewModel>(responseBody);
                }
                HttpContext.Session.SetString("Usuario", Usuario.Nombre + " " + Usuario.Apellido);
                HttpContext.Session.SetString("Token", Usuario.Token);
                response.Sucess = true;
                //Session["UsuarioId"] = userLogin.idusuario;
                response.Redirect = Url.Action("Index", "Home");
            }
            catch (Exception Ex)
            {
                List <ErrorDto> errorDtos = new List <ErrorDto>();
                errorDtos.Add(new ErrorDto {
                    Code = "400", Message = "Usuario o password incorrecto"
                });
                response.Sucess    = false;
                response.ErrorList = errorDtos;
            }

            //var response = new Models.BaseResponse() { Sucess = true, ErrorList = new List<PpcProyect.Entities.ErrorDto>() };
            ////RoleManager

            //ProcessorAccount processor = new ProcessorAccount();

            //var login = processor.LoginUser(model.Email.Trim().ToLower(), model.Password.Trim().ToLower());
            //if (login.Failure)
            //{
            //    response.Sucess = false;
            //    response.ErrorList.AddRange(login.ErrorListService);
            //}
            //else
            //{
            //    Entities.Catalogs.Login userLogin = new Entities.Catalogs.Login();

            //    userLogin = await GetCompleteUserList(model.Email.Trim().ToLower(), model.Password.Trim().ToLower());


            //    if (userLogin.idusuario != null)
            //    {
            //        Session["UsuarioId"] = userLogin.idusuario;
            //        Session["EmpresaId"] = (userLogin.idempresa == 1) ? 0 : userLogin.idempresa;
            //        Session["PreRegistroId"] = userLogin.idprereg;
            //        Session["Correo"] = userLogin.email;
            //        Session["Usuario"] = userLogin.usuarioNombre;

            //        Session["ClientId"] = CheckClientId(userLogin.idusuario.ToString());
            //        Session["idprov"] = CheckProvedorId(userLogin.idusuario.ToString());
            //        if (Convert.ToInt16(Session["idprov"].ToString()) > 0)
            //        {
            //            Session["ProviderName"] = GetProveedores(Session["idprov"].ToString()).Result.nombrecomercial;
            //        }
            //    }
            //    else
            //    {

            //        if (login.Result.User.ToUpper() == "ADMIN")
            //        {
            //            Session["Correo"] = model.Email;
            //            Session["EmpresaId"] = 1;
            //            Session["PreRegistroId"] = 1;
            //        }


            //    }
            //    FormsAuthentication.SetAuthCookie(login.Result.User.ToUpper(), false);
            //    //FormsAuthenticationUser

            //    //FormsAuthentication
            //    Session["userLogin"] = login.Result;
            //    response.Redirect = Url.Action("Index", "Home");
            //}

            return(Json(new
            {
                response = response
            }));
        }