public IdentityResult changePassword(passwordModel pm)
        {
            Employee emp = db.Employees.Find(pm.EmpId);

            var userStore = new UserStore<IdentityUser>();
            var UserManager = new UserManager<IdentityUser>(userStore);

            var user = UserManager.FindByName(emp.Email);

            return UserManager.ChangePassword(user.Id, pm.oldPassword, pm.newPassword);
        }
 protected void ChangePassword_Click(object sender, EventArgs e)
 {
     if (IsValid)
     {
         UserManager manager = new UserManager();
         IdentityResult result = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text);
         if (result.Succeeded)
         {
             Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
         }
         else
         {
             AddErrors(result);
         }
     }
 }
Exemple #3
0
 protected void ChangePassword_Click(object sender, EventArgs e)
 {
     if (IsValid)
     {
         UserManager    manager = new UserManager();
         IdentityResult result  = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text);
         if (result.Succeeded)
         {
             var user = manager.FindById(User.Identity.GetUserId());
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
         }
         else
         {
             AddErrors(result);
         }
     }
 }
Exemple #4
0
    /*
     * CREATED:     E. Lautner		Mar 22 2018
     *
     * SetPassword_Click()
     * Checks that the new password is identical in ConfirmPassTextBox and NewPassTextBox.
     * Attempts to change the password by passing the old password and new password.
     * Prompts MessageUserControl when action fails or passes.
     *
     * PARAMETERS:
     * object sender - references the object that raised the Page_Load event
     * EventArgs e - optional class that may be passed that inherits from EventArgs (usually empty)
     *
     * RETURNS:
     * void
     *
     * ODEV METHOD CALLS:
     * MessageUserControl.ShowSuccessMessage()
     * MessageUserControl.ShowErrorMessage()
     * UserManager.FindById()
     * UserManager.CheckPassword()
     * MessageUserControl.ShowInfoMessage()
     */
    protected void SetPassword_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            if (ConfirmPassTextBox.Text == NewPassTextBox.Text)
            {
                if (NewPassTextBox.Text.Length < 8)
                {
                    MessageUserControl.ShowInfoMessage("New password must be at least 8 characters long.");
                }
                else
                {
                    try
                    {
                        string      userId        = Context.User.Identity.GetUserId();
                        UserManager userManager   = new UserManager();
                        var         currentUser   = userManager.FindById(userId);
                        bool        checkpassword = userManager.CheckPassword(currentUser, OldPassTextBox.Text);
                        if (checkpassword == true)
                        {
                            IdentityResult result = userManager.ChangePassword(Context.User.Identity.GetUserId(), OldPassTextBox.Text, NewPassTextBox.Text);

                            if (result.Succeeded)
                            {
                                MessageUserControl.ShowSuccessMessage("Password successfully updated.");
                            }
                        }
                        else
                        {
                            MessageUserControl.ShowInfoMessage("Old password was incorrect. Please try again.");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageUserControl.ShowErrorMessage("Password change failed. Please try again. If error persists, please contact your administrator.", ex);
                    }
                }
            }
            else
            {
                MessageUserControl.ShowInfoMessage("New Password and Confirm Password did not match. Please try again.");
            }
        }
    }
        public ActionResult ChangePass(String current, String newPass, String ConfirmNewPass)
        {
            var userStore   = new UserStore <IdentityUser>();
            var userManager = new UserManager <IdentityUser>(userStore);
            var user        = userManager.FindByName(User.Identity.Name);

            if (newPass == ConfirmNewPass)
            {
                userManager.ChangePassword(user.Id, current, newPass);
            }
            else
            {
                TempData["message"] = " Confirm Fail , try again! ";
                return(View());
            }


            return(RedirectToAction("Index", "Home"));
        }
Exemple #6
0
        public ActionResult ChangePassword(ChangePasswordVM password)
        {
            using (var db = new SuperheroDBContext())
            {
                if (password.newPassword == password.newPasswordConfirm)
                {
                    var userMgr = new UserManager <IdentityUser>(new UserStore <IdentityUser>(db));

                    userMgr.ChangePassword(User.Identity.GetUserId(), password.oldPassword, password.newPassword);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("newPassword", "Passwords must be the same");
                }
                return(View(password));
            }
        }
Exemple #7
0
        public result Get(String username, String password, String newpassword)
        {
            result respo = new result();
            UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            var cUser = userManager.Find(username, password);

            if (cUser != null && db.Agents.Where(c => c.UserID.Equals(cUser.Id)).First().IsEnable)
            {
                userManager.ChangePassword(cUser.Id, password, newpassword);
                respo.Result = 1;
            }
            else
            {
                respo.Result = 0;
            }

            return(respo);
        }
