protected void Page_Load(object sender, EventArgs e)
        {
            var usuario = Session["UsuarioLogueado"] as Usuario;
            if (usuario.Tipo != UsuarioTipo.WebMaster.ToString())
                Response.Redirect("Login.aspx");
            var logsServices = new LogServices();
             _log = logsServices.Get();
            var hashServices = new HashService();
            foreach (var log in _log)
            {
                var hash = hashServices.Hash(log.Tipo + log.Fecha + log.Email + log.Descripcion);
                if (hash != log.Digito)
                    log.Corrompido = true;
            }
            GridView.DataSource = _log;
            GridView.DataBind();

            var comprasServices = new ComprasServices();
            var compras = comprasServices.GetPedidos();
            foreach (var compa in compras)
            {
                var hash = hashServices.Hash(compa.UsuarioId.ToString() +  compa.PicadaId.ToString() + compa.Fecha.Date.ToString());
                if (hash != compa.Digito)
                    compa.Corrompido = true;
            }
            GdvCompras.DataSource = compras;
            GdvCompras.DataBind();
        }
Ejemplo n.º 2
0
        public IActionResult GetHash()
        {
            var plainText   = "Felipe Gavilán";
            var hashResult1 = hashService.Hash(plainText);
            var hashResult2 = hashService.Hash(plainText);

            return(Ok(new { plainText, hashResult1, hashResult2 }));
        }
Ejemplo n.º 3
0
        public ActionResult GetHash()
        {
            string textoPlano  = "Felipe Gavilán";
            var    hashResult1 = _hashService.Hash(textoPlano).Hash;
            var    hashResult2 = _hashService.Hash(textoPlano).Hash;

            return(Ok(new { textoPlano, hashResult1, hashResult2 }));
        }
Ejemplo n.º 4
0
        public IActionResult Hash()
        {
            string plainText   = "Dimitris Kosmas";
            var    hashResult1 = _hashService.Hash(plainText);
            var    hashResult2 = _hashService.Hash(plainText);

            return(Ok(new { plainText, hashResult1, hashResult2 }));
        }
Ejemplo n.º 5
0
        public IActionResult GetHash()
        {
            var plainText   = "Thomas Margraff";
            var hashResult1 = hashService.Hash(plainText);
            var hashResult2 = hashService.Hash(plainText);

            return(Ok(new { plainText, hashResult1, hashResult2 }));
        }
        public IActionResult GetHash()
        {
            var plaintext   = "Oluwaseyi Ademola";
            var hashResult1 = hashService.Hash(plaintext);
            var hashResult2 = hashService.Hash(plaintext);

            return(Ok(new { plaintext, hashResult1, hashResult2 }));
        }
        public ActionResult GetHash()
        {
            string texto       = "Axel";
            var    hashResult1 = _hashService.Hash(texto).Hash;
            var    hashResult2 = _hashService.Hash(texto).Hash;

            return(Ok(new { texto, hashResult1, hashResult2 }));
        }
Ejemplo n.º 8
0
        public ActionResult GetHash()
        {
            string textoplano  = "douglasLoaiza ";
            var    hashResult  = _hashService.Hash(textoplano).Hash;
            var    hashResult2 = _hashService.Hash(textoplano).Hash;

            return(Ok(new { textoplano, hashResult, hashResult2 }));
        }
        public ActionResult GetHash()
        {
            string plain       = "Freddy Soto";
            var    hashResult  = _hashService.Hash(plain).Hash;
            var    hashResult2 = _hashService.Hash(plain).Hash;

            return(Ok(new { hashResult, hashResult2 }));
        }
Ejemplo n.º 10
0
        public IActionResult GetHash()
        {
            var plainText   = "Vivek Arya";
            var hashResult1 = hashService.Hash(plainText);
            var hashResult2 = hashService.Hash(plainText);

            return(Ok(new { plainText, hashResult1, hashResult2 }));
        }
