예제 #1
0
        /// <summary>
        /// Valida si un usuario esta registrado en la base datos y en caso de existir que
        /// la contraseña enviada sea correcta
        /// </summary>
        /// <param name="request">Credenciales de login</param>
        /// <returns>Un objeto respuesto del tipo LoginResponseDTO.</returns>
        public ResponseDTO <LoginResponseDTO> ValidateUser(UserDTO request)
        {
            ResponseDTO <List <LoginResponseDTO> > responseList = loginResponseDataManager.GetByUser(request);
            ResponseDTO <LoginResponseDTO>         response     = new ResponseDTO <LoginResponseDTO>();


            //Valida que la contraseña sea correcta si se obtuvo al usuario correctamente
            if (responseList.Success)
            {
                //Si el usuario tiene mas de un un rol asignado, se valida si tiene el rol de administrador,
                //en caso de que no exista se envia el rol de supervisor.
                if (responseList.Result.Count > 1)
                {
                    var query = from p in responseList.Result
                                where p.Role.IdRole == 1
                                select p;
                    response.Result = query.First();
                }
                if (response.Result == null)
                {
                    response.Result = responseList.Result.First();
                }

                //Se valida que la contraseña enviada sea correcta
                response.Result.IsAuthenticated = HashEncryption.VerifyHashPassword(response.Result.User.Password, request.Password);
                response.Result.User.Password   = string.Empty;
            }
            if (!response.Result.IsAuthenticated)
            {
                response.Result  = null;
                response.Success = false;
                response.Message = "Username or Password incorrect.";
            }
            return(response);
        }
예제 #2
0
        public void LoginSuccess()
        {
            string email    = "*****@*****.**";
            string password = "******";

            if (!Context.Users.Any(a => a.Email == email))
            {
                var passHash = HashEncryption.Hash(password);
                Context.Users.Add(new User {
                    Email = email, Password = passHash, Name = "Test"
                });
                Context.SaveChanges();
            }

            LoginRequest request = (new LoginRequest {
                Email = email, Password = password
            });

            //Act
            UserResponse respons = Client.Login(request);

            //Assert
            Assert.NotNull(respons);
            Assert.NotNull(respons.User);
            Assert.AreEqual(respons.Respons.Status, ServiceResponseStatus.Ok);
            Assert.AreEqual(respons.User.Email, email);
        }
예제 #3
0
        public void TestMethod8()
        {
            var he = new HashEncryption(HashAlgorithmType.SHA512);

            Assert.AreEqual("ad4656caa3d4328096a14cf58730be80de238e7b029622597dd3836087289dac7bb7b395ee766787b02c2346d4c72aa4cf6aa6e4fc48b4cf57f39019783f0495",
                            he.Encrypt("爱我中华012345abcde~!@#"));
        }
예제 #4
0
        public void TestMethod7()
        {
            var he = new HashEncryption(HashAlgorithmType.SHA384);

            Assert.AreEqual("fab604de55af8cd87d2e32f66a6ead7d103bd11e824b46a9ab29116d9057794a4e4672a39a56f6b94107270656406193",
                            he.Encrypt("爱我中华012345abcde~!@#"));
        }
예제 #5
0
        public void TestMethod1()
        {
            string Pass = HashEncryption.Hash("TextPassword");

            bool ValidatePass = HashEncryption.VerifyHashPassword(Pass, "TextPassword");

            Assert.IsTrue(ValidatePass);
        }
예제 #6
0
        public void TestMethod4()
        {
            var he        = new HashEncryption();
            var targetStr = he.Encrypt("爱我中华012345abcde~!@#", Encoding.Unicode);

            Assert.AreNotEqual("92556af5f0ea9feeefdf40f3c2665acd", targetStr);
            Assert.AreEqual(32, targetStr.Length);
        }
예제 #7
0
 static bool SumsAreEqual(IAbsoluteFilePath source, IAbsoluteFilePath destination)
 {
     if (!destination.Exists || !source.Exists)
     {
         return(false);
     }
     return(HashEncryption.MD5FileHash(source) == HashEncryption.MD5FileHash(destination));
 }
예제 #8
0
        // <summary>
        /// Se actualiza la infomación de un usuario
        /// </summary>
        /// <param name="request"></param>
        /// <returns>Regresa ibjeto de tipo UserDTO</returns>
        public ResponseDTO <int> Update(UserRequestDTO request)
        {
            request.User = request.User == null ? new UserDTO(request.Info.IdUser) : request.User;
            request.Info = request.Info == null ? new InfoDTO() : request.Info;

            request.User.Password = !string.IsNullOrEmpty(request.User.Password)? HashEncryption.Hash(request.User.Password):null;

            return(_userRequestRepository.Update(request));
        }
