public void UpdateUser() { string userName = UserNameTextBox.Text; MembershipUser user = Membership.GetUser(userName); if (PasswordTextBox.Text != user.GetPassword()) { user.ChangePassword(user.GetPassword(), PasswordTextBox.Text); Membership.UpdateUser(user); } if (PasswordQuestionTextBox.Text.Length > 0 && PasswordAnswerTextBox.Text.Length > 0) { user.ChangePasswordQuestionAndAnswer(user.GetPassword(), PasswordQuestionTextBox.Text, PasswordAnswerTextBox.Text); Membership.UpdateUser(user); } user.Comment = CommentTextBox.Text; user.Email = EmailTextBox.Text; user.IsApproved = IsApprovedCheckBox.Checked; Membership.UpdateUser(user); //user.LastActivityDate //user.LastLoginDate if (IsLockedOutCheckBox.Checked != user.IsLockedOut) { user.UnlockUser(); Membership.UpdateUser(user); } LoadUser(userName); RiseUpdated(new UserEditEventArgs(userName)); }
public ViewResult ChangeAnswer(UserFull userModification) { UserAnswer userAnswer = new UserAnswer(userModification); var errors = userAnswer.Validate(); if (errors == null) { MembershipUser mu = Membership.GetUser(); if (!mu.ChangePasswordQuestionAndAnswer(userAnswer.Password, securityQuestionRepository.Get(userModification.SecurityQuestion).Description, userAnswer.SecurityAnswer)) { errors = new ErrorSummary(); errors.RegisterErrorMessage("SecurityQuestion", "There was an error while we was updating your security answer, please check your password and try again."); } else { userModification.Alert = "User security question and answer changed successfully"; } } if (errors != null) { Session["Errors"] = errors.ErrorMessages; } userModification.Tab = 3; userModification = GetAccountData(userModification); return(View("Index", userModification)); }
public ActionResult ChangePassword(string UserName, string currentPassword, string newPassword, string confirmPassword, string newSecurityQuestion, string newSecurityAnswer) { Security_Users viewSecurity_Users = new Security_Users(); viewSecurity_Users.username = UserName; // Basic parameter validation if (String.IsNullOrEmpty(currentPassword)) { ViewData.ModelState.AddModelError("currentPassword", "You must specify a current password."); } if (newPassword == null || newPassword.Length < Provider.MinRequiredPasswordLength) { ViewData.ModelState.AddModelError("newPassword", String.Format(CultureInfo.InvariantCulture, "You must specify a new password of {0} or more characters.", Provider.MinRequiredPasswordLength)); } if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal)) { ViewData.ModelState.AddModelError("newPassword", "The new password and confirmation password do not match."); } if (ViewData.ModelState.IsValid) { // Attempt to change password MembershipUser currentUser = Provider.GetUser(User.Identity.Name, true /* userIsOnline */); bool changeSuccessful = false; bool changeQuestionSuccessful = false; try { changeSuccessful = currentUser.ChangePassword(currentPassword, newPassword); changeQuestionSuccessful = currentUser.ChangePasswordQuestionAndAnswer(newPassword, newSecurityQuestion, newSecurityAnswer); } catch { // An exception is thrown if the new password does not meet the provider's requirements } if (changeSuccessful) { if (changeQuestionSuccessful) { return(RedirectToAction("ChangePasswordSuccess", "Security")); } else { ViewData.ModelState.AddModelError("newSecurityQuestion", "The new security question/answer combination was not accepted. Please try again."); } } else { ViewData.ModelState.AddModelError("password", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form return(View(viewSecurity_Users)); }
protected virtual void UpdateMyAccount(string userName, string oldPassword, string password, string confirmPassword, string email, string passwordQuestion, string passwordAnswer) { PreventDefault(); MembershipUser user = Membership.GetUser(userName); if (user != null) { if (String.IsNullOrEmpty(oldPassword)) { Result.ShowAlert(Localize("EnterCurrentPassword", "Please enter your current password."), "OldPassword"); return; } if (!(Membership.ValidateUser(userName, oldPassword))) { Result.ShowAlert(Localize("PasswordDoesNotMatchRecords", "Your password does not match our records."), "OldPassword"); return; } if (!(String.IsNullOrEmpty(password)) || !(String.IsNullOrEmpty(confirmPassword))) { if (password != confirmPassword) { Result.ShowAlert(Localize("NewPasswordAndConfirmatinDoNotMatch", "New password and confirmation do not match."), "Password"); return; } if (!(user.ChangePassword(oldPassword, password))) { Result.ShowAlert(Localize("NewPasswordInvalid", "Your new password is invalid."), "Password"); return; } } if (email != user.Email) { user.Email = email; Membership.UpdateUser(user); } if (user.PasswordQuestion != passwordQuestion && String.IsNullOrEmpty(passwordAnswer)) { Result.ShowAlert(Localize("EnterPasswordAnswer", "Please enter a password answer."), "PasswordAnswer"); return; } if (!(String.IsNullOrEmpty(passwordAnswer))) { user.ChangePasswordQuestionAndAnswer(oldPassword, passwordQuestion, passwordAnswer); Membership.UpdateUser(user); } Result.HideModal(); } else { Result.ShowAlert(Localize("UserNotFound", "User not found.")); } }
protected void ButtonQa_Click(object sender, EventArgs e) { try { MembershipUser mu = Membership.GetUser(); mu.ChangePasswordQuestionAndAnswer(txtpswqa.Text, txtquestion.Text, txtanswer.Text); Response.Redirect("homepage.aspx"); } catch (Exception ex) { lblQa.Text = ex.Message; } lblQa.Visible = true; }
public void CreateUser() { MembershipUser user = null; CreatedUserTextBox.Text = ""; string userName = UserNameTextBox.Text; Guid userId = new Guid(UserIdTextBox.Text); try { MembershipCreateStatus mcStatus; user = Membership.CreateUser(userName, PasswordTextBox.Text, EmailTextBox.Text, null, null, IsApprovedCheckBox.Checked, userId, out mcStatus); } catch (Exception ex) { CreateStatusLabel.ForeColor = System.Drawing.Color.Red; CreateStatusLabel.Text = ex.Message; } if (user != null) { user.Comment = CommentTextBox.Text; user.IsApproved = IsApprovedCheckBox.Checked; if ((PasswordQuestionTextBox.Text.Length > 0) && (PasswordAnswerTextBox.Text.Length > 0)) { user.ChangePasswordQuestionAndAnswer(PasswordTextBox.Text, PasswordQuestionTextBox.Text, PasswordAnswerTextBox.Text); } CreateStatusLabel.ForeColor = System.Drawing.Color.Green; CreateStatusLabel.Text = "User '" + user.UserName + "' was created."; CreatedUserTextBox.Text = userName; switch (PostCreateMode) { case PostCreateModeEnum.None: break; case PostCreateModeEnum.Create: PrepareToCreate(); break; case PostCreateModeEnum.Update: PrepareToUpdate(); LoadUser(userName); break; default: break; } RiseCreated(new UserEditEventArgs(user)); } }
private void ChangePasswordQAHelper(MembershipUser user, string pw, string newQ, string newA) { try { user.ChangePasswordQuestionAndAnswer(pw, newQ, newA); } catch (ArgumentNullException ane) { Assert.Equal("password", ane.ParamName); } catch (ArgumentException) { Assert.NotNull(pw); } }
protected void btnChangeQuestion_Click(object sender, EventArgs e) { lblMessage.Visible = false; if (user.ChangePasswordQuestionAndAnswer(tbCurrentPassword.Text, dlistPasswordQuestion.SelectedValue, tbPasswordAnswer.Text)) { lblMessage.Visible = true; lblMessage.ForeColor = GREEN; lblMessage.Text = STR_PASSWORD_QUESTION_CHANGED_MESSAGE; } else { lblMessage.Visible = true; lblMessage.ForeColor = RED; lblMessage.Text = STR_PASSWORD_QUESTION_FAILED_MESSAGE; } }
protected void btnSaveSQ_Click(object sender, EventArgs e) { MembershipUser mu = Membership.GetUser(Utility.GetUserName()); if (mu.ChangePasswordQuestionAndAnswer(txtCurPass.Text, txtSecQuest.Text, txtSecAnswer.Text)) { lblSQresult.Text = "Security Question Saved!"; } else { lblSQresult.Text = "Error: Question could not be saved! Check Password"; } btnContinueSQ.Visible = true; btnSaveSQ.Visible = false; btnCancelSQ.Visible = false; LoadUser(); }
void IMembershipManager.UpdateUser(string application, string userName, string email, string oldAnswer, string newQuestion, string newAnswer, bool isApproved, bool isLockedOut) { Membership.ApplicationName = application; MembershipUser membershipUser = Membership.GetUser(userName); membershipUser.Email = email; membershipUser.IsApproved = isApproved; if (isLockedOut == false) { membershipUser.UnlockUser(); } if (Membership.EnablePasswordRetrieval) { string password = membershipUser.GetPassword(oldAnswer); membershipUser.ChangePasswordQuestionAndAnswer(password, newQuestion, newAnswer); } Membership.UpdateUser(membershipUser); }
public ViewResult ChangeAnswer(UserFull userModification) { UserAnswer userAnswer = new UserAnswer(userModification); if (ModelState.IsValid) { MembershipUser mu = Membership.GetUser(); if (mu.ChangePasswordQuestionAndAnswer(userAnswer.Password, securityQuestionRepository.Get(userModification.SecurityQuestion).Description, userAnswer.SecurityAnswer)) { userModification.Alert = "User security question and answer changed successfully"; } else { ModelState.AddModelError("Password", "The password dont match"); } } userModification.Tab = 3; userModification = GetAccountData(userModification); return(View("Index", userModification)); }
public void ChangePasswordQuestionAndAnswer() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "*****@*****.**", "color", "blue", true, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); MembershipUser user = Membership.GetUser("foo"); ChangePasswordQAHelper(user, "", "newQ", "newA"); ChangePasswordQAHelper(user, "barbar!", "", "newA"); ChangePasswordQAHelper(user, "barbar!", "newQ", ""); ChangePasswordQAHelper(user, null, "newQ", "newA"); bool result = user.ChangePasswordQuestionAndAnswer("barbar!", "newQ", "newA"); Assert.IsTrue(result); user = Membership.GetUser("foo"); Assert.AreEqual("newQ", user.PasswordQuestion); }
protected void btnChangePassword_Click(object sender, EventArgs e) { try { MembershipUser user = Membership.GetUser(User.Identity.Name); if (!Membership.ValidateUser(user.UserName, tbCurrentPassword.Text)) { tbCurrentPassword.ErrorText = "Contraseña Anterior Incorrecta"; tbCurrentPassword.IsValid = false; } else if (!user.ChangePassword(tbCurrentPassword.Text, tbPassword.Text)) { tbPassword.ErrorText = "Nueva Contraseña no Válida."; tbPassword.IsValid = false; } else { if (Check_CambiarPregunta.Checked == true) { if (BootstrapComboBox_Pregunta_Change.Text == "" || BootstrapTextBox_Respuesta_Change.Text == "") { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msj", "alert(Debe seleccionar una Pregunta y Respuesta Secreta);", true); return; } if (!user.ChangePasswordQuestionAndAnswer(tbPassword.Text, BootstrapComboBox_Pregunta_Change.Text, BootstrapTextBox_Respuesta_Change.Text.Trim())) { } else { Response.Redirect("~/"); } } Response.Redirect("~/"); } } catch (Exception Ex) { FG.Controlador_Error(Ex, Page.Response); } }
public void ChangePasswordQuestion_OnClick(object sender, EventArgs args) { try { MembershipUser u = Membership.GetUser(); Boolean result = u.ChangePasswordQuestionAndAnswer(PasswordTextbox.Text, QuestionTextbox.Text, AnswerTextbox.Text); if (result) { Msg.Text = "Password Question and Answer changed."; } else { Msg.Text = "Password Question and Answer change failed."; } } catch (Exception e) { Msg.Text = "Change failed. Please re-enter your values and try again."; } }
public override TUser Update(TUser instance) { var user = (TUser)instance; base.Update(instance); if (user.Profile != null) { var exist = ProfileBase <TProfile> .Select(user.Id); if (exist == null) { user.Profile.UserId = user.Id; user.Profile.Insert(); } user.Profile.Update(); } else { user.Profile.Delete(); } MembershipUser u = null; if (!string.IsNullOrWhiteSpace(user.InputNewPassword)) { u = Membership.GetUser(user.Id); u.ChangePassword(user.InputOldPassword, user.InputNewPassword); } if (!string.IsNullOrWhiteSpace(user.InputNewPasswordQuestion)) { if (u == null) { u = Membership.GetUser(user.Id); } u.ChangePasswordQuestionAndAnswer(u.GetPassword(), user.InputNewPasswordQuestion, user.InputNewPasswordAnswer); } return(user); }
protected void buttonChangeQuestionAnswer_Click(object sender, EventArgs e) { //if (Page.IsValid) //{ string password = "", question = "", answer = ""; TextBox txt = (TextBox)ChangePassword1.Controls[0].FindControl("CurrentPassword"); password = txt.Text; HiddenField hf = (HiddenField)ChangePassword1.Controls[0].FindControl("txtQuestion"); question = hf.Value; txt = (TextBox)ChangePassword1.Controls[0].FindControl("Answer"); answer = txt.Text; MembershipUser mu = Membership.GetUser(); if (mu.ChangePasswordQuestionAndAnswer(password, question, answer)) { Response.Redirect("~/Account/Manage.aspx?m=SetQuestionSuccess"); } //} }
void IUserStore.UpdateUser(IUser pUser) { this.Log("username:"******"Could not find user with user name '" + pUser.GetUsername() + "' in the user store."); } if (!user.PasswordQuestion.Equals(pUser.GetSecretQuestion())) { string password = pUser.GetPassword(); if ((password == null) || password.Equals("")) { throw new Exception("To change secret question and answer, original password must be provided."); } user.ChangePasswordQuestionAndAnswer(pUser.GetPassword(), pUser.GetSecretQuestion(), pUser.GetSecretAnswer()); user = this._innerMemProvider.GetUser(pUser.GetUsername(), false); } user.Email = pUser.GetEmail(); this._innerMemProvider.UpdateUser(user); }
public override bool ChangePasswordQuestionAndAnswer(string password, string newPasswordQuestion, string newPasswordAnswer) { return(_innerUser.ChangePasswordQuestionAndAnswer(password, newPasswordQuestion, newPasswordAnswer)); }
protected void lbtnNextStep_Click(object sender, EventArgs e) { try { bool password = txtPassword.Text == txtConfirmPassword.Text; bool answer = txtAnswer.Text == txtConfirmAnswer.Text; if (!password) { lblError.Text = "Въведените пароли не съвпадат."; return; } if (password && answer) { if (hdnEditAccountSecutiry.Value == "") //New Account { DictionaryModel.Account account = new DictionaryModel.Account(); MembershipCreateStatus status; MembershipUser user = Membership.CreateUser(DateTime.Now.ToString("ddhhmmssfff"), txtPassword.Text, txtEmail.Text.Trim().ToLower(), txtQuestion.Text.Trim(), txtAnswer.Text.Trim(), chkApproved.Checked, out status); if (status != MembershipCreateStatus.Success) { switch (status) { case MembershipCreateStatus.DuplicateEmail: lblError.Text = "Въведеният Email адрес е зает."; break; case MembershipCreateStatus.DuplicateProviderUserKey: lblError.Text = "Дублиращ се потребителски код."; break; case MembershipCreateStatus.DuplicateUserName: lblError.Text = "Въведеното потребителско име е заето."; break; case MembershipCreateStatus.InvalidAnswer: lblError.Text = "Въведохте невалиден отговор на тайният въпрос."; break; case MembershipCreateStatus.InvalidEmail: lblError.Text = "Въведохте невалиден Email адрес."; break; case MembershipCreateStatus.InvalidPassword: lblError.Text = "Въведохте невалидна парола."; break; case MembershipCreateStatus.InvalidProviderUserKey: lblError.Text = "Невалиден потретбителски код."; break; case MembershipCreateStatus.InvalidQuestion: lblError.Text = "Веведохте невалиден таен въпрос."; break; case MembershipCreateStatus.InvalidUserName: lblError.Text = "Въведохте невалидно потребителско име."; break; case MembershipCreateStatus.ProviderError: lblError.Text = "Възникна грешка, моля опитайте отново."; break; case MembershipCreateStatus.UserRejected: lblError.Text = "Вашият профил е спрян."; break; default: break; } return; } user.IsApproved = chkApproved.Checked; user.Comment = txtReminder.Text; Membership.UpdateUser(user); Roles.AddUserToRole(user.UserName, "User"); account.ASPNETID = (Guid)user.ProviderUserKey; account.FirstName = string.Empty; account.LastName = string.Empty; entities.Accounts.AddObject(account); entities.SaveChanges(); if (StepCompleted != null) { NewAccountStepCompletedEventArgs args = new NewAccountStepCompletedEventArgs(NewAccountWizardSteps.AccountSecurity); Session["SetupASPNETID"] = args.ASPNETID = account.ASPNETID; Session["SetupAcountId"] = args.CurrentAccountId = account.Id; StepCompleted.Invoke(this, args); //HideEditAddControls(); } } else //Edit Account { MembershipUser user = Membership.GetUser(SetupASPNETID); user.ChangePasswordQuestionAndAnswer(txtPassword.Text, txtQuestion.Text, txtAnswer.Text); user.Comment = txtReminder.Text; user.IsApproved = chkApproved.Checked; Membership.UpdateUser(user); hdnEditAccountSecutiry.Value = null; HideEditAddControls(); if (StepCompleted != null) { NewAccountStepCompletedEventArgs args = new NewAccountStepCompletedEventArgs(NewAccountWizardSteps.AccountSecurity); args.ASPNETID = (Guid)user.ProviderUserKey; StepCompleted.Invoke(this, args); } } } else { lblError.Text = "Въведените отговори на тайният въпрос не съвпадат."; } } catch (Exception ex) { lblError.Text = ex.Message;// "Възникна проблем, моля опитайте по-късно."; } }
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { try { CreateUserWizard1.UserName = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("UserName")).Text; user = Membership.GetUser(CreateUserWizard1.UserName); user.ChangePasswordQuestionAndAnswer(user.GetPassword(), "1", "1"); user.IsApproved = true; user.Comment = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Corp")).Text; Roles.AddUserToRole(CreateUserWizard1.UserName, "user"); Membership.UpdateUser(user); p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true); p.UserProfile.Owner = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; p.UserProfile.Name = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; p.UserProfile.Tel = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Tel")).Text; p.UserProfile.Corp = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Corp")).Text; p.UserProfile.City = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedValue; p.UserProfile.Postcode = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue; p.UserProfile.Address = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Address")).Text; p.UserProfile.Fax = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Fax")).Text; p.UserProfile.Kind = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("Kind")).SelectedValue; p.UserProfile.Type = "1"; p.UserProfile.Zipcht = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedItem.Text + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedItem.Text; p.Save(); /* UserProfiles */ UserProfiles up = new UserProfiles(); up.Username = CreateUserWizard1.UserName; up.Owner = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; up.Name = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; up.Tel = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Tel")).Text; up.Corp = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Corp")).Text; up.City = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedValue; up.Postcode = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue; up.Address = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Address")).Text; up.Fax = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Fax")).Text; up.Kind = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("Kind")).SelectedValue; up.Type = "1"; up.Zipcht = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedItem.Text + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedItem.Text; String sqlUp = ""; sqlUp = sqlUp + " insert into UserProfiles ([address],[city],[corp],[fax] ,[kind],[name],[owner],[postcode],[tel],[type],[username],[zipcht]) "; sqlUp = sqlUp + " values (@address,@city,@corp,@fax ,@kind,@name,@owner,@postcode,@tel,@type,@username,@zipcht)"; //sqlUp = sqlUp + " insert into UserProfiles ([address],[city],[corp],[fax],[kind],[name],[owner],[postcode],[tel],[type],[username],[zipcht]) "; //sqlUp = sqlUp + " values (@address,@city,@corp,@fax,@kind,@name,@owner,@postcode,@tel,@type,@username,@zipcht) "; OleDbCommand cmdM = new OleDbCommand(sqlUp); cmdM.Parameters.Add("@address", OleDbType.VarChar).Value = up.Address; cmdM.Parameters.Add("@city", OleDbType.VarChar).Value = up.City; cmdM.Parameters.Add("@corp", OleDbType.VarChar).Value = up.Corp; cmdM.Parameters.Add("@fax", OleDbType.VarChar).Value = up.Fax; cmdM.Parameters.Add("@kind", OleDbType.VarChar).Value = up.Kind; cmdM.Parameters.Add("@name", OleDbType.VarChar).Value = up.Name; cmdM.Parameters.Add("@owner", OleDbType.VarChar).Value = up.Owner; cmdM.Parameters.Add("@postcode", OleDbType.VarChar).Value = up.Postcode; cmdM.Parameters.Add("@tel", OleDbType.VarChar).Value = up.Tel; cmdM.Parameters.Add("@type", OleDbType.VarChar).Value = up.Type; cmdM.Parameters.Add("@username", OleDbType.VarChar).Value = up.Username; cmdM.Parameters.Add("@zipcht", OleDbType.VarChar).Value = up.Zipcht; cmdM.CommandType = CommandType.Text; //SQLUtil.ExecuteSql(cmdM); object objUserProfile = SQLUtil.ExecuteScalar(cmdM); //mgr.Save(null, null, up); ((Label)CompleteWizardStep1.ContentTemplateContainer.FindControl("Msg")).Text = "學研機構會員新增完成。"; } catch (Exception err) { Membership.DeleteUser(CreateUserWizard1.UserName, true); ((Label)CompleteWizardStep1.ContentTemplateContainer.FindControl("Msg")).Text = "錯誤: " + err.ToString(); } }
public bool ChangePasswordQuestionAndAnswer(string oldAnswer, string newQuestion, string newAnswer) { return(MembershipUser.ChangePasswordQuestionAndAnswer(oldAnswer, newQuestion, newAnswer)); }
public bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { MembershipUser user = Membership.GetUser(username); return(user.ChangePasswordQuestionAndAnswer(password, newPasswordQuestion, newPasswordAnswer)); }
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { try { CreateUserWizard1.UserName = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("UserName")).Text; user = Membership.GetUser(CreateUserWizard1.UserName); user.ChangePasswordQuestionAndAnswer(user.GetPassword(), "2", "2"); user.IsApproved = false; user.Comment = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Corp")).Text; Roles.AddUserToRole(CreateUserWizard1.UserName, "user"); Membership.UpdateUser(user); p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true); p.UserProfile.Name = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; p.UserProfile.Owner = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Owner")).Text; p.UserProfile.Tel = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Tel")).Text; p.UserProfile.Corp = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Corp")).Text; p.UserProfile.City = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedValue; p.UserProfile.Postcode = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue; p.UserProfile.Address = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Address")).Text; p.UserProfile.Fax = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Fax")).Text; p.UserProfile.Kind = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("Kind")).SelectedValue; p.UserProfile.Type = "2"; p.UserProfile.Zipcht = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedItem.Text + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedItem.Text; p.Save(); ReuseTech obj = new ReuseTech(); obj.Username = CreateUserWizard1.UserName; obj.Techitem = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("TechItem")).SelectedValue; if (!obj.Techitem.Equals("V")) { obj.Techother = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("TechItem")).SelectedItem.Text; } else { obj.Techother = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("TechOther")).Text; } obj.Techname = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("TechName")).Text; obj.Wasteitem = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("WasteItem")).SelectedValue; if (!obj.Wasteitem.Equals("U")) { obj.Wasteother = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("WasteItem")).SelectedItem.Text; } else { obj.Wasteother = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("WasteOther")).Text; } obj.Wastename = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("WasteName")).Text; obj.Reusename = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("ReuseName")).Text; //obj.Researchitem = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("ResearchItem")).SelectedValue; //obj.Patent = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Patent")).Text; //obj.Techadv = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("TechAdv")).Text; //obj.Techdesc = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("TechDesc")).Text; obj.Type = "2"; obj.Isapproved = false; obj.Createdate = DateTime.Now; obj.Researchitem = ""; obj.Patent = ""; obj.Techadv = ""; obj.Techdesc = ""; /* UserProfiles */ UserProfiles up = new UserProfiles(); up.Username = CreateUserWizard1.UserName; up.Owner = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; up.Name = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Name")).Text; up.Tel = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Tel")).Text; up.Corp = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Corp")).Text; up.City = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedValue; up.Postcode = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue; up.Address = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Address")).Text; up.Fax = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Fax")).Text; up.Kind = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("Kind")).SelectedValue; up.Type = "2"; up.Zipcht = ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedValue + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedItem.Text + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedItem.Text; /* 配對 */ //at = SpringUtil.at(); String sql = "SELECT * FROM ReuseTech "; sql += " WHERE type='1' and ((TechOther like @param1) or (WasteOther like @param2) or (TechName like @param3) or (WasteName like @param4)) "; //IDbParameters parameters = at.CreateDbParameters(); //parameters.Add("param1", OleDbType.VarChar).Value = obj.Techother; //parameters.Add("param2", OleDbType.VarChar).Value = obj.Wasteother; //parameters.Add("param3", OleDbType.VarChar).Value = "%" + obj.Techname + "%"; //parameters.Add("param4", OleDbType.VarChar).Value = "%" + obj.Wastename + "%"; //DataSet ds = new DataSet(); //at.DataSetFillWithParameters(ds, CommandType.Text, sql, parameters); OleDbCommand cmd = new OleDbCommand(sql); cmd.Parameters.Add("param1", OleDbType.VarChar).Value = obj.Techother; cmd.Parameters.Add("param2", OleDbType.VarChar).Value = obj.Wasteother; cmd.Parameters.Add("param3", OleDbType.VarChar).Value = "%" + obj.Techname + "%"; cmd.Parameters.Add("param4", OleDbType.VarChar).Value = "%" + obj.Wastename + "%"; cmd.CommandType = CommandType.Text; DataSet ds = SQLUtil.QueryDS(cmd); ArrayList matchList = new ArrayList(); foreach (DataRow dRow in ds.Tables[0].Rows) { Match match = new Match(); user2 = Membership.GetUser(dRow["UserName"].ToString()); p2 = (ProfileCommon)ProfileCommon.Create(dRow["UserName"].ToString(), true); match.Username2 = CreateUserWizard1.UserName; match.Username1 = dRow["UserName"].ToString(); match.Rid1 = (int)dRow["Id"]; match.Name2 = p.UserProfile.Name; match.Name1 = p2.UserProfile.Name; match.Corp2 = p.UserProfile.Corp; match.Corp1 = p2.UserProfile.Corp; match.Tel2 = p.UserProfile.Tel; match.Tel1 = p2.UserProfile.Tel; match.Wasteitem2 = obj.Wasteother; match.Wasteitem1 = dRow["WasteOther"].ToString(); match.Wastename2 = obj.Wastename; match.Wastename1 = dRow["WasteName"].ToString(); match.Techitem2 = obj.Techother; match.Techitem1 = dRow["TechOther"].ToString(); match.Techname2 = obj.Techname; match.Techname1 = dRow["TechName"].ToString(); match.Reusename2 = obj.Reusename; match.Reusename1 = dRow["ReuseName"].ToString(); match.Matchdate = DateTime.Now; match.Ischecked = "A"; match.Isdeleted = false; match.Isconfirm2 = "A"; match.Isconfirm1 = "A"; match.Isdroped2 = "A"; match.Isdroped1 = "A"; match.Createdate2 = DateTime.Now; match.Createdate1 = (DateTime)dRow["Createdate"]; match.Isapproved2 = false; if (user2 != null) { if (user2.IsApproved) { match.Isapproved1 = true; } else { match.Isapproved1 = false; } } else { match.Isapproved1 = false; } match.Techdesc = dRow["TechDesc"].ToString(); match.Techadv = dRow["TechAdv"].ToString(); matchList.Add(match); } Save(obj, matchList, up); //mgr.Save(obj, matchList, up); ((Label)CompleteWizardStep1.ContentTemplateContainer.FindControl("Msg")).Text = "您的帳號申請資料已經送出,請等待審核通知。"; #region Email /* Mail */ /* to 會員 */ //Marquee objM = mgrM.getMarquee("B"); String sqlMarquee = "SELECT * from Marquee where Id=? "; OleDbCommand cmdM = new OleDbCommand(sqlMarquee); cmdM.Parameters.Add("?", OleDbType.VarChar).Value = "B"; cmdM.CommandType = CommandType.Text; DataSet dsm = SQLUtil.QueryDS(cmdM); string strEmailMsg = ""; foreach (DataRow dr in dsm.Tables[0].Rows) { strEmailMsg = dr["Msg"].ToString(); } SmtpClient sc = new SmtpClient("smtp.tgpf.org.tw"); sc.Credentials = new System.Net.NetworkCredential("*****@*****.**", "IDB.riw@2018"); string strMsg = ""; string strTo = ""; string strFrom = ""; string strSubject = "資源化技術研發供需資訊平台通知"; //strMsg += "帳號: " + CreateUserWizard1.UserName + "\n"; //strMsg += "單位: " + p.UserProfile.Corp + "\n"; //strMsg += "會員姓名: " + p.UserProfile.Name + "\n"; //strMsg += "Email: " + ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Email")).Text + "\n"; strMsg += "<p>" + p.UserProfile.Name + " 先生/小姐您好</p>"; strMsg += "<p>感謝您加入「資源化技術研發供需資訊平台」 會員!!</p>"; strMsg += "<p>目前正在審核您的會員資料,造成不便敬請見諒。</p>"; strMsg += "<p>待審核後系統將主動通知您審核結果,</p>"; strMsg += "<p>通過審核後即可再次登入「資源化技術研發供需資訊平台」,</p>"; strMsg += "<p>獲得平台所提供的相關功能與服務!</p><br/><br/>"; strMsg += "<p>此信件為系統自動發送,請勿直接回覆,謝謝。</p>"; MembershipUser mng = Membership.GetUser("isrmng"); strFrom = mng.Email; strTo = ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Email")).Text; //try //{ MailMessage msgMail = new MailMessage(strFrom, strTo); msgMail.Subject = strSubject; msgMail.IsBodyHtml = true; msgMail.Body = strMsg; msgMail.CC.Add("*****@*****.**"); new util().SendMail(strFrom, strTo, strSubject, strMsg, "*****@*****.**"); /* to Manager */ strSubject = "資源化技術研發供需資訊平台-新增會員通知"; strMsg = "<p>業者廠商</p>"; strMsg += "<p>單位名稱:" + p.UserProfile.Corp + "</p>"; strMsg += "<p>聯絡人:" + p.UserProfile.Name + "</p>"; strMsg += "<p>地址:" + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("cityList")).SelectedItem.Text + ((DropDownList)UserTemplate.ContentTemplateContainer.FindControl("zipList")).SelectedItem.Text + ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Address")).Text + "</p>"; strMsg += "<p>電話:" + ((TextBox)UserTemplate.ContentTemplateContainer.FindControl("Tel")).Text + "</p>"; if (strEmailMsg.Length > 0) { strMsg += "<p><a href=\"" + strEmailMsg + "\">" + strEmailMsg + "</a></p>"; } //strMsg += "<p><a href=\"" + objM.Msg + "\">" + objM.Msg + "</a></p>"; strTo = mng.Email; msgMail = new MailMessage(strFrom, strTo); msgMail.Subject = strSubject; msgMail.IsBodyHtml = true; msgMail.Body = strMsg; msgMail.CC.Add("*****@*****.**"); new util().SendMail(strFrom, strTo, strSubject, strMsg, "*****@*****.**"); /* Mail End */ //} //catch //{ // ((Label)CompleteWizardStep1.ContentTemplateContainer.FindControl("Msg")).Text = "您的帳號申請資料已經送出,請等待審核通知。<br/>錯誤:信件寄送失敗 "; //} #endregion } catch (Exception err) { Membership.DeleteUser(CreateUserWizard1.UserName, true); String strDelReuseTech = "delete from ReuseTech where UserName = @username"; OleDbCommand cmdDelReuseTech = new OleDbCommand(strDelReuseTech); cmdDelReuseTech.Parameters.Add("@username", OleDbType.VarChar).Value = CreateUserWizard1.UserName; cmdDelReuseTech.CommandType = CommandType.Text; SQLUtil.ExecuteSql(cmdDelReuseTech); String strDelUserProfile = "delete from UserProfiles where UserName = @username"; OleDbCommand cmdDelUserProfile = new OleDbCommand(strDelUserProfile); cmdDelUserProfile.Parameters.Add("@username", OleDbType.VarChar).Value = CreateUserWizard1.UserName; cmdDelUserProfile.CommandType = CommandType.Text; SQLUtil.ExecuteSql(cmdDelUserProfile); ((Label)CompleteWizardStep1.ContentTemplateContainer.FindControl("Msg")).Text = "錯誤: " + err.ToString(); } }
protected void ButtonSave_Click(object sender, EventArgs e) { MembershipUser membershipUser = null; string password = ""; LabelError.Text = ""; if (TextBoxPassword.Text != TextBoxConfirmPassword.Text) { LabelError.Text = "Password and Confirm Password must be the same."; PanelError.Visible = true; return; } try { membershipUser = Membership.GetUser(TextBoxUserName.Text); password = answer.Replace("-", ""); password = password.Substring(0, 10); password += "#$"; if (membershipUser.GetPassword(this.answer) != password) { LabelError.Text = "Your Account could not be confirmed. Please contact the System Administrator."; PanelError.Visible = true; return; } } catch (Exception exception) { LabelError.Text += "Please enter User Name as indicated on email."; PanelError.Visible = true; } try { if (membershipUser.ChangePassword(password, TextBoxPassword.Text) == false) { LabelError.Text = ("Password is not valid. Please re-enter.<br />"); PanelError.Visible = true; return; } membershipUser.ChangePasswordQuestionAndAnswer(TextBoxPassword.Text, DropDownListSecurityQuestion.SelectedValue, TextBoxSecurityAnswer.Text); membershipUser.IsApproved = true; Membership.UpdateUser(membershipUser); Account account = Account.GetAccountByUserName(TextBoxUserName.Text); MailMessage mailMessage = new MailMessage(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), membershipUser.Email); mailMessage.Subject = "IN - SPAR MAPPER - Registration Confirmed"; mailMessage.Body = String.Format("Hi {3} {4},\n\nCongratulations your account on IN - SPAR MAPPER is now active.\n\nYour profile is as follows: \n User Name: {0} \n Password: {1} \n\nPlease navigate your web browser to {2} to Login.\n\nKind Regards,\nIN - SPAR MAPPER Administrator.", TextBoxUserName.Text, TextBoxPassword.Text, ConfigurationManager.AppSettings["applicationUri"].ToString(), account.FirstName, account.LastName); mailMessage.IsBodyHtml = false; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailRelay"].ToString()); smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["administrationEmailAddress"].ToString(), ConfigurationManager.AppSettings["password"].ToString()); smtpClient.EnableSsl = true; smtpClient.Send(mailMessage); Response.Redirect("Default.aspx"); } catch (Exception exception) { LabelError.Text += (exception.Message + "<br />"); PanelError.Visible = true; } }
public HttpResponseMessage SetSecurityAnswer(UserAuthenticationRequest securityRequest) { HttpResponseMessage hrm = Request.CreateErrorResponse( HttpStatusCode.PreconditionFailed, "Unexpected Error locating user membership"); if (securityRequest == null) { return(hrm = Request.CreateErrorResponse( HttpStatusCode.PreconditionFailed, "Unexpected Error parsing request.")); } string userName = Request.UserName(); MembershipUser mu = Membership.GetUser(userName); if (mu != null) { // Validate answer length. if (securityRequest.SecretAnswer.Length < SecurityConfiguration.Settings.MinimumSecretAnswerLength) { hrm = Request.CreateErrorResponse( HttpStatusCode.PreconditionFailed, String.Format("The secret question answer is less than the minimum length of {0}", SecurityConfiguration.Settings.MinimumSecretAnswerLength ) ); return(hrm); } string secretQuestion = string.IsNullOrEmpty(securityRequest.SecretQuestion) ? mu.PasswordQuestion : securityRequest.SecretQuestion; if (!string.IsNullOrEmpty(securityRequest.Password) && !string.IsNullOrEmpty(secretQuestion) && !string.IsNullOrEmpty(securityRequest.SecretAnswer)) { try { if (mu.ChangePasswordQuestionAndAnswer( securityRequest.Password, secretQuestion, securityRequest.SecretAnswer)) { mu.Comment = string.Empty; Membership.UpdateUser(mu); if (!Roles.IsUserInRole(userName, "Customer")) { Roles.AddUserToRole(userName, "Customer"); } hrm = Request.CreateResponse(HttpStatusCode.OK); } else { hrm = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Wrong Password"); } } catch (Exception exc) { hrm = Request.CreateErrorResponse(HttpStatusCode.NoContent, exc.Message); } } else { hrm = Request.CreateErrorResponse( HttpStatusCode.PreconditionFailed, "Missing Password or Secret Answer"); } } return(hrm); }
/// <summary> /// Updates question and answer for the facade user in the data store. /// </summary> /// <param name="password">The current password for the facade user.</param> /// <param name="question">The new question for the facade user.</param> /// <param name="answer">The answer for the question for the facade user.</param> /// <returns>true if the update was successful; otherwise, false.</returns> public bool ChangePasswordQuestionAndAnswer(string password, string question, string answer) { return(_membershipUser.ChangePasswordQuestionAndAnswer(password, question, answer)); }
protected void OnSubmittedFormSave(object sender, EventArgs e) { List <dynamic> ReturnObj = new List <dynamic>(); try { Byte[] imgByte = null; NameValueCollection nvc = Request.Form; MasterUser objMasterUser = new MasterUser(); objMasterUser.UserName = nvc["ctl00$MainContent$username"]; MembershipUser _User = Membership.GetUser(objMasterUser.UserName); if (_User == null) { throw new Exception("Username " + HttpUtility.HtmlEncode(objMasterUser.UserName) + " not found. Please check the value and re-enter."); } else { MasterUser _MasterUser = new UsersDAL().GetValidUser(_User.UserName); if (_MasterUser.UUID == (Guid)_User.ProviderUserKey) { HttpPostedFile File = Request.Files["ctl00$MainContent$imgUpload"]; if (File != null && File.ContentLength > 0) { imgByte = new Byte[File.ContentLength]; File.InputStream.Read(imgByte, 0, File.ContentLength); objMasterUser.Image = imgByte; } else { if (_MasterUser.Image != null) { objMasterUser.Image = _MasterUser.Image; } } objMasterUser.UUID = (Guid)_User.ProviderUserKey; objMasterUser.FullName = (!string.IsNullOrEmpty(nvc["ctl00$MainContent$fullname"]) ? nvc["ctl00$MainContent$fullname"].Trim() : string.Empty); string birthDate = (!string.IsNullOrEmpty(nvc["ctl00$MainContent$birthdate"]) ? nvc["ctl00$MainContent$birthdate"].Trim() : string.Empty); if (birthDate != "") { objMasterUser.BirthDate = DateTime.ParseExact(birthDate, "dd-MM-yyyy", null); } else { objMasterUser.BirthDate = null; } if (!string.IsNullOrEmpty(nvc["ctl00$MainContent$Gender"])) { string selectedGender = nvc["ctl00$MainContent$Gender"].ToString(); objMasterUser.Gender = (selectedGender == "male" ? "M" : "F"); } objMasterUser.Comment = (!string.IsNullOrEmpty(nvc["ctl00$MainContent$comment"]) ? nvc["ctl00$MainContent$comment"].Trim() : string.Empty); objMasterUser.Website = (!string.IsNullOrEmpty(nvc["ctl00$MainContent$website"]) ? nvc["ctl00$MainContent$website"].Trim() : string.Empty); objMasterUser.UserPhoneNo = nvc["ctl00$MainContent$phone"]; //email:new=update if (_User.Email.Trim() != nvc["ctl00$MainContent$email"].Trim()) { _User.Email = nvc["ctl00$MainContent$email"].Trim(); Membership.UpdateUser(_User); objMasterUser.UserEmail = _User.Email; } //password:notnull=change() if (!string.IsNullOrEmpty(nvc["ctl00$MainContent$oldpassword"])) { string oldpassword = string.Empty; string newpassword = string.Empty; oldpassword = nvc["ctl00$MainContent$oldpassword"].Trim(); if (!string.IsNullOrEmpty(nvc["ctl00$MainContent$newpassword"]) && !string.IsNullOrEmpty(nvc["ctl00$MainContent$confirmpassword"])) { newpassword = nvc["ctl00$MainContent$newpassword"].Trim(); } else { throw new Exception("A password-related error has occured. Please try again."); } if (_User.ChangePassword(oldpassword, newpassword)) { objMasterUser.UserPassword = newpassword; bool mail = MailHelper.SendMail(new MasterUser() { UserEmail = _User.Email, FullName = objMasterUser.FullName, UserName = objMasterUser.UserName }, newpassword); ReturnObj.Add(new { source = "Password Updated", message = "Password successfully updated. Your new password will be sent to your email id : " + new Helper().EmailClipper(_User.Email) }); } else { throw new Exception("A password-related error has occured. Please check your old password and Try Again!"); } } //sec. question/answer:notnull=change() if ((_MasterUser.SecQuestion.Trim() != nvc["ctl00$MainContent$question"].Trim()) || (Security.Decrypt(_MasterUser.SecAnswer.Trim()) != nvc["ctl00$MainContent$answer"].Trim())) { string question = string.Empty; string answer = string.Empty; if (!string.IsNullOrEmpty(nvc["ctl00$MainContent$question"]) && !string.IsNullOrEmpty(nvc["ctl00$MainContent$answer"])) { question = nvc["ctl00$MainContent$question"].Trim(); answer = nvc["ctl00$MainContent$answer"].Trim(); } else { throw new Exception("A security-related error has occured. Please try again."); } if (_User.ChangePasswordQuestionAndAnswer(_User.GetPassword(Security.Decrypt(_MasterUser.SecAnswer.Trim())), question, answer)) { objMasterUser.SecQuestion = question; objMasterUser.SecAnswer = answer; ReturnObj.Add(new { source = "Security Details Updated", message = "Security details (question/answer) successfully updated." }); } } objMasterUser.ModifiedBy = new UsersDAL().GetValidUser(HttpContext.Current.User.Identity.Name).UserID; objMasterUser.ModifiedTimeStamp = DateTime.Now; if (new UsersDAL().UpdateProfileUser(objMasterUser)) { ReturnObj.Add(new { source = "Profile Updated", message = "Profile successfully updated." }); string json = JsonConvert.SerializeObject(ReturnObj, Formatting.Indented); string script = "var data = " + json + ";"; ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "dataVar", script, true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "output", "ShowOutput('" + _MasterUser.UserID + "');", true); } else { throw new Exception("An error occurred while updating user profile"); } } } } catch (Exception ex) { ((SiteMaster)this.Master).ShowMessage("Error", "An error occurred", ex, true); } }
public AspUser SaveAspUser(AspUser saveUser) { if (saveUser != null) { MembershipProvider simpleProvider = Membership.Providers["SimpleProvider"]; if (saveUser.UserId == Guid.Empty) //means this is new user : create user { // Insert New Membership Account MembershipCreateStatus status; MembershipUser newUser = Membership.CreateUser(saveUser.UserName, saveUser.Password, saveUser.Email, saveUser.PasswordQuestion, saveUser.PasswordAnswer, saveUser.IsApproved, out status); if (status == MembershipCreateStatus.Success) { Guid newUserId = Utilities.ToGuid(newUser.ProviderUserKey); ApartmentMethods.UpdateAspUserOrganisationId(newUserId, saveUser.OrganisationId); saveUser = GetAspUser(newUserId); } else { switch (status) { case MembershipCreateStatus.DuplicateEmail: saveUser.ErrorMessage = "The e-mail address already exists in the database for the application."; break; case MembershipCreateStatus.DuplicateProviderUserKey: saveUser.ErrorMessage = "The provider user key already exists in the database for the application."; break; case MembershipCreateStatus.DuplicateUserName: saveUser.ErrorMessage = "The user name already exists in the database for the application."; break; case MembershipCreateStatus.InvalidAnswer: saveUser.ErrorMessage = "The password answer is not formatted correctly."; break; case MembershipCreateStatus.InvalidEmail: saveUser.ErrorMessage = "The e-mail address is not formatted correctly."; break; case MembershipCreateStatus.InvalidProviderUserKey: saveUser.ErrorMessage = "The provider user key is of an invalid type or format."; break; case MembershipCreateStatus.InvalidQuestion: saveUser.ErrorMessage = "The password question is not formatted correctly."; break; case MembershipCreateStatus.InvalidUserName: saveUser.ErrorMessage = "The user name was not found in the database."; break; case MembershipCreateStatus.InvalidPassword: saveUser.ErrorMessage = "The password is not formatted correctly."; break; default: saveUser.ErrorMessage = "Fail to create new user"; break; } } } else { MembershipUser memberShipUser = Membership.GetUser(saveUser.UserId); int? updateCode = null; if (memberShipUser.UserName != saveUser.UserName) { updateCode = ApartmentMethods.UpdateMembershipUserName(Membership.ApplicationName, memberShipUser.UserName, saveUser.UserName); memberShipUser = Membership.GetUser(saveUser.UserId); } string newGenPassword = string.Empty; bool saveQAerror = false; if (updateCode == null || updateCode == 0) { memberShipUser.Email = saveUser.Email; memberShipUser.IsApproved = saveUser.IsApproved; Membership.UpdateUser(memberShipUser); if (!string.IsNullOrEmpty(saveUser.PasswordQuestion) && !string.IsNullOrEmpty(saveUser.PasswordAnswer)) { saveQAerror = !memberShipUser.ChangePasswordQuestionAndAnswer(saveUser.InputPassword, saveUser.PasswordQuestion, saveUser.PasswordAnswer); } if (saveUser.IsResetPassword) { if (simpleProvider != null) { MembershipUser simpleUser = simpleProvider.GetUser(saveUser.UserId, false); if (simpleUser != null) { if (saveUser.IsResetPassword) { newGenPassword = simpleUser.ResetPassword(); } } } } } saveUser = GetAspUser(saveUser.UserId); saveUser.NewGenPassword = newGenPassword; saveUser.IsSavedQAError = saveQAerror; } } return(saveUser); }
public void UpdateUser(object sender, EventArgs e) { if (!Page.IsValid) { return; } string resultMsg = ""; string userIDText = UserID.Text; string emailText = Email.Text; string password = null; string newPassword = null; string question = null; string answer = null; if (Membership.EnablePasswordRetrieval) { password = Password.Text.Trim(); newPassword = NewPassword.Text.Trim(); if (Membership.RequiresQuestionAndAnswer) { question = SecretQuestion.Text; answer = SecretAnswer.Text; } } try { MembershipUser mu = Membership.GetUser(userIDText); mu.Email = Email.Text; mu.IsApproved = ActiveUser.Checked; Membership.UpdateUser(mu); UpdateRoleMembership(userIDText); // Are we allowed to change secret question & answer? // We will need old password for this. // if (Membership.EnablePasswordRetrieval && Membership.RequiresQuestionAndAnswer && password != null && question != null && answer != null) { mu.ChangePasswordQuestionAndAnswer(password, question, answer); } // Are we allowed to change the password? // We will need old password for this. // if (Membership.EnablePasswordRetrieval && !string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(newPassword)) { mu.ChangePassword(password, newPassword); } resultMsg = "User details has been successfully updated."; } catch (Exception ex) { resultMsg = "Failed to update user details. Error message: " + ex.Message; } SetResultMessage(resultMsg); }
protected void Button_Continuar_Change_Click(object sender, EventArgs e) { if (BootstrapTextBox_Contraseña_Anterior_Change.Text.Trim() == "") { //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Debe ingresar la contraseña actual.');", true); Toast.ShowToast(this, Toast.ToastType.Error, "Debe ingresar la contraseña actual."); return; } if (BootstrapTextBox_Nueva_Contraseña_change.Text.Trim() == "" || BootstrapTextBox_Confirmar_Contra_Change.Text.Trim() == "") { //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Debe ingresar la nueva contraseña y su confirmacion.');", true); Toast.ShowToast(this, Toast.ToastType.Error, "Debe ingresar la nueva contraseña y su confirmacion."); return; } if (FG.ValidarPassword(BootstrapTextBox_Nueva_Contraseña_change.Text.Trim()) == false) { Label_Mensaje_NuevaContra_Change.Text = "Mensaje: La nueva constraseña no cumple con los requisitos de longitud y complejidad. Esta debe contener un mínimo de 8 caracteres incluyendo Mayúscula, Minúscula, Caracter especial y Número."; return; } if (BootstrapTextBox_Nueva_Contraseña_change.Text.Trim() != BootstrapTextBox_Confirmar_Contra_Change.Text.Trim()) { //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Las contraseñas no coinciden.');", true); Toast.ShowToast(this, Toast.ToastType.Error, "Las contraseñas no coinciden."); return; } MembershipUser User = Membership.GetUser(LoginUser.Text.Trim()); if (User.IsLockedOut) { User.UnlockUser(); } if (Membership.ValidateUser(LoginUser.Text.Trim(), BootstrapTextBox_Contraseña_Anterior_Change.Text.Trim())) { string ContraseñaAnterior = BootstrapTextBox_Contraseña_Anterior_Change.Text.Trim(); string NuevaContraseña = BootstrapTextBox_Nueva_Contraseña_change.Text.Trim(); if (User != null) { User.ChangePassword(ContraseñaAnterior, NuevaContraseña); User.ChangePasswordQuestionAndAnswer(NuevaContraseña, BootstrapComboBox_Pregunta_Change.Text.Trim(), BootstrapTextBox_Respuesta_Change.Text.Trim()); if (Roles.GetRolesForUser(LoginUser.Text.Trim()).Count() == 0) { //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('El Usuario no pertenece a ningún Perfil. Contacte al Administrador.');", true); Toast.ShowToast(this, Toast.ToastType.Error, "El Usuario no pertenece a ningún Perfil. Contacte al Administrador."); return; } string Rol = Roles.GetRolesForUser(LoginUser.Text.Trim())[0].ToString(); //Roles.AddUserToRole(LoginUser.Text.Trim(), "Administrador"); FG.Logueos_Usuarios(LoginUser.Text.Trim(), Rol); FormsAuthentication.RedirectFromLoginPage(LoginUser.Text.Trim(), false); } } else if (User.IsApproved == false) { Toast.ShowToast(this, Toast.ToastType.Error, "El Usuario está Deshabilitado del sistema. Contacte al Administrador."); return; } }