Ejemplo n.º 11
0
        public ActionResult GetHash()
        {
            string textoPlano  = "Carlos Mario Monroy";
            var    hashResult1 = _hashService.Hash(textoPlano).Hash;
            var    hashResult2 = _hashService.Hash(textoPlano).Hash;

            return(Ok(new { textoPlano, hashResult1, hashResult2 }));
        }
        public ActionResult GetHash()
        {
            string textoPlano  = "Ariel Cabrera";
            var    hashResult1 = _hashService.Hash(textoPlano).Hash;
            var    hashResult2 = _hashService.Hash(textoPlano).Hash;

            return(Ok(new { textoPlano, hashResult1, hashResult2 }));
        }
Ejemplo n.º 13
0
        public IActionResult GetHash()
        {
            var plainText   = "Name Surname";
            var hashResult1 = _hashService.Hash(plainText);
            var hashResult2 = _hashService.Hash(plainText);

            return(Ok(new { plainText, hashResult1, hashResult2 }));
        }
        public ActionResult RealizarHash(string textoPlano)
        {
            var resultado1 = hashService.Hash(textoPlano);
            var resultado2 = hashService.Hash(textoPlano);

            return(Ok(new
            {
                textoPlano = textoPlano,
                Hash1 = resultado1,
                Hash2 = resultado2
            }));
        }
        public ActionResult GetHash()
        {
            string plainText   = "DavidJuajinoy";
            var    HashResult  = hashService.Hash(plainText);
            var    HashResult1 = hashService.Hash(plainText);

            return(Ok(
                       new
            {
                plainText = plainText,
                HashResult = HashResult,
                HashResult1 = HashResult1
            }
                       ));
        }
Ejemplo n.º 16
0
        public IHttpResponse PostLogin(IHttpRequest request)
        {
            var usernameOrEmail = request.FormData["username"].ToString();
            var password        = request.FormData["password"].ToString();

            var hashedPassword = hashService.Hash(password);

            User user;

            if (usernameOrEmail.Contains("%40"))
            {
                WebUtility.UrlEncode(usernameOrEmail);

                user = Context.Users.FirstOrDefault(x => x.Email == usernameOrEmail && x.Password == hashedPassword);
            }
            else
            {
                user = this.Context.Users.FirstOrDefault(x => x.Username == usernameOrEmail && x.Password == hashedPassword);
            }
            if (user == null)
            {
                return(new RedirectResult("/Users/Login"));
            }

            var username = user.Username;

            var response = new RedirectResult("/Home/Index");

            this.SignInUser(username, request, response);

            return(response);
        }
Ejemplo n.º 17
0
        public IActionResult GetHash()
        {
            var plainText = "Ali Chavoshi";
            var result    = _hashService.Hash(plainText);

            return(Ok(result));
        }
Ejemplo n.º 18
0
        public void HashPasswordAndCheck(string inputPassword, string expectedHash)
        {
            var configuration  = new AppConfigurationBuilder().Build();
            var hashService    = new HashService(configuration);
            var hashedPassword = hashService.Hash(inputPassword);

            Assert.Equal(hashedPassword, expectedHash);
        }
