public ActionResult ChangePassword(ChangePasswordModel model)
 {
     if (WorkContext.CurrentUserId == 0)
     {
         return(RedirectToAction("LogOff", "Account", new { ReturnUrl = Request.RawUrl }));
     }
     if (ModelState.IsValid)
     {
         var    entity            = _userRepository.GetById(WorkContext.CurrentUserId);
         string hashedOldPassword = PasswordHelper.CreatePasswordHash(model.OldPassword, entity.PasswordSalt);
         if (hashedOldPassword.ToLower() != entity.Password.ToLower())
         {
             ModelState.AddModelError("", "Current Password is incorrect");
             return(View(model));
         }
         string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
         string hashedPassword = PasswordHelper.CreatePasswordHash(model.NewPassword, passwordSalt);
         entity.Password           = hashedPassword;
         entity.PasswordSalt       = passwordSalt;
         entity.NeedChangePassWord = false;
         using (UnitOfWork)
         {
             _userRepository.Update(entity);
         }
     }
     ViewBag.Success = "Password changed successfully";
     return(View(model));
 }
Пример #2
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            MembershipUser            result = null;
            ValidatePasswordEventArgs args   = new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
            }
            else if (GetUserNameByEmail(email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
            }
            else
            {
                MembershipUser user = GetUser(username, false);
                if (user == null)
                {
                    string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
                    string hashedPassword = PasswordHelper.CreatePasswordHash(password, passwordSalt);

                    User userData = new User();
                    //userData.FirstName = passwordQuestion;
                    //userData.LastName = passwordAnswer;
                    userData.Username     = username;
                    userData.EmailAddress = email;
                    userData.Password     = hashedPassword;
                    userData.PasswordSalt = passwordSalt;
                    userData.IsApproved   = isApproved;
                    userData.IsLockedOut  = false;
                    userData.IsOnline     = false;
                    userData.CreateDate   = DateTime.Now;

                    User userReturn;
                    using (_unitOfWork)
                    {
                        userReturn = _userRepository.Insert(userData);
                    }

                    if (userReturn != null)
                    {
                        status = MembershipCreateStatus.Success;
                    }
                    else
                    {
                        status = MembershipCreateStatus.UserRejected;
                    }

                    result = GetUser(username, false);
                }
                else
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                }
            }

            return(result);
        }
Пример #3
0
        public override bool ValidateUser(string username, string password)
        {
            _userRepository = MvcUnityContainer.Container.Resolve <IUserRepository>();
            var officeRepository  = MvcUnityContainer.Container.Resolve <IMyOfficeRepository>();
            var storageRepository = MvcUnityContainer.Container.Resolve <IStorageRepository>();
            var userData          = _userRepository.GetAll().FirstOrDefault(t => t.EmailAddress.ToLower() == username.ToLower());

            if (userData == null)
            {
                return(false);
            }

            if (userData.IsDeleted == true || userData.IsApproved == false || userData.IsLockedOut == true ||
                (userData.AllowLoginFrom.HasValue && userData.AllowLoginFrom.Value.TimeOfDay > DateTime.Now.TimeOfDay) ||
                (userData.AllowLoginTo.HasValue && userData.AllowLoginTo.Value.TimeOfDay < DateTime.Now.TimeOfDay))
            {
                return(false);
            }

            string hashedPassword = PasswordHelper.CreatePasswordHash(password, userData.PasswordSalt);
            bool   result         = userData.Password.ToLower() == hashedPassword.ToLower();

            if (result == true)
            {
                WorkContext.FullName      = string.Format("{0} {1}", userData.FirstName, userData.LastName);
                WorkContext.CurrentUserId = userData.UserId;
                var rolesArray = (from p in userData.Roles
                                  select p.RoleName).ToArray();
                //Check permision
                if (rolesArray.Contains(RoleType.Administrator))
                {
                    WorkContext.MyOffices  = officeRepository.Search("").Select(p => p.MyOfficeId).ToArray();
                    WorkContext.MyStorages = storageRepository.Search("").Select(p => p.StorageId).ToArray();
                }
                else
                {
                    WorkContext.MyOffices  = userData.MyOffices.Select(p => p.MyOfficeId).ToArray();
                    WorkContext.MyStorages = userData.Storages.Select(p => p.StorageId).ToArray();
                }
                userData.LastLogInDate = DateTime.Now;
                _userRepository.UpdateLastActivityDate(username, (DateTime)userData.LastLogInDate);
            }
            return(result);
        }
        public ActionResult Register(AccountDetailsModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            //Insert new user
            string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
            string hashedPassword = PasswordHelper.CreatePasswordHash(model.Password, passwordSalt);
            var    userEntity     = new User
            {
                Address1      = model.Address1,
                Address2      = model.Address2,
                FirstName     = model.ContactName,
                ContactNumber = model.ContactNumber,
                CountryRegion = model.CountryRegion,
                EmailAddress  = model.EmailAddress,
                PostCodeZip   = model.PostCodeZip,
                TownCity      = model.TownCity,
                Username      = model.EmailAddress,
                Password      = hashedPassword,
                PasswordSalt  = passwordSalt,
                IsApproved    = true,
                IsLockedOut   = false,
                IsOnline      = false,
                CreateDate    = DateTime.Now,
                Roles         = new List <Role>(),
            };

            //Add Admin role
            userEntity.Roles.Add(_roleRepository.GetAll().Where(p => p.RoleName == RoleType.KinhDoanh).FirstOrDefault());
            //Add User
            using (UnitOfWork)
            {
                _userRepository.Insert(userEntity);
            }

            return(RedirectToAction("LogOn", "Account"));
        }
