public bool UpdateUser(UserMin user)
        {
            List <SqlParameter> _Parametros = new List <SqlParameter>();

            try
            {
                _Parametros.Add(new SqlParameter("@Nick", user.Nick));
                _Parametros.Add(new SqlParameter("@Password", user.Password));
                _Parametros.Add(new SqlParameter("@Name", user.FirstName));
                _Parametros.Add(new SqlParameter("@Last", user.Lastname));
                _Parametros.Add(new SqlParameter("@email", user.Email));
                _Parametros.Add(new SqlParameter("@Address", user.Address));
                _Parametros.Add(new SqlParameter("@City", user.City));
                _Parametros.Add(new SqlParameter("@State", user.State));
                _Parametros.Add(new SqlParameter("@Country", user.Country));
                _Parametros.Add(new SqlParameter("@Zip", user.Zip));
                _Parametros.Add(new SqlParameter("@Imagen", user.Imagen));
                _Parametros.Add(new SqlParameter("@Id", user.ID));
                _Parametros.Add(new SqlParameter("@Phone", user.Phone));
                sql.PrepararProcedimiento("dbo.[USER.Update]", _Parametros);
                sql.EjecutarProcedimiento();
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(sqlEx.Message, sqlEx);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
            return(true);
        }
예제 #2
0
        public async Task <Login> Login(string username, string password)
        {
            await Task.Delay(1000);

            UserMin _user = new UserMin()
            {
                Nick     = username,
                Password = Functions.GetSHA256(password).ToUpper()
            };


            WebAPIUrl = "http://189.254.239.133/LoginAppApi/api/login/autenticar";

            //Con esta Api de ejemplo hice la prueba
            //WebAPIUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Set your REST API url here
            var uri = new Uri(WebAPIUrl);

            try
            {
                HttpContent _content = new StringContent(JsonConvert.SerializeObject(_user));
                _content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                var response = await client.PostAsync(uri, _content);

                if (response.IsSuccessStatusCode)
                {
                    Login _login  = new Login();
                    var   content = await response.Content.ReadAsStringAsync();

                    _login = JsonConvert.DeserializeObject <Login>(content);
                    return(_login);
                }
            }
            catch (Exception ex)
            {
            }
            return(null);


            //return new Login()
            //{
            //    ID = 1,
            //    Name = "Ramón",
            //    Password = password,
            //    Nick = username,
            //    Token = "jajajajejejejijijjojojjujuju"
            //};
        }
예제 #3
0
        public IActionResult Login([FromBody] UserMin user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }


            var ConnectionStringLocal = _configuration.GetValue <string>("ServidorLocal");

            using (ILogin Login = Factorizador.CrearConexionServicioLogin(APIUsers.Library.Models.ConnectionType.MSSQL, ConnectionStringLocal))
            {
                //id = User.InsertUser(value.Nick, Functions.GetSHA256(value.Password));
                APIUsers.Library.Models.User objusr = Login.EsblecerLogin(user.Nick, user.Password);
                if (objusr.ID > 0)
                {
                    //if (user.Nick == "rgatilanov" && user.Password == "4297f44b13955235245b2497399d7a93") //MD5 (123123)
                    //{
                    var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetValue <string>("SecretKey")));
                    var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                    var tokeOptions = new JwtSecurityToken(
                        issuer: "http://localhost:44369",
                        audience: "http://localhost:44369",
                        claims: new List <System.Security.Claims.Claim>(),
                        expires: DateTime.Now.AddMinutes(5),
                        signingCredentials: signinCredentials
                        );

                    var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                    return(Ok(new { Token = tokenString }));
                    //}
                }
                else
                {
                    return(Unauthorized());
                }
            }
        }
        public int InsertUser(UserMin user)
        {
            int IdUser = 0;
            List <SqlParameter> _Parametros = new List <SqlParameter>();

            try{
                _Parametros.Add(new SqlParameter("@Nick", user.Nick));
                _Parametros.Add(new SqlParameter("@Password", user.Password));
                _Parametros.Add(new SqlParameter("@Name", user.FirstName));
                _Parametros.Add(new SqlParameter("@Last", user.Lastname));
                _Parametros.Add(new SqlParameter("@email", user.Email));
                _Parametros.Add(new SqlParameter("@Address", user.Address));
                _Parametros.Add(new SqlParameter("@City", user.City));
                _Parametros.Add(new SqlParameter("@State", user.State));
                _Parametros.Add(new SqlParameter("@Country", user.Country));
                _Parametros.Add(new SqlParameter("@Zip", user.Zip));
                _Parametros.Add(new SqlParameter("@Imagen", user.Imagen));
                _Parametros.Add(new SqlParameter("@Role", user.Role));
                _Parametros.Add(new SqlParameter("@Phone", user.Phone));

                SqlParameter valreg = new SqlParameter();
                valreg.ParameterName = "@Id";
                valreg.DbType        = DbType.Int32;
                valreg.Direction     = ParameterDirection.Output;
                _Parametros.Add(valreg);

                sql.PrepararProcedimiento("dbo.[USER.Insert]", _Parametros);
                IdUser = int.Parse(sql.EjecutarProcedimientoOutput().ToString());
                return(IdUser);
            }
            catch (SqlException sqlEx) {
                throw new Exception(sqlEx.Message, sqlEx);
            }
            catch (Exception ex) {
                throw new Exception(ex.Message, ex);
            }
        }