Exemple #8
0
        public ActionResult RevisePwd(RevisePwdViewModelr model)
        {
            //用户先得登录才能修改

            if (ModelState.IsValid)
            {
                //输入合法,进行修改
                bool changePwdSuccessed;
                try
                {
                    var userManage =
                        new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new EntityDbContext()));
                    var userName = (Session["LoginUserSessionModel"] as LoginUserSessionModel).User.UserName;
                    //判断原密码是否输入正确
                    var user = userManage.Find(userName, model.PassWord);
                    if (user == null)
                    {
                        ModelState.AddModelError("", "原密码不正确");
                        return(View(model));
                    }
                    else
                    {
                        //修改密码
                        changePwdSuccessed = userManage.ChangePassword(user.Id, model.PassWord, model.NewPassWord).Succeeded;
                        if (changePwdSuccessed)
                        {
                            return(Content("<script>alert('恭喜修改密码成功!');location.href='" + Url.Action("index", "home") +
                                           "'</script>"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "修改密码失败,请重试");
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "修改密码失败,请重试");
                }
            }

            return(View(model));
        }
Exemple #9
0
 public ActionResult ChangePassword(ChangePassword model)
 {
     if (ModelState.IsValid)
     {
         MyIdentityUser user   = userManager.FindByName(HttpContext.User.Identity.Name);
         IdentityResult result = userManager.ChangePassword(user.Id, model.OldPassword, model.NewPassword);
         if (result.Succeeded)
         {
             IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
             authenticationManager.SignOut();
             return(RedirectToAction("Login", "Account"));
         }
         else
         {
             ModelState.AddModelError("", "Error while changing the password.");
         }
     }
     return(View(model));
 }
        protected void ChangePasswordButton_Click(object sender, EventArgs e)
        {
            string existingPassword        = ExistingPasswordTextBox.Text;
            string newPassword             = NewPasswordTextBox.Text;
            string newPasswordConfirmation = ConfirmPasswordTextBox.Text;

            try
            {
                UserManager.ChangePassword(CurrentUser, existingPassword, newPassword, newPasswordConfirmation);
                SessionInfo.Current.User = CurrentUser;
                LoginManager.UpdateLastLoginAuditInfo(SessionInfo.Current.User);
                Login.SetupSessionForCurrentSessionUser();
                Response.Redirect("~/Default.aspx");
            }
            catch (ChangePasswordException cpex)
            {
                FeedbackLabel1.SetErrorMessage(cpex.Message);
            }
        }