Ejemplo n.º 19
0
        public async Task <ActionResult> Post([FromBody] Users user)
        {
            try
            {
                ApiError errorResponse   = new ApiError();
                var      userNameCreated = await context.Users.FirstOrDefaultAsync(x => x.UserName == user.UserName);

                var emailRegistered = await context.Users.FirstOrDefaultAsync(x => x.Email == user.Email);

                var dniRegistered = await context.Users.FirstOrDefaultAsync(x => x.Identification == user.Identification);

                var telephoneRegistered = await context.Users.FirstOrDefaultAsync(x => x.Telephone == user.Telephone);

                if (userNameCreated != null)
                {
                    errorResponse.Success      = false;
                    errorResponse.ErrorMessage = "El usuario ya existe";
                    return(new JsonResult(errorResponse));
                }

                else if (emailRegistered != null)
                {
                    errorResponse.Success      = false;
                    errorResponse.ErrorMessage = "El Email ya esta registrado";
                    return(new JsonResult(errorResponse));
                }

                else if (dniRegistered != null)
                {
                    errorResponse.Success      = false;
                    errorResponse.ErrorMessage = "El Número de Identificación ya esta registrado";
                    return(new JsonResult(errorResponse));
                }

                else if (telephoneRegistered != null)
                {
                    errorResponse.Success      = false;
                    errorResponse.ErrorMessage = "El telefono ya ha sido registrado";

                    return(new JsonResult(errorResponse));
                }

                var hash = _hashService.Hash(user.Password);
                user.Password     = hash.Hash;
                user.SaltPassword = hash.Salt;

                context.Users.Add(user);
                context.SaveChanges();
                return(new CreatedAtRouteResult("getUser", new { id = user.UserCode }, user));
            }

            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Ejemplo n.º 20
0
        public IHttpResponse DoRegister(RegisterViewModel model)
        {
            SetDefaultViewData();
            string errorMessage;

            if (string.IsNullOrWhiteSpace(model.Username) || model.Username.Length < 4)
            {
                errorMessage = "Please, provide valid username with length 4 or more symbols";
                return(BadRequestError(errorMessage));
            }

            if (Db.Users.Any(u => u.Username.Equals(model.Username)))
            {
                errorMessage = $"User with username: {model.Username} already exists.";
                return(BadRequestError(errorMessage));
            }

            if (string.IsNullOrWhiteSpace(model.Password) || model.Password.Length < 6)
            {
                errorMessage = "Please, provide valid password with length 6 or more symbols";
                return(BadRequestError(errorMessage));
            }

            if (!model.Password.Equals(model.ConfirmPassword))
            {
                errorMessage = "Passwords do not match.";
                return(BadRequestError(errorMessage));
            }

            var hashedPassword = HashService.Hash(model.Password);

            model.Password = hashedPassword;

            try
            {
                _userService.Create(model);
            }
            catch (Exception e)
            {
                //TODO Log error
                return(ServerError(e.Message));
            }

            ViewData["title"] = "Home";

            return(View("home/index"));
        }
        public void TestIfLoginReturnsTrue()
        {
            var context     = InitContext();
            var username    = "******";
            var password    = "******";
            var email       = "email";
            var hashService = new HashService();

            var hashedPassword = hashService.Hash(password);

            context.Users.Add(new User(username, email, hashedPassword));
            context.SaveChanges();

            var loginService = new LoginService(context);

            Assert.IsTrue(loginService.Login(username, password));
            Assert.IsFalse(loginService.Login(username, "wrongpass"));
        }
Ejemplo n.º 22
0
        public IHttpResponse DoLogin(LoginViewModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Username) || string.IsNullOrWhiteSpace(model.Password) ||
                string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
            {
                var errorMessage = "Invalid username or password.";
                return(BadRequestError(errorMessage));
            }

            var hashedPassword = HashService.Hash(model.Password);

            using (Db)
            {
                var user = Db.Users.FirstOrDefault(u => u.Username.Equals(model.Username));

                bool isEqual = user != null && user.Username.Equals(model.Username);

                if (!Db.Users.Any(u => u.Password.Equals(hashedPassword)) || !isEqual)
                {
                    var errorMessage = "Invalid username or password.";
                    return(BadRequestError(errorMessage));
                }

                ViewData["greeting"] = user.Name;
            }


            Request.Session.AddParameter(".auth_cake", model.Username);

            Request.Session.AddParameter(ShoppingCartViewModel.SessionKey, new ShoppingCartViewModel());

            ViewData["authenticated"]    = "bloc";
            ViewData["cart"]             = "bloc";
            ViewData["notAuthenticated"] = "none";
            ViewData["title"]            = "Home";
            ViewData["searchTerm"]       = null;

            var cookieContent = UserCookieService.GetUserCookie(model.Username);

            Response.Cookies.Add(new HttpCookie(".auth_cake", $"{cookieContent}; {GlobalConstants.HttpOnly}", 7));

            return(View("/"));
        }