예제 #5
0
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            //  Get API key provider
            var    provider          = new TokenServices();
            var    resourceService   = new ResourceService();
            var    tokenValue        = "";
            var    controllerName    = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var    actionName        = filterContext.ActionDescriptor.ActionName;
            string controllerPackage = GetNameSpace(filterContext);

            try
            {
                try
                {
                    tokenValue = filterContext.Request.Headers.GetValues(Token).FirstOrDefault();
                }
                catch
                {
                    //skip toke property not supplied
                }
                // Validate Token
                var arr = tokenValue.Split(':');
                try
                {
                    var userMin = new UserMin()
                    {
                        UserId = 2, UserType = UserType.Anonymous
                    };
                    if (!string.IsNullOrEmpty(tokenValue))
                    {
                        //authorized user
                        string tokenString = arr[1];
                        long   userId      = Convert.ToInt64(arr[0]);
                        var    user        = provider.ValidateToken(arr[1], userId);
                        if (user == null)
                        {
                            throw new SecurityException("Token validation failed");
                        }
                        userMin = new UserMin()
                        {
                            UserId = user.UserId, UserType = user.UserType
                        };
                    }
                    //validate resource grant
                    resourceService.validateUrlPermission(actionName, controllerName, controllerPackage, userMin.UserId);
                    HttpContext.Current.Items.Add(SiteConstants.SessionKey, userMin);
                }
                catch (ArgumentOutOfRangeException)
                {
                    throw new SecurityException("Invalid Authorization data format");
                }
                catch (FormatException)
                {
                    throw new SecurityException("Invalid Authorization data format");
                }
            }
            catch
            {
                throw;
            }
            base.OnActionExecuting(filterContext);
        }
        /*public Login Authenticate(UserMin usMin)
         * {
         *  // Integración a base de datos
         *  if (usMin.Nick == "rgatilanov" && usMin.Password == "96CAE35CE8A9B0244178BF28E4966C2CE1B8385723A96A6B838858CDD6CA0A1E") //SHA2
         *  {
         *      // Leemos el secret_key desde nuestro appseting
         *      var secretKey = _configuration.GetValue<string>("SecretKey");
         *      var key = Encoding.ASCII.GetBytes(secretKey);
         *      var tokenDescriptor = new SecurityTokenDescriptor
         *      {
         *          // Nuestro token va a durar un día
         *          Expires = DateTime.UtcNow.AddDays(1),
         *          // Credenciales para generar el token usando nuestro secretykey y el algoritmo hash 256
         *          SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
         *      };
         *      var tokenHandler = new JwtSecurityTokenHandler();
         *      var createdToken = tokenHandler.CreateToken(tokenDescriptor);
         *      return new Login()
         *      {
         *          ID = usMin.ID,
         *          Nick = usMin.Nick,
         *          Token = tokenHandler.WriteToken(createdToken),
         *      };
         *  }
         *  else
         *      return null;
         * }*/
        #endregion
        #region Método para integración con Angular
        public IActionResult Login([FromBody] UserMin user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }

            var ConnectionStringLocal = _configuration.GetValue <string>("ServidorLocal");

            //var ConnectionStringLocal = _configuration.GetValue<string>("ConnectionStringLocal");
            APIUsers.Library.Models.User objusr;
            using (APIUsers.Library.Interfaces.ILogin Login = APIUsers.Library.Interfaces.Factorizador.CrearConexionServicioLogin(APIUsers.Library.Models.ConnectionType.MSSQL, ConnectionStringLocal))
            {
                //if (user.Nick == "rgatilanov" && user.Password == "96cae35ce8a9b0244178bf28e4966c2ce1b8385723a96a6b838858cdd6ca0a1e") //sha2 (123123)
                //{
                objusr = Login.EstablecerLogin(user.Nick, user.Password);
            }

            if (objusr.ID > 0)
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetValue <string>("SecretKey")));
                var claims    = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.Nick),
                    new Claim(ClaimTypes.Role, "Admin"),
                    new Claim(ClaimTypes.Role, "Manager")
                };

                // Esta lógica se manda al servicio de tokens
                //var tokeOptions = new JwtSecurityToken(
                //    issuer: "http://localhost:44369",
                //    audience: "http://localhost:44369",
                //    claims: claims,
                //    expires: DateTime.Now.AddMinutes(5),
                //    signingCredentials: signinCredentials
                //);
                //var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                //return Ok(new { Token = tokenString });

                // Para utilizar el key del archivo de configuración sobreescribí el siguiente método para enviarselo desde la API
                //var accessToken = tokenService.GenerateAccessToken(claims);
                var accessToken  = tokenService.GenerateAccessToken(claims, secretKey);
                var refreshToken = tokenService.GenerateRefreshToken();

                user.RefreshToken           = refreshToken;
                user.RefreshTokenExpiryTime = DateTime.Now.AddDays(7);

                using (APIUsers.Library.Interfaces.IUser User = APIUsers.Library.Interfaces.Factorizador.CrearConexionServicio(APIUsers.Library.Models.ConnectionType.MSSQL, ConnectionStringLocal))
                {
                    User.UpdateRefreshTokenNExpiryTime(user);
                }

                return(Ok(new
                {
                    Token = accessToken,
                    RefreshToken = refreshToken
                }));
            }
            else
            {
                return(Unauthorized());
            }
        }