예제 #9
0
 public ActionResult CommentCreate([Bind(Include = "CommentId,ArticleId,Content,CommentPassword,PostTime")] Comment comment)
 {
     if (ModelState.IsValid)
     {
         IEncryptable encryptor = new HashEncryption();
         comment.CommentPassword = encryptor.Encrypt(comment.CommentPassword);
         db.Comments.Add(comment);
         db.SaveChanges();
     }
     return(RedirectToAction("View", new { id = comment.ArticleId }));
 }
예제 #10
0
 //
 public void Add100Users()
 {
     for (int i = 0; i < 100; i++)
     {
         string userName = "******" + i;
         var    passHash = HashEncryption.Hash(userName);
         Context.Users.Add(new User {
             Email = userName + "@a.a", Password = passHash, Name = userName
         });
         Context.SaveChanges();
     }
 }
예제 #11
0
        public ActionResult AdminLogin([Bind(Include = "Name,AccountPassword")] Account account)
        {
            IEncryptable encryptor         = new HashEncryption();
            string       encryptedPassword = encryptor.Encrypt(account.AccountPassword);
            bool         userValid         = db.Accounts.Any(u => u.Name.Equals(account.Name) && u.AccountPassword.Equals(encryptedPassword));

            if (userValid)
            {
                FormsAuthentication.SetAuthCookie(account.Name, false);
                return(RedirectToAction("AdminIndex"));
            }
            return(RedirectToAction("AdminLogin"));
        }
예제 #12
0
        public ActionResult CommentDeleteConfirmed(int commentId, string password)
        {
            var          comment       = db.Comments.Find(commentId);
            IEncryptable encryptor     = new HashEncryption();
            bool         passwordVaild = encryptor.IsEqual(password, comment.CommentPassword);

            if (passwordVaild)
            {
                db.Comments.Remove(comment);
                db.SaveChanges();
                return(Json("Comment has been deleted successfully!"));
            }
            return(Json("Wrong password!"));
        }
예제 #13
0
                private async Task OnlyCopyIfHashMisMatch(IAbsoluteFilePath source, IAbsoluteFilePath destination,
                                                          ITProgress status)
                {
                    if (
                        await
                        TaskExt.StartLongRunningTask(
                            () => HashEncryption.MD5FileHash(source) != HashEncryption.MD5FileHash(destination))
                        .ConfigureAwait(false))
                    {
                        await CopyAsyncInternal(source, destination, true, status).ConfigureAwait(false);

                        return;
                    }
                    this.Logger()
                    .Info("Source and destination files equal. Source: {0}, Destination: {1}", source,
                          destination);
                }
예제 #14
0
        public ServiceResponse Registration(User user, string password, string repeatPassword)
        {
            user.Email = user.Email.ToLower();

            ValidationResult valid = userServiceValidation.Registration(user, password, repeatPassword);

            if (!valid.IsSucces)
            {
                return(new ServiceResponse(ServiceRespondStatus.Error, valid.ErrorList));
            }

            user.Password = HashEncryption.Hash(password);

            context.Users.Add(user);
            context.SaveChanges();

            return(new ServiceResponse());
        }
예제 #15
0
        public ValidationResult ComparePassword(string password, string hashPassword)
        {
            _password = password;
            result    = new ValidationResult();

            this.IsNull();
            if (!result.IsSucces)
            {
                return(result);
            }

            bool isCorrectPassword = HashEncryption.Verification(_password, hashPassword);

            if (!isCorrectPassword)
            {
                result.AddError(ValidationKey.PasswordNotCompare);
            }

            return(result);
        }
예제 #16
0
 private void Copy(UserCrDto userCrDto, User user, bool copyNickname, bool copyPassword)
 {
     user.city_id       = userCrDto.CityId;
     user.university_id = userCrDto.UniversityId;
     user.description   = userCrDto.Description;
     user.email         = userCrDto.Email;
     user.group         = userCrDto.Group;
     user.name          = userCrDto.Name;
     user.phone         = userCrDto.Phone;
     user.surname       = userCrDto.Surname;
     if (copyNickname)
     {
         user.nickname = userCrDto.Nickname;
     }
     if (copyPassword)
     {
         var encryption = new HashEncryption();
         encryption.HashPassword(user);
     }
 }