Ejemplo n.º 23
0
        public IHttpResponse PostLogin(IHttpRequest request)
        {
            var username = request.FormData["username"].ToString();
            var password = request.FormData["password"].ToString();

            var hashService   = new HashService();
            var cookieService = new UserCookieService();

            var hashedPassword = hashService.Hash(password);

            var user = this.Context.Users.FirstOrDefault(u => u.Username == username && u.HashedPassword == hashedPassword);

            if (user == null)
            {
                return(new RedirectResult("/login"));
            }

            request.Session.AddParameter("username", username);
            var userCookieValue = cookieService.GetUserCookie(username);

            request.Cookies.Add(new HttpCookie("IRunes_auth", userCookieValue));
            return(new RedirectResult("home/index"));
        }
 public async Task Validate <TEntity>(DigitoVerificadorTablasEnum tabla) where TEntity : Verificable, IEntityToDb, new()
 {
     (await new GenericRepository <TEntity>().GetAsync())
     .Success(async x =>
     {
         var hasService                  = new HashService();
         var codigoVerificador           = hasService.Hash(string.Join("", x.Select(s => hasService.Hash(s.Hash))));
         var digitoVerificadorRepository = new GenericRepository <DigitoVerificadorVertical>();
         (await digitoVerificadorRepository.GetAsync(
              new Parameters().Add(nameof(tabla), tabla.ToString())))
         .Success(async verificadorVertical =>
         {
             var valid    = verificadorVertical.First();
             valid.Digito = codigoVerificador;
             await digitoVerificadorRepository.UpdateDataAsync(valid);
         })
         .Error(async erros =>
         {
             await digitoVerificadorRepository.InsertDataAsync(new DigitoVerificadorVertical(codigoVerificador,
                                                                                             DigitoVerificadorTablasEnum.Concursos));
         });
     });
 }
Ejemplo n.º 25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var usuario = Session["UsuarioLogueado"] as Usuario;

            if (usuario.Tipo != UsuarioTipo.WebMaster.ToString())
            {
                Response.Redirect("Login.aspx");
            }
            var logsServices = new LogServices();
            var logs         = logsServices.Get();
            var hashServices = new HashService();

            foreach (var log in logs)
            {
                var hash = hashServices.Hash(log.Tipo + log.Fecha + log.Email + log.Descripcion);
                if (hash != log.Digito)
                {
                    log.Corrompido = true;
                }
            }
            GridView.DataSource = logs;
            GridView.DataBind();
        }
        private async Task <Response <bool> > CallVarificables <TEntity>(DigitoVerificadorTablasEnum tabla,
                                                                         Func <DigitoVerificadorVertical, string, Task <Response <bool> > > successCall,
                                                                         Func <List <string>, Task <Response <bool> > > errorCall
                                                                         ) where TEntity : Verificable, IEntityToDb, new()
        {
            var returnValue = Response <bool> .Ok(true);

            (await new GenericRepository <TEntity>().GetAsync())
            .Success2(async x =>
            {
                var hasService                  = new HashService();
                var codigoVerificador           = hasService.Hash(string.Join("", x.Select(s => hasService.Hash(s.Hash))));
                var digitoVerificadorRepository = new GenericRepository <DigitoVerificadorVertical>();
                returnValue = (await digitoVerificadorRepository.GetAsync(
                                   new Parameters().Add(nameof(tabla), tabla.ToString())))
                              .Success(async verificadorVertical =>
                {
                    return(await successCall(verificadorVertical.First(), codigoVerificador));
                })
                              .Error(async errors => { await errorCall(errors); });
                return(returnValue);
            });
            return(returnValue);
        }
Ejemplo n.º 27
0
 public ActionResult <object> GetObtenerHash(string textoEncriptado, string salt)
 {
     byte[] bytesSalt = Encoding.ASCII.GetBytes(salt);
     return(Ok(_hashService.Hash(textoEncriptado, bytesSalt)));
 }
Ejemplo n.º 28
0
 private string HashPhraseWithSalt(string phrase, string salt)
 {
     return(_sut.Hash(new ClearPhrase(phrase, salt)));
 }
Ejemplo n.º 29
0
        public static User VerifyUser(string username, string password)
        {
            var users = new List <User>();

            DateTime localDate = DateTime.Now;

            users.Add(new User {
                Id = 1, Username = "******", Password = "******", Profile = "admin", Status = true, CreatedDate = localDate
            });
            users.Add(new User {
                Id = 2, Username = "******", Password = "******", Profile = "employee", Status = true, CreatedDate = localDate
            });
            users.Add(new User {
                Id = 3, Username = "******", Password = "******", Profile = "consult", Status = true, CreatedDate = localDate
            });

            return(users.Where(x =>
                               x.Username.ToLower() == username.ToLower() && HashService.Verify(x.Password, HashService.Hash(password))
                               ).FirstOrDefault());
        }