Exemple #11
0
        public ActionResult ChangePassword(ChangePasswordViewModel model, string formMode)
        {
            if ((formMode != null) & (formMode == "restore"))
            {
                var user = UserManager.FindById(UserIdS);
                if (user == null)
                {
                    ModelState.AddModelError("", S.UserNotFound);
                    return(View(model));
                }

                ViewBag.Code = UserManager.GeneratePasswordResetToken(user.Id);
                ViewBag.User = user.Email;

                EMail.SendEmail(
                    user.Email,
                    user.Email,
                    System.Configuration.ConfigurationManager.AppSettings["ASE.SiteName"] + " - " + S.RestoringPassword,
                    this.RenderPartialView("MT_RestorePassword"));

                return(RedirectToAction("RestorePassword", new { email = user.Email }));
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var result = UserManager.ChangePassword(UserIdS, model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                return(RedirectToAction("MyProfile", "Member"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }

            return(View(model));
        }
Exemple #12
0
 public JsonResult ChangePassword(ChangePasswordDTO model)
 {
     try
     {
         string UserId = string.Empty;
         if (!string.IsNullOrEmpty(model.UserId))
         {
             UserId = model.UserId;
         }
         else
         {
             UserId = GetLoggedInUserId();
         }
         var user = UserManager.FindById(UserId);
         if (UserManager.CheckPassword(user, model.CurrentPassword))
         {
             var IsPasswordUpdated = UserManager.ChangePassword(UserId, model.CurrentPassword, model.NewPassword);
             if (IsPasswordUpdated.Succeeded)
             {
                 var IsTableUpdated = passwordHistoryService.UpdateLastModifiedDateByUser(UserId);
                 if (IsTableUpdated)
                 {
                     Response.Cookies[".AspNet.ApplicationCookie"].Expires = DateTime.Now.AddDays(-1);
                     return(Json(new { result = "Success" }, JsonRequestBehavior.AllowGet));
                 }
                 else
                 {
                     return(Json(new { result = "Unable to send Email" }));
                 }
             }
             return(Json(new { result = "Not Updated" }));
         }
         else
         {
             return(Json(new { result = "Not Matched" }, JsonRequestBehavior.AllowGet));
         }
     }
     catch (Exception ex)
     {
         return(Json(new { result = "Failure" }, JsonRequestBehavior.AllowGet));
     }
 }
        public ActionResult ChangePassword(SettingsViewModel vm)
        {
            if (ModelState.IsValid)
            {
                AppUser        user   = UserManager.FindById(User.Identity.GetUserId());
                IdentityResult result = UserManager.ChangePassword(user.Id, vm.OldPassword, vm.NewPassword);

                if (result.Succeeded)
                {
                    return(RedirectToAction("LogOut", "Account"));
                }

                else
                {
                    AddErrorsFromResult(result);
                }
            }

            return(View("~/Views/Home/Settings.cshtml", vm));
        }
        public string  ChangePassWD(string oldPassword, string newPassword)
        {
            AppUser user = UserManager.FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

            if (user == null)
            {
                return("用户未登录,请先登录!!");
            }
            if (UserManager.CheckPassword(user, oldPassword) == false)
            {
                return("旧密码不对");
            }
            IdentityResult result = UserManager.ChangePassword(user.Id, oldPassword, newPassword);

            if (result.Succeeded == true)
            {
                return("Success");
            }
            return(result.Errors.ToString());
        }
        public ActionResult ChangePasswordSave(ChangePasswordViewModel loginModel)
        {
            CheckModelState();
            User user = new User();

            try
            {
                user = _userAppService.GetUserByUserName(loginModel.UsernameOrEmailAddress);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (user != null)
            {
                var result = _userManager.ChangePassword(user.Id, loginModel.CurrentPassword, loginModel.NewPassword);
            }
            return(RedirectToAction("Index"));
        }
 public ActionResult Change(ChangePasswordModel model)
 {
     if (ModelState.IsValid)
     {
         IdentityResult canChangePw = UserManager.ChangePassword(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
         if (canChangePw == IdentityResult.Success)
         {
             return(View("Index"));
         }
         else
         {
             ModelState.AddModelError("", "Old password is wrong");
         }
     }
     else
     {
         ModelState.AddModelError("", "Change failed. Please try again");
     }
     return(View(model));
 }
Exemple #17
0
        public ChangePasswordResponseModel ChangePassword(ChangePasswordRequestModel model)
        {
            var resultMessage = "Başarılı";
            var isSuccess     = true;

            try
            {
                UserManager.ChangePassword(model.OldPassword, model.UserId, model.NewPassword);
            }
            catch (Exception ex)
            {
                isSuccess     = false;
                resultMessage = ex.Message;
            }

            return(new ChangePasswordResponseModel()
            {
                IsSuccess = isSuccess, Message = resultMessage
            });
        }
        public ActionResult UserChangePassword(ChangePasswordViewModel model)
        {
            ModelState.Remove("ModifiedOnDatetime");
            ModelState.Remove("ModifiedUsername");

            if (ModelState.IsValid)
            {
                BusinessLayerResult <Users> res = userManager.ChangePassword(model);
                if (res.Errors.Count > 0)
                {
                    res.Errors.ForEach(x => ModelState.AddModelError("", x.Message));
                    return(View(res.Result));
                }

                ViewBag.ChangePassword = "******";
                return(View(model));
            }

            return(View(model));
        }
Exemple #19
0
        public HttpStatusCodeResult UpdatePassword(UserViewModel user)
        {
            if (user.oldpassword != null)
            {
                if (user.password1 != user.password2)
                {
                    return(new HttpStatusCodeResult(417, "Lösenorden matchar inte"));
                }

                var result = UserManager.ChangePassword(user.id, user.oldpassword, user.password1);

                if (result != IdentityResult.Success)
                {
                    return(new HttpStatusCodeResult(403, "Nuvarande lösenordet är fel"));
                }
            }

            db.SaveChanges();
            return(new HttpStatusCodeResult(200, "En användare med id: " + user.id.ToString() + "uppdaterades"));
        }
        public static bool ChangePasswordAsync(string Email, string CurrentPassword, string NewPassword)
        {
            var userContext = new ApplicationDbContext();
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));
            var userASP     = userManager.FindByEmail(Email);

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

            var response = userManager.ChangePassword(userASP.Id, CurrentPassword, NewPassword);

            if (!response.Succeeded)
            {
                return(false);
            }

            return(response.Succeeded);
        }
Exemple #21
0
        public IHttpActionResult TrocarSenha(JObject form)
        {
            string  userName   = string.Empty;
            string  novaSenha  = string.Empty;
            string  velhaSenha = string.Empty;
            dynamic jsonObject = form;

            try
            {
                userName   = jsonObject.UserName.Value;
                novaSenha  = jsonObject.NovaSenha.Value;
                velhaSenha = jsonObject.VelhaSenha.Value;
            }
            catch
            {
                return(this.BadRequest("Chamada Incorreta"));
            }

            var userContext = new ApplicationDbContext();
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));
            var userASP     = userManager.Find(userName, velhaSenha);

            if (userASP == null)
            {
                return(this.BadRequest("Usuário ou Senha incorretos"));
            }

            IdentityResult resposta = userManager.ChangePassword(userASP.Id, velhaSenha, novaSenha);

            if (resposta.Succeeded)
            {
                return(Ok <object>(new
                {
                    Message = "A senha foi alterada"
                }));
            }
            else
            {
                return(BadRequest(resposta.Errors.ToString()));
            }
        }
        protected void Save_Click(object sender, EventArgs e)
        {
            if (OldPass.Text == "")
            {
                lblModal.Text = "Old password is required";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "$('#divPopUp').modal('show');", true);
                return;
            }
            if (NewPass.Text == "")
            {
                lblModal.Text = "New password is required";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "$('#divPopUp').modal('show');", true);
                return;
            }
            if (ConfirmNewPass.Text == "")
            {
                lblModal.Text = "Confirm new password is required";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "$('#divPopUp').modal('show');", true);
                return;
            }
            if (NewPass.Text != ConfirmNewPass.Text)
            {
                lblModal.Text = "New password and confirm new password must same";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "$('#divPopUp').modal('show');", true);
                return;
            }
            var userStore   = new UserStore <IdentityUser>();
            var userManager = new UserManager <IdentityUser>(userStore);
            var result      = userManager.ChangePassword(User.Identity.GetUserId(), OldPass.Text, NewPass.Text);

            if (result.Succeeded)
            {
                lblModal.Text = "Success change password";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "$('#divPopUp').modal('show');", true);
            }
            else
            {
                lblModal.Text = result.Errors.FirstOrDefault();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "$('#divPopUp').modal('show');", true);
            }
        }
        protected void Btn_Submit_Click(object sender, EventArgs e)
        {
            if(TxtNewPassword.Text.Equals(TxtConfirmPassword.Text,StringComparison.CurrentCulture))
            {
                StatusMessage.Text = "<span class='errorText'>Password & Confirm Password do not match!</span>";
            }

            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var result = manager.ChangePassword(this.Page.User.Identity.GetUserId(), TXtCurrentPassword.Text, TxtNewPassword.Text);
            if(result.Succeeded)
            {
                StatusMessage.Text = "<span class='errorText'>we have changed your password successfully!</span>";
            }
            else
            {
                StatusMessage.Text = "<span class='errorText'>Please try after some time, we are having issues!</span>";
            }

        }
        public ActionResult ChangePassword(string oldPassword, string newPassword, string re_newPassword)
        {
            UserManager um     = new UserManager();
            int         ses_id = (Session["user"] as User).Id;
            bool        sonuc  = false;

            sonuc = um.ChangePassword(ses_id, oldPassword, newPassword, re_newPassword);

            if (sonuc)
            {
                //ViewBag.Sonuc = "Parola Başarıyla Değiştirildi";
                //ViewBag.Color = "success";
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                TempData["Error"] = null;
                ViewBag.Error     = "ChangePassword";
                return(View("ErrorPage"));
            }
        }
