public void ResetPassword_OnClick(object sender, EventArgs args) { string newPassword; u = Membership.GetUser(UsernameTextBox.Text, false); if (u == null) { Msg.Text = "Username " + Server.HtmlEncode(UsernameTextBox.Text) + " not found. Please check the value and re-enter."; return; } try { newPassword = u.ResetPassword(AnswerTextBox.Text); } catch (MembershipPasswordException e) { Msg.Text = "Invalid password answer. Please re-enter and try again."; return; } catch (Exception e) { Msg.Text = e.Message; return; } if (newPassword != null) { Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword); } else { Msg.Text = "Password reset failed. Please re-enter your values and try again."; } }
protected void btnChangePassword_Click(object sender, EventArgs e) { try { MembershipUser theUser = Membership.GetUser(lblPopupUsername.Text); string tempPWD = theUser.ResetPassword(); theUser.ChangePassword(tempPWD, txtPopupNewPassword.Text); pnlChangePassword.Visible = false; pMessage.Clear(); pMessage.Add(Farschidus.Translator.AppTranslate["general.message.passwordChaneged"], Farschidus.Web.UI.Message.MessageTypes.Success); mShowMessage(pMessage); } catch (Exception ex) { pMessage.Clear(); pMessage.Add(ex.Message, Farschidus.Web.UI.Message.MessageTypes.Error); mShowMessage(pMessage); } }
public RedirectToRouteResult PasswordRecovery(string UserName, string Answer) { MembershipUser mu = Membership.GetUser(UserName); try { string newpassword = mu.ResetPassword(Answer); SmtpMailing mail = new SmtpMailing(); string body = newpassword + "<br /><br /><h2 style='font-family:Century Gothic; color:#4D679B; font-weight:bold; font-size:14px; margin:0 0 0 30px; padding-bottom:2px;'>Please use it to login and change it in PROFILE page.</h2>"; mail.SendMail(mu.Email, "Password Reset", "Your new password is", body, false); Session["Errors"] = "Your new password has been sent by email, please check your inbox."; return(RedirectToAction("Index")); } catch (Exception e) { Session["Errors"] = e.Message; } return(RedirectToAction("ForgotPassword")); }
public string CHANGE_PASSWORD(int pType, string pUser, string pOldPassword, string pNewPassword) { string res = "OK"; try { if (pType == TYPE_CHANGEPASSWORD) { MembershipUser user = Membership.GetUser(pUser); user.ChangePassword(pOldPassword, pNewPassword); } else if (pType == TYPE_RESETPASSWORD) { MembershipUser user = Membership.GetUser(pOldPassword); res = res + ":" + user.ResetPassword(); } } catch (Exception ex) { res = ex.Message; } return(res); }
protected void IdentityConfirmation(string userName, string passwordAnswer) { PreventDefault(); MembershipUser user = Membership.GetUser(userName); if (user != null) { string newPassword = user.ResetPassword(passwordAnswer); // create an email and send it to the user MailMessage message = new MailMessage(); message.To.Add(user.Email); message.Subject = String.Format("New password for \'{0}\'.", userName); message.Body = newPassword; SmtpClient client = new SmtpClient(); client.Send(message); // hide modal popup and display a confirmation Result.HideModal(); Result.ShowAlert("A new password has been emailed to the address on file."); } }
protected void bt_SaveResetPwd_Click(object sender, EventArgs e) { if (tbx_ConfirmPwd.Text.Length < 6) { MessageBox.Show(this, "密码长度必需大于6!"); return; } MembershipUser user = Membership.GetUser(lb_Username.Text, false); string pwd = user.ResetPassword(); if (!user.ChangePassword(pwd, tbx_ConfirmPwd.Text)) { MessageBox.Show(this, "输入的密码无效,密码修改失败!"); return; } Membership.UpdateUser(user); MessageBox.ShowAndRedirect(this, "密码重置成功!", "StaffList.aspx"); }
/// <summary> /// The user submitts an email to reset the password /// for the user account. /// The current password is encrypted in the email /// in order to be able to change the password. /// </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> /// <param name="data">The data.</param> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); MembershipUser membershipUser = Membership.GetUser(Sitecore.Context.Domain.Name + @"\" + form["UserName"]); if (membershipUser != null) { string newPassword = Membership.GeneratePassword(6, 0); string oldPwd = membershipUser.ResetPassword(); newPassword = newPassword.Replace("|", string.Empty); membershipUser.ChangePassword(oldPwd, newPassword); ICustomerManager <CustomerInfo> customerProvider = Context.Entity.Resolve <ICustomerManager <CustomerInfo> >(); CustomerInfo customerInfo = customerProvider.GetCustomerInfo(form["UserName"]); string email = customerInfo.Email; if (!Utils.MainUtil.IsValidEmailAddress(email)) { email = customerInfo.Email; } string key = form["UserName"] + "|" + newPassword; string encryptKey = Crypto.EncryptTripleDES(key, "5dfkjek5"); encryptKey = Uri.EscapeDataString(encryptKey); Item newPasswordLink = Utils.ItemUtil.GetNavigationLinkItem("New Password"); string url = Utils.ItemUtil.GetNavigationLinkPath(newPasswordLink) + "?key=" + encryptKey; var param = new { Recipient = email, URL = url }; IMail mailProvider = Context.Entity.Resolve <IMail>(); mailProvider.SendMail(MailTemplateNameResetYourPassword, param, string.Empty); } // No action is performed because of the security policies. }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { MembershipUser user = Membership.GetUser(username); if (user != null) { user.ResetPassword(password); status = MembershipCreateStatus.Success; } else { user = base.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status); if (status == MembershipCreateStatus.Success) { // Usermap.InsertUser(username); } } return(user); MembershipUser user1 = base.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status); if (status == MembershipCreateStatus.Success) { // Usermap.InsertUser(username); } return(user1); }
protected void btnReset_Click(object sender, EventArgs e) { Validate("User"); if (!IsValid) { return; } if (Request.QueryString["un"] != null) { MembershipUser user = Membership.GetUser(txtUserName.Text); if (user == null) { if (!string.IsNullOrEmpty(Common.SessionInfo.RedirectURL)) { Response.Redirect(Common.SessionInfo.RedirectURL, false); } else { Response.Redirect("UserAdministration.aspx", false); } } // Update Email user.Email = txtEmail.Text; Membership.UpdateUser(user); string oldPassword = user.ResetPassword(); //user.GetPassword(); if (oldPassword.Length > 0 && Password.Text.Length > 0) { if (user.ChangePassword(oldPassword, Password.Text)) { new bllAudit().Insert("Security", "Reset Password", "User:"******"Password has been reset.", MessageType.Information, this); } } } }
public static void ConvertAllClearPasswordsToEncrypted() { // Remember to change passwordFormat="Encrypted" in web.config's membership section String qry = "SELECT * FROM my_aspnet_users, my_aspnet_membership WHERE my_aspnet_users.id = my_aspnet_membership.userId"; DataTable dt_membership = SQL.SelectDataTable(qry, null, null); for (int i = 0; i < dt_membership.Rows.Count; i++) { String username = dt_membership.Rows[i]["name"].ToString(); String userid = dt_membership.Rows[i]["userId"].ToString(); String original_password = dt_membership.Rows[i]["Password"].ToString(); String password_format = dt_membership.Rows[i]["PasswordFormat"].ToString(); if (password_format == "0") { // Set user's new password type to encrypted String uqry = "UPDATE my_aspnet_membership SET PasswordFormat=2 WHERE userid=@userid"; SQL.Update(uqry, "@userid", userid); // Get user information MembershipUser user = Membership.GetUser(username); // If user is locked, temporarily unlock bool is_user_locked = user.IsLockedOut; if (is_user_locked) { uqry = "UPDATE my_aspnet_membership SET IsLockedOut=0 WHERE userid=@userid"; SQL.Update(uqry, "@userid", userid); } // Reset password (now encrypted) then replace with original user.ChangePassword(user.ResetPassword(), original_password); // Re-lock locked user if (is_user_locked) { uqry = "UPDATE my_aspnet_membership SET IsLockedOut=1 WHERE userid=@userid"; SQL.Update(uqry, "@userid", userid); } } } }
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "InitPwd") { // InitPwd string username = e.CommandArgument.ToString().Trim(); MembershipUser user = Membership.GetUser(username); if (user == null) { user = Membership.CreateUser(username, username); } if (user.IsLockedOut) { user.UnlockUser(); } string pwd = user.ResetPassword(); if (user.ChangePassword(pwd, username)) { // Response.Write("<script language='javascript'>alert('初始化密码为用户名成功!');</script>"); // DataBinder(); //LogUtil.Add( // String.Format("事件:用户{0}成功初始化了学生{1}的密码", Page.User.Identity.Name, user.UserName) // ); //JsUtil.MessageBox(this, "初始化密码为用户名成功!"); Succeed("初始化密码为用户名成功!"); } else { // Response.Write("<script language='javascript'>alert('初始化密码为用户名失败!');</script>"); //LogUtil.Add( // String.Format("事件:用户{0}初始化了学生{1}的密码失败", Page.User.Identity.Name, user.UserName) // ); this.Fail("初始化密码为用户名失败!"); } this.BindData(); } }
public ActionResult ResetPassword(string id) { UserManagementProvider _UserManagementRepo = new UserManagementProvider(); try { MembershipUser mbruser = Membership.GetUser(id); Guid userId = new Guid(mbruser.ProviderUserKey.ToString()); string UserFullName = _UserManagementRepo.GetAgentUserFullNameByUserID(userId); string password = mbruser.ResetPassword(); TempData["TemoResetPassword"] = password; mbruser.Comment = "MustChangePassword"; Membership.UpdateUser(mbruser); } catch (Exception ex) { TempData["ResponseMsg"] = "Password can not reset due to- " + ex.Message; } return(RedirectToAction("Index")); }
public String ResetPassword(string passwordAnswer) { String logMethodName = ".ResetPassword(string passwordAnswer) - "; _log.Debug(logMethodName + " - Begin Method"); MembershipUser user = GetUser(); String newPassword = null; try { newPassword = user.ResetPassword(passwordAnswer); } catch (Exception ex) { throw new SecurityAdapterException("An error has occured in the .NET Membership provider while calling MembershipUser.ResetPassword(passwordAnswer)", ex); } _log.Debug(logMethodName + " - End Method"); return(newPassword); }
public ActionResult EmployeReset(EmployeeModel employee) { string newPassword = Membership.GeneratePassword(6, 0); newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => "9"); if (employee != null) { MembershipUser user = Membership.GetUser(employee.Login); if (user != null) { string oldPassword = user.ResetPassword(); user.ChangePassword(oldPassword, newPassword); } else { Membership.CreateUser(employee.Login, newPassword); } return(Content("Пароль по умолчанию: " + newPassword)); } return(Content(bool.FalseString)); }
public ActionResult ResetPassword(ResetPasswordModel resetPasswordModel) { if (ModelState.IsValid) { //TODO: userId ignored as we only allow users to reset their own passwords MembershipUser currentUser = Membership.GetUser(resetPasswordModel.Username); if (currentUser != null) { currentUser.UnlockUser(); string newPassword = currentUser.ResetPassword(); SendPasswordResetEmail(currentUser.Email, newPassword); TempData["isSuccessReset"] = true; return(RedirectToAction("Logon")); } else { ModelState.AddModelError("Username", "Username not found."); } } return(View(resetPasswordModel)); }
protected void btnSend_Click(object sender, EventArgs e) { MembershipUser mu = Membership.GetUser(txtUser.Text); if (mu != null) { string newPassword = mu.ResetPassword(); WebMailing w = new WebMailing(); string body = File.ReadAllText(Path.Combine(HttpContext.Current.Server.MapPath(Config.MailTemplatePath), "newpassword.htm")); body = body.Replace("[NEW_PASSWORD]", newPassword); body = body.Replace("[USUARIO]", MembershipHelper.GetUser(mu.UserName).FullName); w.SendMail(mu.Email, "Cambio de Contraseña", "Cambio de Contraseña", body, false); Flash.Attributes["class"] = "flash_notice"; lblInfo.Text = "Su contraseña fue enviada con éxito."; } else { Flash.Attributes["class"] = "flash_alert"; lblInfo.Text = "El usuario ingresado es incorrecto"; } }
public bool SetTempPassword(string userName, string tempPassword) { try { MembershipUser user = Membership.GetUser(userName); if (user.ChangePassword(user.ResetPassword(), tempPassword) == false) { throw new Exception("Error changing password."); } user.LastActivityDate = DateTime.Now.AddMonths(-1); Membership.UpdateUser(user); return(true); } catch (Exception ex) { DBCommands.RecordError(ex); return(false); } }
/// <summary> /// Resetea el Password de un usuario /// </summary> /// <param name="userName">Nombre del Usuario</param> /// <param name="providerName">Nombre del proveedor de membership</param> /// <returns>Password auto generado</returns> public static String ResetUserPassword(String userName, string providerName) { String wNewPassword; SqlMembershipProvider wProvider = GetSqlMembershipProvider(providerName); MembershipUser wUser = GetMembershipUser(userName, wProvider.Name); // block the user if (wUser != null) { wNewPassword = wUser.ResetPassword(); } else { Fwk.Exceptions.TechnicalException te = new TechnicalException(string.Format(Fwk.Security.Properties.Resource.User_NotExist, userName)); ExceptionHelper.SetTechnicalException <FwkMembership>(te); te.ErrorId = "4005"; throw te; } return(wNewPassword); }
/// <summary> /// Modified By: Charlene Remotigue /// Date Modified: 03/03/2012 /// Description: add unlock user and reset password /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void uoUserList_ItemCommand(object sender, System.Web.UI.WebControls.ListViewCommandEventArgs e) { string strLogDescription; string strFunction; if (e.CommandName == "Delete") { UserAccountBLL.DeleteUser(e.CommandArgument.ToString()); DateTime dateNow = CommonFunctions.GetCurrentDateTime(); string sUserNameDeleted = e.CommandArgument.ToString(); //Insert log audit trail (Gabriel Oquialda - 17/11/2011) strLogDescription = "User account deleted. (flagged as inactive) " + sUserNameDeleted; strFunction = "uoUserList_ItemCommand"; BLL.AuditTrailBLL.InsertLogAuditTrail(0, "", strLogDescription, strFunction, Path.GetFileName(Request.Path), CommonFunctions.GetDateTimeGMT(dateNow), DateTime.Now, uoHiddenFieldUser.Value); GetUsers("", ""); } else if (e.CommandName == "Unlock") { MembershipUser mUser = Membership.GetUser(e.CommandArgument.ToString()); mUser.UnlockUser(); AlertMessage("User " + e.CommandArgument.ToString() + " successfully unlocked."); } else if (e.CommandName == "Reset") { MembershipUser mUser = Membership.GetUser(e.CommandArgument.ToString()); string str = mUser.ResetPassword(); string sEmail = mUser.Email.ToString(); SendEmail(e.CommandArgument.ToString(), sEmail, str); //AlertMessage("User password successfully reset. New password will be emailed to user."); AlertMessage("New password has been sent to " + mUser.Email + "."); } }
protected void btnPwd_Click(object sender, EventArgs e) { PasswordGenerator pg = new PasswordGenerator(); pg.ExcludeSymbols = true; pg.Exclusions = "0oABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$^*()-_=+[]{}\\|;:'\",./"; pg.Maximum = 10; pg.Minimum = 6; var list = Bmk.Find(Condition.Empty); foreach (var stu in list) { string xh = stu.xstbh.Trim(); MembershipUser user = Membership.GetUser(xh); if (user != null) { string oldPwd = user.ResetPassword(); stu.Password = pg.Generate(); stu.Save(); user.ChangePassword(oldPwd, stu.Password.Trim()); if (Roles.IsUserInRole(xh, "Students") == false) { Roles.AddUserToRole(xh, "Students"); } } else { stu.Password = pg.Generate(); stu.Save(); Membership.CreateUser(xh, stu.Password.Trim()); if (Roles.IsUserInRole(xh, "Students") == false) { Roles.AddUserToRole(xh, "Students"); } } } this.BindData(); }
public ActionResult AdminResetPassword(string user) { if (ModelState.IsValid && Roles.IsUserInRole("Administrator")) { MembershipUser currentUser = System.Web.Security.Membership.GetUser(user); string newpassword = currentUser.ResetPassword(); //Send email to user with new password try { EmailOutbox outEmail = db.EmailOutboxes.Where(s => s.purpose == "password reset").FirstOrDefault(); string fromAddress = outEmail.emailAddress; //"*****@*****.**"; string fromName = outEmail.emailName; string password = outEmail.emailPassword; //"Parcmen!"; string emailBody = "Your password for the Pocket Job Coach has been reset to the temporary password '" + newpassword + "'. Please login and change your password now at http://pjc.gear.host"; string server = outEmail.smtpServerName; //"smtp.gmail.com"; int port = outEmail.portNumber; int timeout = outEmail.smtpTimeout; Email.send(fromAddress, fromName, currentUser.Email, "Pocket Job Coach Password Reset", emailBody, password, server, port, timeout); Response.Redirect("~/Account/List"); } catch (Exception e) { db.Debugs.Add(new Debug() { debugMessage = e.ToString().Substring(0, 199) }); db.SaveChanges(); Response.Redirect("~/Unauthorized"); } ModelState.AddModelError("", "Password has been reset for " + currentUser.UserName); } else { Response.Redirect("~/Unauthorized"); } return(View()); }
public ActionResult ResetPassword(string id) { int Agentid = (int)TempData["AgentId"]; try { MembershipUser mbruser = Membership.GetUser(id); Guid userId = new Guid(mbruser.ProviderUserKey.ToString()); string UserFullName = _UserManagementRepo.GetAgentUserFullNameByUserID(userId); string password = mbruser.ResetPassword(); TempData["TemoResetPassword"] = password; mbruser.Comment = "MustChangePassword"; Membership.UpdateUser(mbruser); return(RedirectToAction("Index", "AgentUserManagement", new { @id = Agentid })); } catch (Exception ex) { TempData["ResponseMsg"] = "Email Cannot sent due to error - " + ex.Message; return(RedirectToAction("Index", "AgentUserManagement", new { @id = Agentid })); } }
public void PasswordRecovery() { if (this.Request.Form.Count > 0) { string login = this.Request.Form["Login"]; MembershipUser requestUser = Membership.GetUser(login); if (requestUser != null) { ViewData["NewPassword"] = requestUser.ResetPassword(); RenderView("PasswordRecovery", ViewData); } else { ViewData["Failur"] = true; RenderView("PasswordRecovery", ViewData); } } else { RenderView("PasswordRecovery"); } }
public ActionResult ForgotMyPassword(UserClass uc, string ConfirmPassword) { if (string.IsNullOrWhiteSpace(uc.UserName)) { ViewBag.resetPasswordMessage = "Lütfen kullanıcı adını giriniz."; return(View(uc)); } MembershipUser mu = Membership.GetUser(uc.UserName); if (mu == null) { ViewBag.resetPasswordMessage = "Kullanıcı adı yanlıştır."; return(View(uc)); } if (uc.Password != ConfirmPassword) { ViewBag.resetPasswordMessage = "Şifreler aynı değil"; return(View(uc)); } if (mu.PasswordQuestion == uc.PasswordQuestion) { string oldnewPwd = mu.ResetPassword(uc.PasswordAnswer); if (oldnewPwd != null) { mu.ChangePassword(oldnewPwd, uc.Password); ViewBag.Message = "Şifre başarıyla değiştirildi."; } } else { ViewBag.resetPasswordMessage = "Girilen bilgiler yanlıştır."; } return(View(uc)); }
protected void btnChangePassword_Click(object sender, EventArgs e) { MembershipUser user = Membership.GetUser(txtMANR.Text); if (user == null) { ChangePasswordMessage("Brugeren findes ikke", true); } else { if (txtPassword.Text != txtPassword2.Text) { ChangePasswordMessage("Begge passwords skal være ens", true); } else { if (txtPassword.Text.Length < 6) { ChangePasswordMessage("Password skal være minimum 6 tegn", true); } else { bool passwordChanged = user.ChangePassword(user.ResetPassword(), txtPassword.Text); if (passwordChanged) { ChangePasswordMessage("Password ændret", false); txtPassword.Text = String.Empty; txtPassword2.Text = String.Empty; } else { ChangePasswordMessage("Der skete en fejl. Prøv igen", true); } } } } }
public static void ResetUserAccount(string username, string password) { //Disable security in case the user is running in a limited user capacity using (new SecurityDisabler()) { Account a = Account.FromName(username, AccountType.User); if (a != null) { MembershipUser user = Membership.GetUser(a.Name); // Enable the Account if (!user.IsApproved) { user.IsApproved = true; Membership.UpdateUser(user); } // Reset the password user.ChangePassword(user.ResetPassword(), password); } } }
protected void btnReset_Click(object sender, EventArgs e) { if (ddlUser.SelectedIndex > 0 && txtPassword.Text.Trim() != "") { try { MembershipUser user = Membership.GetUser(ddlUser.SelectedItem.Text.Trim(), false); user.ChangePassword(user.ResetPassword(), txtPassword.Text.Trim()); string str = ddlUser.SelectedItem.Text.Trim() + " password has changed successfully"; ClientScript.RegisterStartupScript(GetType(), "success", "<script>alert('" + str + "')</script>"); } catch (Exception ex) { ClientScript.RegisterStartupScript(GetType(), "Error", "<script>alert('" + ex.Message.ToString() + "')</script>"); } btnClear_Click(sender, e); } else { ClientScript.RegisterStartupScript(GetType(), "Information", "<script>alert('Please Verify User Name and Password')</script>"); } }
public ActionResult NewOrEdit(User model, string password) { try { string mess = ""; var db = DB.Entities; if (model.ID == 0) { MembershipUser aspnetUser = Membership.CreateUser(model.UserName, password, model.Email); Guid userCreated = (Guid)aspnetUser.ProviderUserKey; if (userCreated != null) { model.AspnetUserID = userCreated; // Add new db.User.AddObject(model); mess = "Thêm mới tài khoản thành công"; } } else { // Edit if (!string.IsNullOrEmpty(password)) { MembershipUser aspnetUser = Membership.GetUser(model.UserName); bool isSuccess = aspnetUser.ChangePassword(aspnetUser.ResetPassword(), password); } db.AttachTo("User", model); db.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Modified); mess = "Sửa tài khoản thành công"; } db.SaveChanges(); return(RedirectToAction("Index", new { message = mess })); } catch { SelectOption(model); return(View(model)); } }
protected void ButtonReset_Click(object sender, EventArgs e) { try { HiddenField hf = (HiddenField)DetailsView1.FindControl("HFUserName"); MembershipUser currUser = Membership.Providers["MySqlMembershipProviderReset"].GetUser(hf.Value.ToString(), false); currUser.ChangePassword(currUser.ResetPassword(), "CC_password1"); currUser.Comment = "CHANGEPASS"; if (currUser.IsLockedOut == true) { currUser.UnlockUser(); } //LiteralConfirm.Text = "Password is: " + u.GetPassword(); LabelResponse.Text = "Password Reset to 'CC_password1'."; messaging.SendEmail(currUser.Email.ToString(), "Password Reset", "Password has been reset, new password is CC_password1"); } catch (Exception ex) { LabelResponse.Text = "Error: " + ex.ToString(); } }
public JsonResult ModifyPassword(ModifyPasswordModel ModelInfo) { try { bool b = GlobalController.ValidateUser(this.User.Identity.Name, ModelInfo.OldPassword); if (!b) { return(Json(ReturnInfo.Error("旧密码错误!"))); } else { MembershipUser MembershipUser = Membership.GetUser(this.User.Identity.Name); string NewRandomPassword = MembershipUser.ResetPassword(); MembershipUser.ChangePassword(NewRandomPassword, ModelInfo.NewPassword); return(Json(ReturnInfo.Success(string.Empty))); } } catch (Exception ex) { return(Json(ReturnInfo.Error(ex.Message), JsonRequestBehavior.AllowGet)); } }
public ActionResult ForgotPassword(string email) { string username = Membership.GetUserNameByEmail(email); if (String.IsNullOrEmpty(username)) { ViewBag.Fail = "Email này không tồn tại trong hệ thống"; } else { try { MembershipUser currentUser = Membership.GetUser(username); string newpass = currentUser.ResetPassword(); MailMessage message = new MailMessage(); message.From = new System.Net.Mail.MailAddress("*****@*****.**"); message.To.Add(new System.Net.Mail.MailAddress(email)); message.IsBodyHtml = true; message.BodyEncoding = Encoding.UTF8; message.Subject = "Lấy lại mật khẩu"; message.Body = "Chào <b>" + username + "</b>,<br />Mật khẩu mới: " + newpass + "<br/><br/>Hệ thống tra cứu thuật ngữ hành chính văn phòng và hoạt động xã hội."; SmtpClient client = new SmtpClient(); client.Send(message); ViewBag.Success = "Mật khẩu mới đã được gửi về email của bạn!"; } catch { ViewBag.Fail = "Lấy lại mật khẩu không thành công, email không hợp lệ!"; } } return(View()); }