예제 #17
0
        public ServiceResponse ChangePassword(int userId, string oldPassword, string newPassword, string repeatNewPassword)
        {
            User user = GetUserById(userId);

            if (user == null)
            {
                return(new ServiceResponse(ServiceRespondStatus.Error, ValidationKey.NullUser.ToString(), MessageOperation.GetValidationMessage(ValidationKey.NullUser)));
            }

            ValidationResult passwordValidate = userServiceValidation.ChangePassword(user.Password, oldPassword, newPassword, repeatNewPassword);

            if (!passwordValidate.IsSucces)
            {
                return(new ServiceResponse(ServiceRespondStatus.Error, passwordValidate.ErrorList));
            }

            user.Password = HashEncryption.Hash(newPassword);
            context.SaveChanges();

            return(new ServiceResponse());
        }
예제 #18
0
 protected void Page_Load(object sender, EventArgs e)
 {
     txtError.Visible = false;
     txtError.Text    = string.Empty;
     //Session.Abandon();
     if (IsPostBack)
     {
         lafien_products_dbEntities db    = new lafien_products_dbEntities();
         HashEncryption             hasEn = new HashEncryption();
         string  enPass = hasEn.SHA256Hash(txtPassword.Value);
         Account obj    = db.Accounts.FirstOrDefault(x => x.UserName == txtUsername.Value && x.Password == enPass);
         if (obj != null)
         {
             HttpContext.Current.Session["LoggedAccount"] = obj;
             Response.Redirect("~/Pages/Default.aspx");
         }
         else
         {
             txtError.Visible = true;
             txtError.Text    = "Invalid Username or Password!";
         }
     }
 }
예제 #19
0
        public CrResult <UserDto> Create(UserCrDto userCrDto)
        {
            var crResult = new CrResult <UserDto>();

            CheckRegisterData(userCrDto, crResult, true, true);
            if (crResult.ActionResult == ActionResult.Success)
            {
                var user       = Converter.ConvertToUser(userCrDto);
                var encryption = new HashEncryption();
                encryption.HashPassword(user);
                try
                {
                    var createdUser = _context.User.Add(user);
                    _context.SaveChanges();
                    crResult.CreatedObject = Converter.ConvertToUserDto(createdUser);
                }
                catch (DbUpdateException)
                {
                    crResult.ActionResult = ActionResult.DatabaseError;
                }
            }
            return(crResult);
        }