Exemple #25
0
 protected void ChangePassword_Click(object sender, EventArgs e)
 {
     if (IsValid)
     {
         //新建账户管理对象
         UserManager manager = new UserManager();
         //调用UserManager的ChangePassword()方法,通过userid找到当前用户,修改密码。并将修改结果返回给result变量
         IdentityResult result = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text);
         if (result.Succeeded)                                       //如果修改成功
         {
             var user = manager.FindById(User.Identity.GetUserId()); //根据ID找到当前用户
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
             //重定向并 提示修改成功
         }
         else
         {
             AddErrors(result);
         }
     }
 }
Exemple #26
0
        private void btnChange_Click(object sender, EventArgs e)
        {
            string name = (string)this.listBox1.SelectedItem;

            if (name != null)
            {
                ChangePwd f = new ChangePwd(name);
                f.ShowDialog();

                if (f.DialogResult == DialogResult.OK)
                {
                    bool changed = UserManager.ChangePassword(f.Username, f.OldPassword, f.Password);
                    if (!changed)
                    {
                        MessageBox.Show("Failed to change password for " + f.Username);
                    }

                    RefreshList();
                }
            }
        }
Exemple #27
0
        public JsonResult AlterarSenha(string senhaAtual, string novaSenha)
        {
            var userId = User.Identity.GetUserId();

            var userStore   = new UserStore <IdentityUser>(new IdentityEntityContext());
            var userManager = new UserManager <IdentityUser>(userStore);

            var userValidator = new UserValidator <IdentityUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };

            userManager.UserValidator = userValidator;

            var result = userManager.ChangePassword(userId, senhaAtual, novaSenha);

            object resposta;

            if (result.Succeeded)
            {
                resposta = new
                {
                    response = "funcionou"
                };

                Usuario usuario = apl.SelecionarById(userId);

                usuario.Senha = novaSenha;
                apl.Alterar(usuario.Pessoa, usuario);
            }
            else
            {
                resposta = new
                {
                    response = result.Errors.ElementAt(0)
                };
            }

            return(Json(resposta));
        }
        public ActionResult DeleteAccount(DeleteAccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!User.Identity.Name.IsEqual(model.UserName))
                {
                    return(RedirectToAction("Manage", new { message = ManageMessageId.UserNameMismatch }));
                }
                else
                {
                    // require users to enter their password in order to execute account delete action
                    var user = UserManager.Find(User.Identity.Name, model.CurrentPassword);

                    if (user != null)
                    {
                        // execute delete action
                        if (UserHelper.DeleteUser(User.Identity.Name))
                        {
                            // delete email address and set password to something random
                            UserManager.SetEmail(User.Identity.GetUserId(), null);

                            string randomPassword = "";
                            using (SHA512 shaM = new SHA512Managed())
                            {
                                randomPassword = Convert.ToBase64String(shaM.ComputeHash(Encoding.UTF8.GetBytes(Path.GetRandomFileName())));
                            }

                            UserManager.ChangePassword(User.Identity.GetUserId(), model.CurrentPassword, randomPassword);

                            AuthenticationManager.SignOut();
                            return(View("~/Views/Account/AccountDeleted.cshtml"));
                        }

                        // something went wrong when deleting user account
                        return(View("~/Views/Error/Error.cshtml"));
                    }
                }
            }
            return(RedirectToAction("Manage", new { message = ManageMessageId.WrongPassword }));
        }