Пример #5
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (ValidateUser(username, oldPassword) == false)
            {
                return(false);
            }

            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, oldPassword, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                if (args.FailureInformation != null)
                {
                    throw args.FailureInformation;
                }
                else
                {
                    throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
                }
            }

            string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
            string hashedPassword = PasswordHelper.CreatePasswordHash(newPassword, passwordSalt);

            User userReturn;

            using (_unitOfWork)
            {
                User user = _userRepository.GetUserByUsername(username);
                user.Password     = hashedPassword;
                user.PasswordSalt = passwordSalt;
                userReturn        = _userRepository.Update(user);
            }
            return(userReturn != null);
        }
Пример #6
0
 public ActionResult ChangePassword(ChangePasswordModel model)
 {
     if (ModelState.IsValid)
     {
         var entity = Repository.GetById(model.UserId);
         //string hashedOldPassword = PasswordHelper.CreatePasswordHash(model.OldPassword, entity.PasswordSalt);
         //if (hashedOldPassword.ToLower() != entity.Password.ToLower())
         //{
         //    ModelState.AddModelError("", "Current Password is incorrect");
         //    return View(model);
         //}
         string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
         string hashedPassword = PasswordHelper.CreatePasswordHash(model.NewPassword, passwordSalt);
         entity.Password     = hashedPassword;
         entity.PasswordSalt = passwordSalt;
         using (UnitOfWork)
         {
             Repository.Update(entity);
         }
     }
     //Save success
     this.SetSuccessNotification("Mật khẩu đã được đổi thành công.");
     return(View(model));
 }