Ejemplo n.º 30
0
        public void DeployWebApi(ITaskContext context)
        {
            DeploymentConfig config = null;
            var json = File.ReadAllText("DeploymentConfig.json");

            config = JsonConvert.DeserializeObject <DeploymentConfig>(json);
            ValidateDeploymentConfig(config);
            string connectionString;

            if (!string.IsNullOrWhiteSpace(config.LiteDbConnectionString))
            {
                connectionString = config.LiteDbConnectionString;
            }
            else
            {
                var liteDbPassword = GenerateRandomSecureString(15);
                connectionString = $"FileName=database.db; Password={liteDbPassword}";
            }

            bool createDb     = false;
            var  dbFileName   = Files.GetFileNameFromConnectionString(connectionString);
            var  isPathRooted = Path.IsPathRooted(dbFileName);

            if (!config.IsUpdate)
            {
                if (config.RecreateDatabase)
                {
                    createDb = true;
                }
                else
                {
                    if (isPathRooted)
                    {
                        if (!File.Exists(dbFileName))
                        {
                            createDb = true;
                        }
                    }
                    else
                    {
                        var dbPath = Path.Combine(config.DeploymentPath, dbFileName);
                        if (!File.Exists(dbPath))
                        {
                            createDb = true;
                        }
                    }
                }

                if (createDb)
                {
                    File.Delete(dbFileName);
                    using (var db = new LiteRepository(connectionString))
                    {
                        IUserRepository repository  = new UserRepository(db);
                        var             hashService = new HashService();

                        repository.AddUser(new User
                        {
                            Username = config.Username,
                            Password = hashService.Hash(config.Password),
                        });
                    }

                    if (!isPathRooted)
                    {
                        var outputDbFilePath = Path.Combine("FlubuCore.WebApi", dbFileName);

                        context.Tasks().CopyFileTask(dbFileName, outputDbFilePath, true)
                        .Execute(context);
                    }
                }
                else
                {
                    ////Delete old db file if it exists so it doesnt rewrite database at deployed location.
                    var outputDbFilePath = Path.Combine("FlubuCore.WebApi", dbFileName);
                    if (File.Exists(outputDbFilePath))
                    {
                        File.Delete(outputDbFilePath);
                    }
                }

                context.Tasks().UpdateJsonFileTask(@".\FlubuCore.WebApi\appsettings.json")
                .Update(new KeyValuePair <string, JValue>("FlubuConnectionStrings.LiteDbConnectionString",
                                                          new JValue(connectionString))).Execute(context);

                context.Tasks().UpdateJsonFileTask(@".\FlubuCore.WebApi\appsettings.json")
                .Update(new KeyValuePair <string, JValue>("WebApiSettings.AllowScriptUpload",
                                                          new JValue(config.AllowScriptUpload))).Execute(context);

                context.Tasks().UpdateJsonFileTask(@".\FlubuCore.WebApi\appsettings.json")
                .Update("JwtOptions.SecretKey", GenerateRandomString(30)).Execute(context);
                context.Tasks().CreateDirectoryTask(config.DeploymentPath + "\\Packages", false).Execute(context);
                context.Tasks().CreateDirectoryTask(config.DeploymentPath + "\\Scripts", false).Execute(context);
            }
            else
            {
                ////Delete old db file if it exists so it doesnt rewrite database at deployed location.
                var outputDbFilePath = Path.Combine("FlubuCore.WebApi", dbFileName);
                if (File.Exists(outputDbFilePath))
                {
                    File.Delete(outputDbFilePath);
                }

                if (File.Exists("FlubuCore.WebApi/appsettings.json"))
                {
                    File.Delete("FlubuCore.WebApi/appsettings.json");
                }

                if (File.Exists("FlubuCore.WebApi/web.config"))
                {
                    File.Delete("FlubuCore.WebApi/web.config");
                }
            }

            context.Tasks().CopyDirectoryStructureTask("FlubuCore.Webapi", config.DeploymentPath, true)
            .Execute(context);
        }