Exemple #29
0
        public IHttpActionResult ChangePassword(JObject form)
        {
            var     userName    = string.Empty;
            var     oldPassword = string.Empty;
            var     newPassword = string.Empty;
            dynamic jsonObject  = form;

            try
            {
                userName    = jsonObject.UserName.Value;
                oldPassword = jsonObject.OldPassword.Value;
                newPassword = jsonObject.NewPassword.Value;
            }
            catch
            {
                return(this.BadRequest("Incorrect call"));
            }
            var userContext = new ApplicationDbContext();
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));
            var userASP     = userManager.Find(userName, oldPassword);

            if (userASP == null)
            {
                return(this.BadRequest("Usuario y Password incorrecto"));
            }

            var response = userManager.ChangePassword(userASP.Id, oldPassword, newPassword);

            if (response.Succeeded)
            {
                return(this.Ok <object>(new
                {
                    Message = "El password ha sido cambiado exitosamente"
                }));
            }
            else
            {
                return(this.BadRequest(response.Errors.ToString()));
            }
        }
Exemple #30
0
        public ActionResult ChangePassWord(ChangePassWordViewModel model)
        {
            if (ModelState.IsValid)
            {
                //输入合法,进行修改
                bool changePwdSuccessed;
                try
                {
                    var userManage =
                        new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new EntityDbContext()));
                    var userName = (Session["loginUserSessionModel"] as LoginUserSessionModel).User.UserName;
                    var user     = userManage.Find(userName, model.PassWord);
                    if (user == null)
                    {
                        ModelState.AddModelError("", "原密码不正确");
                        return(View(model));
                    }
                    else
                    {
                        //修改密码
                        changePwdSuccessed = userManage.ChangePassword(user.Id, model.PassWord, model.ConFirmPassWord)
                                             .Succeeded;
                        if (changePwdSuccessed)
                        {
                            return(Content("<script>alert('修改成功!');location.href='" + Url.Action("login", "Account") + "'</script>"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "修改密码失败,请重试");
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "修改密码失败,请重试");
                }
            }

            return(View(model));
        }