Пример #7
0
        public virtual ActionResult Save(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                var listRole = _roleRepository.GetAll().ToList();
                listRole = listRole.Where(p => p.RoleId != 9).ToList();
                var listOffice  = _myOfficeRepository.Search(string.Empty).ToList();
                var listStorage = _storageRepository.Search(string.Empty).ToList();
                userModel.AvailableOffices   = listOffice;
                userModel.AvailableUserRoles = listRole;
                userModel.AvailableStorages  = listStorage;
                return(View("Create", userModel));
            }
            //Check existed
            var modelExisted = Repository.GetAll().FirstOrDefault(p => p.EmailAddress == userModel.Email);

            if ((modelExisted != null && modelExisted.UserId != userModel.UserId) || (modelExisted != null && userModel.UserId <= 0))
            {
                var listRole = _roleRepository.GetAll().ToList();
                listRole = listRole.Where(p => p.RoleId != 9).ToList();
                userModel.AvailableUserRoles = listRole;
                var listOffice = _myOfficeRepository.Search(string.Empty).ToList();
                userModel.AvailableOffices = listOffice;
                var listStorage = _storageRepository.Search(string.Empty).ToList();
                userModel.AvailableStorages = listStorage;
                this.SetErrorNotification("Email này đã tồn tại trong hệ thống.");
                return(View("Create", userModel));
            }
            string passwordSalt = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);

            if (userModel.UserId <= 0) //Create User
            {
                var user = new User()
                {
                    EmailAddress     = userModel.Email,
                    Username         = userModel.Email,
                    FirstName        = userModel.FirstName,
                    LastName         = userModel.LastName,
                    Password         = PasswordHelper.CreatePasswordHash(userModel.Password, passwordSalt),
                    IsApproved       = true,
                    IsLockedOut      = !userModel.IsLockedOut,
                    CreateDate       = DateTime.UtcNow,
                    LastActivityDate = DateTime.UtcNow,
                    PasswordSalt     = passwordSalt,
                    Roles            = new List <Role>(),
                    MyOffices        = new List <MyOffice>(),
                    Storages         = new List <Storage>(),
                    AllowLoginFrom   = userModel.AllowLoginFrom,
                    AllowLoginTo     = userModel.AllowLoginTo,
                    Salary           = userModel.Salary
                };
                foreach (var belongOffice in userModel.BelongOffices)
                {
                    user.MyOffices.Add(_myOfficeRepository.GetById(belongOffice));
                }
                foreach (var storage in userModel.BelongStorages)
                {
                    user.Storages.Add(_storageRepository.GetById(storage));
                }

                user.Roles.Add(_roleRepository.GetById(userModel.RoleId));
                if (userModel.DeliveryInDay)
                {
                    user.Roles.Add(_roleRepository.GetAll().FirstOrDefault(p => p.RoleName == RoleType.DuyetDonHangTrongNgay));
                }
                using (UnitOfWork)
                {
                    Repository.Insert(user);
                }
            }
            else //Edit user
            {
                var userEdit = Repository.GetAll().Where(p => p.UserId == userModel.UserId).Include(p => p.Storages).Include(p => p.MyOffices).FirstOrDefault();
                userEdit.EmailAddress   = userModel.Email;
                userEdit.Username       = userModel.Email;
                userEdit.FirstName      = userModel.FirstName;
                userEdit.LastName       = userModel.LastName;
                userEdit.IsLockedOut    = !userModel.IsLockedOut;
                userEdit.AllowLoginFrom = userModel.AllowLoginFrom;
                userEdit.AllowLoginTo   = userModel.AllowLoginTo;
                userEdit.Salary         = userModel.Salary;
                if (userEdit.Roles.FirstOrDefault().RoleId != userModel.RoleId)
                {
                    userEdit.Roles = new List <Role>();
                    userEdit.Roles.Add(_roleRepository.GetById(userModel.RoleId));
                }
                if (userModel.DeliveryInDay)
                {
                    userEdit.Roles.Add(_roleRepository.GetAll().FirstOrDefault(p => p.RoleName == RoleType.DuyetDonHangTrongNgay));
                }
                userEdit.MyOffices.Clear();
                foreach (var belongOffice in userModel.BelongOffices)
                {
                    userEdit.MyOffices.Add(_myOfficeRepository.GetById(belongOffice));
                }
                userEdit.Storages.Clear();
                foreach (var storage in userModel.BelongStorages)
                {
                    userEdit.Storages.Add(_storageRepository.GetById(storage));
                }
                using (UnitOfWork)
                {
                    Repository.Update(userEdit);
                }
            }

            //Save success
            this.SetSuccessNotification(string.Format("{0} đã được lưu thành công.", "Nhân viên"));
            return(RedirectToAction("Index", new { area = "Administrator" }));
        }
        public ActionResult ForgotPassWord(ForgotPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                var strError = "";
                //var lstError = new List<ErrorViewModel>();
                var Keys   = ModelState.Keys.ToList();
                var Values = ModelState.Values.ToList();
                //Collect all errors
                for (int i = 0; i < Keys.Count; i++)
                {
                    if (Values[i].Errors != null && Values[i].Errors.Count > 0)
                    {
                        strError += Values[i].Errors.FirstOrDefault().ErrorMessage;
                        break;
                    }
                }
                return(Json(strError));
            }
            else
            {
                var newPassWord = StringHelper.GenerateRandomString(6, new Random());
                //Update User
                var user = _userRepository.GetUserByUsername(model.Email);
                if (user != null)
                {
                    using (UnitOfWork)
                    {
                        string passwordSalt   = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
                        string hashedPassword = PasswordHelper.CreatePasswordHash(newPassWord, passwordSalt);
                        user.Password                 = hashedPassword;
                        user.PasswordSalt             = passwordSalt;
                        user.NeedChangePassWord       = true;
                        user.NeedRemindChangePassword = true;
                        _userRepository.Update(user);
                    }
                }
                else
                {
                    return(Json("This user not existed in system."));
                }
                //Send Mail
                // 0: New password
                // 1: Url login
                // 2: Url image sign in
                // 3: Url host
                string  mess     = "";
                string  dataPath = System.Web.HttpContext.Current.Server.MapPath("~/Content/EmailTemplates");
                IniFile ini      = new IniFile(dataPath + "\\SendMailForgotPassWord.ini");
                var     title    = ini.GetStringValue("Title");
                var     subject  = ini.GetStringValue("Subject");
                var     content  = ini.GetStringValue("Content");

                object[] obj = new object[5];
                obj[0] = newPassWord;
                obj[1] = WebHelpers.GetUrlHost();
                obj[2] = WebHelpers.GetUrlHost() + "/Content/images/SignIn.png";
                obj[3] = WebHelpers.GetUrlHost();
                _mailServerService.SendByServer(model.Email, subject, string.Format(content, obj), null, ref mess);
            }
            return(Json("true"));
        }