예제 #20
0
        private bool Autenticado(string usuario, string senha)
        {
            ControleAcessoServiceClient servico = new ControleAcessoServiceClient();

            try
            {
                var resultService = servico.ListarUsuarioPorLoginAsync(usuario);

                resultService.Wait();

                if (HashEncryption.Compare(senha.ToUpper(), resultService.Result.Senha.ToUpper()) && (resultService.Result.Status.Equals("A")))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #21
0
        public void TestMethod1()
        {
            var he = new HashEncryption();

            Assert.AreEqual("e807f1fcf82d132f9bb018ca6738a19f", he.Encrypt("1234567890"));
        }
예제 #22
0
        /// <summary>
        /// Se agrega información de usuarios nuevos
        /// </summary>
        /// <param name="request"></param>
        /// <returns>Regresa id de usuario</returns>
        public ResponseDTO <int> Add(UserRequestDTO request)
        {
            request.User.Password = HashEncryption.Hash(request.User.Password);

            return(_userRequestRepository.Add(request));
        }
예제 #23
0
        public static string HashEncrypt(this string str, HashAlgorithmType haType = HashAlgorithmType.MD5, Encoding encoding = null)
        {
            var he = new HashEncryption(haType);

            return(he.Encrypt(str, encoding));
        }
예제 #24
0
        public void ProcessRequest(HttpContext context)
        {
            // set from an earlier in pipeline by CDNInterceptPipeline
            string minifyPath = StringUtil.GetString(context.Items["MinifyPath"]);

            if (string.IsNullOrEmpty(minifyPath))
            {
                context.Response.StatusCode = 404;
                context.Response.End();
            }


            UrlString url       = new UrlString(minifyPath);
            string    localPath = url.Path;

            string filePath = FileUtil.MapPath(localPath);

            // if the request is a .js file
            if (localPath.EndsWith(".js"))
            {
                HashEncryption hasher = new HashEncryption(HashEncryption.EncryptionProvider.MD5);
                if (!string.IsNullOrEmpty(localPath))
                {
                    // generate a unique filename for the cached .js version
                    string cachedFilePath = FileUtil.MapPath(string.Format("/App_Data/MediaCache/{0}.js", hasher.Hash(url.ToString())));

                    // if it doesn't exist create it
                    if (!FileUtil.FileExists(cachedFilePath))
                    {
                        // if the original file exsits minify it
                        if (FileUtil.FileExists(filePath))
                        {
                            JsMinifier minifier = new JsMinifier();
                            string     minified = minifier.Minify(filePath);
                            FileUtil.WriteToFile(cachedFilePath, minified);
                        }
                    }

                    if (FileUtil.FileExists(cachedFilePath))
                    {
                        context.Response.ClearHeaders();
                        context.Response.Cache.SetExpires(DateTime.Now.AddDays(14));
                        context.Response.AddHeader("Content-Type", "application/x-javascript; charset=utf-8");
                        context.Response.WriteFile(cachedFilePath);
                        context.Response.End();
                        _success = true;
                    }
                }
            }
            // if the request is a .css file
            else if (localPath.EndsWith(".css"))
            {
                HashEncryption hasher = new HashEncryption(HashEncryption.EncryptionProvider.MD5);
                if (!string.IsNullOrEmpty(localPath))
                {
                    // generate a unique filename for the cached .css version
                    string cachedFilePath = FileUtil.MapPath(string.Format("/App_Data/MediaCache/{0}.css", hasher.Hash(url.ToString())));

                    // if it doesn't exist create it
                    if (!FileUtil.FileExists(cachedFilePath))
                    {
                        // if the original file exsits minify it
                        if (FileUtil.FileExists(filePath))
                        {
                            CssMinifier minifier = new CssMinifier();
                            string      minified = CssMinifier.Minify(FileUtil.ReadFromFile(filePath));

                            // if Css Processing is enabled, replace any urls inside the css file.
                            if (CDNSettings.ProcessCss)
                            {
                                // find all css occurences of url([url])
                                Regex reReplaceUrl = new Regex("url\\(\\s*['\"]?([^\"')]+)['\"]?\\s*\\)");

                                try
                                {
                                    // replacing  url([url]) with url([cdnUrl]) in css
                                    minified = reReplaceUrl.Replace(minified, (m) =>
                                    {
                                        string oldUrl = "";
                                        if (m.Groups.Count > 1)
                                        {
                                            oldUrl = m.Groups[1].Value;
                                        }

                                        if (WebUtil.IsInternalUrl(oldUrl))
                                        {
                                            if (oldUrl.StartsWith("."))
                                            {
                                                oldUrl = VirtualPathUtility.Combine(url.Path, oldUrl);
                                            }
                                            string newUrl = CDNManager.ReplaceMediaUrl(oldUrl, string.Empty);
                                            if (!string.IsNullOrEmpty(newUrl))
                                            {
                                                return(m.Value.Replace(m.Groups[1].Value, newUrl));
                                            }
                                        }

                                        return(m.Value);
                                    });
                                }
                                catch (Exception ex)
                                {
                                    Log.Error("Minify error", ex, this);
                                }
                            }

                            FileUtil.WriteToFile(cachedFilePath, minified);
                        }
                    }

                    if (FileUtil.FileExists(cachedFilePath))
                    {
                        context.Response.ClearHeaders();
                        context.Response.Cache.SetExpires(DateTime.Now.AddDays(14));
                        context.Response.AddHeader("Content-Type", "text/css; charset=utf-8");
                        context.Response.TransmitFile(cachedFilePath);
                        context.Response.End();
                        _success = true;
                    }
                }
            }
        }
예제 #25
0
        public void ProcessRequest(HttpContext context)
        {
            // set from an earlier in pipeline by CDNInterceptPipeline 
            string minifyPath = StringUtil.GetString(context.Items["MinifyPath"]);

            if (string.IsNullOrEmpty(minifyPath))
            {
                context.Response.StatusCode = 404;
                context.Response.End();
            }
            
            
            UrlString url = new UrlString(minifyPath);
            string localPath = url.Path;

            string filePath = FileUtil.MapPath(localPath);

            // if the request is a .js file
            if (localPath.EndsWith(".js"))
            {
                HashEncryption hasher = new HashEncryption(HashEncryption.EncryptionProvider.MD5);
                if (!string.IsNullOrEmpty(localPath))
                {
                    // generate a unique filename for the cached .js version
                    string cachedFilePath = FileUtil.MapPath(string.Format("/App_Data/MediaCache/{0}.js", hasher.Hash(url.ToString())));

                    // if it doesn't exist create it
                    if (!FileUtil.FileExists(cachedFilePath))
                    {
                        // if the original file exsits minify it
                        if (FileUtil.FileExists(filePath))
                        {
                            JsMinifier minifier = new JsMinifier();
                            string minified = minifier.Minify(filePath);
                            FileUtil.WriteToFile(cachedFilePath, minified);
                        }
                    }

                    if (FileUtil.FileExists(cachedFilePath))
                    {
                        context.Response.ClearHeaders();
                        context.Response.Cache.SetExpires(DateTime.Now.AddDays(14));
                        context.Response.AddHeader("Content-Type", "application/x-javascript; charset=utf-8");
                        context.Response.WriteFile(cachedFilePath);
                        context.Response.End();
                        _success = true;
                    }
                }
            }
            // if the request is a .css file
            else if (localPath.EndsWith(".css"))
            {
                HashEncryption hasher = new HashEncryption(HashEncryption.EncryptionProvider.MD5);
                if (!string.IsNullOrEmpty(localPath))
                {
                    // generate a unique filename for the cached .css version
                    string cachedFilePath = FileUtil.MapPath(string.Format("/App_Data/MediaCache/{0}.css", hasher.Hash(url.ToString())));

                    // if it doesn't exist create it
                    if (!FileUtil.FileExists(cachedFilePath))
                    {
                        // if the original file exsits minify it
                        if (FileUtil.FileExists(filePath))
                        {
                            CssMinifier minifier = new CssMinifier();
                            string minified = CssMinifier.Minify(FileUtil.ReadFromFile(filePath));

                            // if Css Processing is enabled, replace any urls inside the css file.
                            if (CDNSettings.ProcessCss)
                            {
                                // find all css occurences of url([url])
                                Regex reReplaceUrl = new Regex("url\\(\\s*['\"]?([^\"')]+)['\"]?\\s*\\)");

                                try
                                {
                                    // replacing  url([url]) with url([cdnUrl]) in css
                                    minified = reReplaceUrl.Replace(minified, (m) =>
                                    {
                                        string oldUrl = "";
                                        if (m.Groups.Count > 1)
                                            oldUrl = m.Groups[1].Value;

                                        if (WebUtil.IsInternalUrl(oldUrl))
                                        {
                                            if (oldUrl.StartsWith("."))
                                            {
                                                oldUrl = VirtualPathUtility.Combine(url.Path, oldUrl);
                                            }
                                            string newUrl = CDNManager.ReplaceMediaUrl(oldUrl, string.Empty);
                                            if (!string.IsNullOrEmpty(newUrl))
                                            {
                                                return m.Value.Replace(m.Groups[1].Value, newUrl);
                                            }
                                        }

                                        return m.Value;
                                    });
                                }
                                catch (Exception ex)
                                {
                                    Log.Error("Minify error", ex, this);
                                }
                            }

                            FileUtil.WriteToFile(cachedFilePath, minified);
                        }
                    }

                    if (FileUtil.FileExists(cachedFilePath))
                    {
                        context.Response.ClearHeaders();
                        context.Response.Cache.SetExpires(DateTime.Now.AddDays(14));
                        context.Response.AddHeader("Content-Type", "text/css; charset=utf-8");
                        context.Response.TransmitFile(cachedFilePath);
                        context.Response.End();
                        _success = true;
                    }
                }
            }







        }
예제 #26
0
        public void TestMethod2()
        {
            var he = new HashEncryption();

            Assert.AreEqual("bc49baed53d7f0e7ca9642bd12bfa935", he.Encrypt("爱我中华"));
        }
예제 #27
0
        public void TestMethod3()
        {
            var he = new HashEncryption();

            Assert.AreEqual("92556af5f0ea9feeefdf40f3c2665acd", he.Encrypt("爱我中华012345abcde~!@#"));
        }
예제 #28
0
        public void TestMethod6()
        {
            var he = new HashEncryption(HashAlgorithmType.SHA256);

            Assert.AreEqual("190816046f4a031e30080ecab24dd813508e68701121cc9ba83d58e7b15622b9", he.Encrypt("爱我中华012345abcde~!@#"));
        }
예제 #29
0
        public void TestMethod5()
        {
            var he = new HashEncryption(HashAlgorithmType.SHA1);

            Assert.AreEqual("287fecdb4c35e861098b2c1a7e56b6aec76193a5", he.Encrypt("爱我中华012345abcde~!@#"));
        }