Exemple #31
0
        public ActionResult Edit(ApplicationUser user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (user.Password != null)
                    {
                        UserManager.ChangePassword(user, user.Password);
                    }
                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                return(View(user));
            }

            return(View(user));
        }
        public bool ChangePassword(string userName, string newPassword, string oldPassword, out string errMsg)
        {
            errMsg = string.Empty;
            try
            {
                if (newPassword == oldPassword)
                {
                    throw new Exception("New password can not be the same as old password!");
                }

                IdentityUser   cUser  = _userMng.FindByName(userName);
                IdentityResult result = _userMng.ChangePassword(cUser.Id, oldPassword, newPassword);
                if (result.Errors.Count() > 0)
                {
                    foreach (string msg in result.Errors)
                    {
                        if (!string.IsNullOrEmpty(errMsg))
                        {
                            errMsg += Environment.NewLine + msg;
                        }
                        else
                        {
                            errMsg += msg;
                        }
                    }
                    throw new Exception(errMsg);
                }

                // password change compleled update last password change
                BLL.AccountMng accBll = new BLL.AccountMng();
                accBll.UpdateLastPasswordChange(cUser.Id);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
        public ActionResult ProfilePassword(Register model)
        {
            ApplicationUser info = UserManager.FindById(model.Id);

            if (model.Password == null || model.oldPassword == null || model.rePassword == null)
            {
                TempData["ErrorMessage"] = "Şifre alanı boş bırakılamaz.";
            }
            else
            {
                if (UserManager.Find(info.UserName, model.oldPassword) != null)
                {
                    if (model.Password.Equals(model.rePassword))
                    {
                        if (!model.Password.Equals(model.oldPassword))
                        {
                            if (ModelState.IsValid)
                            {
                                UserManager.ChangePassword(info.Id, model.oldPassword, model.Password);
                                TempData["User"] = info;
                            }
                        }
                        else
                        {
                            TempData["ErrorMessage"] = "Girdiğiniz şifre eskisiyle aynı.";
                        }
                    }
                    else
                    {
                        TempData["ErrorMessage"] = "Girdiğiniz şifreler uyuşmamaktadır.";
                    }
                }
                else
                {
                    TempData["ErrorMessage"] = "Girdiğiniz şifre doğru değil.";
                }
            }
            return(RedirectToAction("Profile", info));
        }
        protected void grvUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var row = grvUsers.Rows[e.RowIndex];
            var id = grvUsers.DataKeys[e.RowIndex].Value.ToString();

            var firstName = ((TextBox)row.FindControl("txtFirstName")).Text;
            var lastName = ((TextBox)row.FindControl("txtLastName")).Text;
            var email = ((TextBox)row.FindControl("txtEmail")).Text;
            var currentPassword = ((TextBox)row.FindControl("txtCurrentPassword")).Text;
            var newPassword = ((TextBox)row.FindControl("txtNewPassword")).Text;
            var role = ((DropDownList)row.FindControl("ddlRoleEdit")).Text;
            var jobClinic = ((DropDownList)row.FindControl("ddlJobClinicEdit")).Text; //TODO: Automatically edit RelationType (exept Writer) on files.
            var isActive = ((CheckBox)row.FindControl("chkIsActive")).Checked;

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = userManager.FindById(id);

            if (user != null && (
                userManager.FindById(SharedClass.CurrentUser).UserName == "Admin" ||
                user.UserName != "Admin"
                ))
            {
                if (newPassword != "")
                {
                    var result = userManager.ChangePassword(id, currentPassword, newPassword);
                }
                userManager.SetEmail(id, email);
                userManager.RemoveFromRoles(id, userManager.GetRoles(id).ToArray());
                userManager.AddToRole(id, role);

                using (Medical_Clinic_Entities mc = new Medical_Clinic_Entities())
                {
                    BSI__Clinic_Employee employee = mc.BSI__Clinic_Employees.Where(o => o.Id == id).First();
                    employee.First_Name = firstName;
                    employee.Last_Name = lastName;
                    employee.Job_Clinic = jobClinic;
                    employee.Is_Active = isActive;

                    mc.SaveChanges();
                }
            }
            grvUsers.EditIndex = -1;
        }