コード例 #1
0
		public ActionResult Register(RegisterPage currentPage, RegisterPageViewModel model, RegisterForm registerForm, int[] SelectedCategories)
		{
			model.RegisterForm.AvailableCategories = GetAvailableCategories();
			model.RegisterForm.SelectedCategories = SelectedCategories;
			if (registerForm.Password != registerForm.PasswordConfirm)
			{
				ModelState.AddModelError("RegisterForm.ValidationMessage", _localizationService.GetString("/common/validation/compare_passwords"));
			}

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

			string emailAddress = registerForm.UserName.Trim();
			string password = registerForm.Password;

			// Account
			MembershipUser user = null;
			MembershipCreateStatus createStatus;
			user = Membership.CreateUser(emailAddress, password, emailAddress, null, null, true, out createStatus);

			bool existingUserWithoutPassword = false;

			if (createStatus == MembershipCreateStatus.DuplicateUserName)
			{
				user = Membership.GetUser(emailAddress);
				var customer1 = CustomerContext.Current.GetContactForUser(user);

                if (customer1 == null)
                {

                    customer1 = CustomerContact.CreateInstance(user);
                }


                if (customer1.GetHasPassword())
				{
					ModelState.AddModelError("RegisterForm.ValidationMessage", _localizationService.GetString("/common/account/register_error_unique_username"));
				}
				else
				{
					existingUserWithoutPassword = true;
				}
			}
			else if (user == null)
			{
				ModelState.AddModelError("RegisterForm.ValidationMessage", _localizationService.GetString("/common/account/register_error"));
			}

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

			if (!existingUserWithoutPassword)
			{
                Roles.AddUserToRole(user.UserName, AppRoles.EveryoneRole);
                Roles.AddUserToRole(user.UserName, AppRoles.RegisteredRole);
			}
			else
			{
				// set new password
				var pass = user.ResetPassword();
				user.ChangePassword(pass, password);
			}

			var customer = CustomerContext.Current.GetContactForUser(user);

            if (customer == null)
            {

                customer = CustomerContact.CreateInstance(user);
            }

            customer.FirstName = registerForm.Address.FirstName;
			customer.LastName = registerForm.Address.LastName;
			customer.SetPhoneNumber(registerForm.Phone);
			customer.FullName = string.Format("{0} {1}", customer.FirstName, customer.LastName);
			customer.SetHasPassword(true);

			// member club
			if (registerForm.MemberClub)
			{
				customer.CustomerGroup = Constants.CustomerGroup.CustomerClub;
			}

			// categories
			customer.SetCategories(SelectedCategories);

			customer.SaveChanges();

			var CustomerAddressRepository = ServiceLocator.Current.GetInstance<ICustomerAddressRepository>();
			CustomerAddressRepository.SetCustomer(customer);

			// copy address fields to shipping address
			registerForm.Address.CheckAndSetCountryCode();

			var ShippingAddress = (Address)registerForm.Address.Clone();
			ShippingAddress.IsPreferredShippingAddress = true;
			CustomerAddressRepository.Save(ShippingAddress);

			registerForm.Address.IsPreferredBillingAddress = true;
			CustomerAddressRepository.Save(registerForm.Address);

			LoginController.CreateAuthenticationCookie(ControllerContext.HttpContext, emailAddress, Mediachase.Commerce.Core.AppContext.Current.ApplicationName, false);

			bool mail_sent = SendWelcomeEmail(registerForm.UserName, currentPage);

			return Redirect(_urlResolver.GetUrl(ContentReference.StartPage));
		}
コード例 #2
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsValid)
                {
                    return;
                }

                string userName    = Request.QueryString["userName"];
                string password    = passwordTextbox.Text;
                string roleName    = rolesDropDownList.SelectedItem.Value.Trim();
                string email       = emailTextbox.Text.Trim();
                string currentUser = Context.User.Identity.Name.ToLower();

                //if (userName.ToLower().Trim() == "admin" && currentUser != "admin")
                //{
                //    return;
                //}

                MembershipUser user = Membership.GetUser(userName);
                userName = userNameTextbox.Text.Trim();
                if (user == null && password.Length < 5)
                {
                    return;
                }

                //Add new user
                if (user == null)
                {
                    if (Roles.IsUserInRole(userName, roleName))
                    {
                        return;
                    }

                    if (string.IsNullOrEmpty(email))
                    {
                        WebHelper.AddMemberShipUserWithoutEmail(userName, password, roleName);
                    }
                    else
                    {
                        WebHelper.AddMemberShipUser(userName, password, email, roleName);
                    }


                    user            = Membership.GetUser(userName);
                    user.IsApproved = chkActive.Checked;
                    Membership.UpdateUser(user);

                    string loggedData = string.Format("{0}|{1}", userName, roleName);
                }
                else //Edit user
                {
                    string[] roles = Roles.GetRolesForUser(user.UserName);
                    if (!CheckPermitRoles(roles))
                    {
                        return;
                    }

                    if (!ChangePassword && roles.Length > 0 && roles[0].ToLower().Trim() != rolesDropDownList.SelectedItem.Value.ToLower().Trim())
                    {
                        Roles.RemoveUserFromRoles(user.UserName, roles);
                        Roles.AddUserToRole(user.UserName, rolesDropDownList.SelectedItem.Value.ToLower().Trim());
                    }

                    if (!string.IsNullOrEmpty(password))
                    {
                        // Unlock user
                        if (user.IsLockedOut)
                        {
                            user.UnlockUser();
                        }
                        //string currentPassword = user.GetPassword();
                        user.ChangePassword(user.ResetPassword(), passwordTextbox.Text.Trim());
                    }

                    user.Email = email;

                    if (String.Compare(user.UserName, userName) == 0)
                    {
                        user.IsApproved = chkActive.Checked;
                        Membership.UpdateUser(user);

                        // Update Rate hour and DB Name
                        Guid   guid      = WebHelper.GetUserID(userName);
                        string uIDupdate = guid.ToString();
                    }
                    else
                    {
                        if (Roles.IsUserInRole(userName, roleName))
                        {
                            return;
                        }

                        // todo: update user name.
                        user = Membership.GetUser(userName);
                    }
                }

                StatusLabel.Text = "Updated!";

                // Update Rate hour and DB Name
                string uID = WebHelper.GetUserID(userName).ToString();
                if (dsUserDetails != null && dsUserDetails.Tables.Count > 0 && dsUserDetails.Tables[0].Rows.Count > 0)
                {
                    CultureInfo ivC           = new CultureInfo("es-US");
                    DateTime    effectiveDate = Convert.ToDateTime("01/01/1900", ivC);

                    string lsRateHour = string.Empty, lsSubcontractor = string.Empty, lsDBName = string.Empty, lsUserType = string.Empty;
                    string lsEffectiveDate = effectiveDate.ToString("MM/dd/yyyy");
                    foreach (DataRow dr in dsUserDetails.Tables[0].Rows)
                    {
                        if (dr.RowState != DataRowState.Added)
                        {
                            continue;
                        }
                        if (lsDBName.Equals(""))
                        {
                            lsRateHour      = dr["rate_hour"].ToString();
                            lsSubcontractor = dr["Subcontractor"].ToString();
                            lsDBName        = dr["DBName"].ToString();
                            lsUserType      = dr["UserType"].ToString();
                            lsEffectiveDate = Convert.ToDateTime(dr["EffectiveDate"].ToString(), ivC).ToString("MM/dd/yyyy");
                        }
                        else
                        {
                            lsRateHour      = lsRateHour + ";" + dr["rate_hour"].ToString();
                            lsSubcontractor = lsSubcontractor + ";" + dr["Subcontractor"].ToString();
                            lsDBName        = lsDBName + ";" + dr["DBName"].ToString();
                            lsUserType      = lsUserType + ";" + dr["UserType"].ToString();
                            lsEffectiveDate = lsEffectiveDate + ";" + Convert.ToDateTime(dr["EffectiveDate"].ToString(), ivC).ToString("MM/dd/yyyy");
                        }
                    }
                    SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure, "sp_UpdateUserDetails",
                                              Data.CreateParameter("@IN_UserID", uID),
                                              Data.CreateParameter("@IN_UserName", userNameTextbox.Text.Trim()),
                                              Data.CreateParameter("@IN_RateHour", lsRateHour),
                                              Data.CreateParameter("@IN_SubCont", lsSubcontractor),
                                              Data.CreateParameter("@IN_DBName", lsDBName),
                                              Data.CreateParameter("@IN_UserType", lsUserType),
                                              Data.CreateParameter("@IN_EffectiveDate", lsEffectiveDate)
                                              );
                    dsUserDetails = new DataSet();
                    // Binding User Details
                    LoadUserDetails(WebHelper.GetUserID(user.UserName).ToString());
                    DataView dv = new DataView(dsUserDetails.Tables[0]);
                    this.lvStage.DataSource = dv;
                    this.lvStage.DataBind();
                }
                // Update tbl_ReportTo, tbl_UsersAdd
                SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure, "sp_UpdateReportTo",
                                          Data.CreateParameter("@IN_ReportToID", (this.ReportToID == null ? DBNull.Value : this.ReportToID)),
                                          Data.CreateParameter("@IN_ReportToName", txtReportTo.Text.Trim()),
                                          Data.CreateParameter("@IN_UserID", uID),
                                          Data.CreateParameter("@IN_UserName", userNameTextbox.Text.Trim()),
                                          Data.CreateParameter("@IN_DateJoined", string.IsNullOrEmpty(DateJoinedTextBox.Text) ? "01/01/1900" : DateJoinedTextBox.Text),
                                          Data.CreateParameter("@IN_DateResigned", string.IsNullOrEmpty(DateResignedTextBox.Text) ? "12/31/9999" : DateResignedTextBox.Text)
                                          );
            }
            catch (Exception ex)
            {
                StatusLabel.Text = ex.ToString();
            }
        }
コード例 #3
0
        public string ChangePassword(string username, string oldPassword, string newPassword)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                Regex r = new Regex(PasswordExpression);
                if (!r.IsMatch(oldPassword) || !r.IsMatch(newPassword))
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "密码必须是由数字或字母组成的字符串,且最小6位,最大30位!");
                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }

                MembershipUser user = Membership.GetUser(username);
                if (user == null)
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "用户名不存在!");
                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }
                if (!Membership.ValidateUser(username, oldPassword))
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    if (user.IsLockedOut)
                    {
                        sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "您的账号已被锁定,请联系管理员先解锁后才能登录!");
                    }
                    else if (!user.IsApproved)
                    {
                        sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "您的帐户尚未获得批准。您无法登录,直到管理员批准您的帐户!");
                    }
                    else
                    {
                        sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "原密码输入不正确,请检查!");
                    }

                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }

                if (!user.ChangePassword(oldPassword, newPassword))
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "修改密码失败,请正确输入并重试");
                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }

                sb.Append("<Rsp>");
                sb.AppendFormat("<IsOk>{0}</IsOk>", true);
                sb.Append("<ErrorMsg></ErrorMsg>");
                sb.Append("</Rsp>");
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                new CustomException(string.Format("服务-接口:string ChangePassword(string username, string oldPassword, string newPassword):异常:{0}", ex.Message), ex);
                StringBuilder sb = new StringBuilder();
                sb.Append("<Rsp>");
                sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", ex.Message);
                sb.Append("</Rsp>");
                return(sb.ToString());
            }
        }
コード例 #4
0
        protected void OnSendClick(object sender, EventArgs e)
        {
            string username = Membership.GetUserNameByEmail(txtEMail.Text);

            if (!string.IsNullOrEmpty(username))
            {
                MembershipUser user = Membership.GetUser(username, false);
                if (user != null)
                {
                    if (user.IsLockedOut)
                    {
                        user.UnlockUser();
                    }

                    string password          = Helper.GeneratePassword(6, 2);
                    string temporaryPassword = user.ResetPassword();
                    user.ChangePassword(temporaryPassword, password);

                    try
                    {
                        MailAddress receiver       = new MailAddress(txtEMail.Text);
                        string      messageCulture = !string.IsNullOrEmpty(UserProfile.GetProfile(user.UserName).PrefferedCulture) ? UserProfile.GetProfile(user.UserName).PrefferedCulture : SiteConfig.DefaultLanguage;
                        string      subject        = _4screen.CSB.Common.SiteConfig.SiteName + " " + GuiLanguage.GetGuiLanguage("Pages.Popups.WebUI.Base", messageCulture).GetString("TextAccountSubject");
                        string      body           = GuiLanguage.GetGuiLanguage("Templates", messageCulture).GetString("EmailAccountRetrieval");
                        body = body.Replace("<%USER%>", username);
                        body = body.Replace("<%PASSWORD%>", Server.HtmlEncode(password));
                        if (user.PasswordQuestion != "-")
                        {
                            body = body.Replace("<%ACTIVATIONCODE%>", string.Format("<p>{0} <b>{1}</b></p>", language.GetString("TextActivationCode"), Server.HtmlEncode(user.PasswordQuestion)));
                        }
                        else
                        {
                            body = body.Replace("<%ACTIVATIONCODE%>", string.Empty);
                        }
                        List <MailAddress> bccList = new List <MailAddress>();
                        foreach (string bccEmail in ConfigurationManager.AppSettings["RegistrationBCCMail"].Split(','))
                        {
                            if (!string.IsNullOrEmpty(bccEmail))
                            {
                                bccList.Add(new MailAddress(bccEmail));
                            }
                        }
                        Mail.SendMail(receiver, new List <MailAddress>(), bccList, subject, body, true);

                        PnlRecover.Visible = false;
                        PnlSent.Visible    = true;
                    }
                    catch
                    {
                        PnlError.Visible = true;
                        LitError.Text    = languageShared.GetString("EmailUnableToSend");
                    }
                }
                else if (user.IsLockedOut)
                {
                    PnlError.Visible = true;
                    LitError.Text    = language.GetString("MessageAccountLocked");
                }
                else
                {
                    PnlError.Visible = true;
                    LitError.Text    = language.GetString("MessageAccountInfoNotFound");
                }
            }
            else
            {
                PnlError.Visible = true;
                LitError.Text    = language.GetString("MessageAccountInfoNotFound");
            }
        }
コード例 #5
0
ファイル: EditMember.aspx.cs プロジェクト: jraghu24/Rraghu
        protected void tmp_save(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
            {
                foreach (uicontrols.TabPage tp in _contentControl.GetPanels())
                {
                    tp.ErrorControl.Visible = true;
                    tp.ErrorHeader          = ui.Text("errorHandling", "errorHeader");
                    tp.CloseCaption         = ui.Text("close");
                }
            }
            else
            {
                if (Page.IsPostBack)
                {
                    // hide validation summaries
                    foreach (uicontrols.TabPage tp in _contentControl.GetPanels())
                    {
                        tp.ErrorControl.Visible = false;
                    }
                }

                if (Member.InUmbracoMemberMode())
                {
                    _document.LoginName = MemberLoginNameTxt.Text;
                    _document.Email     = MemberEmail.Text;

                    // Check if password should be changed
                    string tempPassword = ((controls.passwordChanger)MemberPasswordTxt.Controls[0]).Password;
                    if (tempPassword.Trim() != "")
                    {
                        _document.Password = tempPassword;
                    }

                    // Groups
                    foreach (ListItem li in _memberGroups.Items)
                    {
                        if (("," + _memberGroups.Value + ",").IndexOf("," + li.Value + ",") > -1)
                        {
                            if (!Roles.IsUserInRole(_document.LoginName, li.Value))
                            {
                                Roles.AddUserToRole(_document.LoginName, li.Value);
                            }
                        }
                        else if (Roles.IsUserInRole(_document.LoginName, li.Value))
                        {
                            Roles.RemoveUserFromRole(_document.LoginName, li.Value);
                        }
                    }

                    //The value of the properties has been set on IData through IDataEditor in the ContentControl
                    //so we need to 'retrieve' that value and set it on the property of the new IContent object.
                    //NOTE This is a workaround for the legacy approach to saving values through the DataType instead of the Property
                    //- (The DataType shouldn't be responsible for saving the value - especically directly to the db).
                    foreach (var item in _contentControl.DataTypes)
                    {
                        _document.getProperty(item.Key).Value = item.Value.Data.Value;
                    }

                    // refresh cache
                    _document.XmlGenerate(new System.Xml.XmlDocument());
                    _document.Save();
                }
                else
                {
                    _member.Email = MemberEmail.Text;
                    if (Membership.Provider.EnablePasswordRetrieval)
                    {
                        string tempPassword = ((controls.passwordChanger)MemberPasswordTxt.Controls[0]).Password;
                        if (tempPassword.Trim() != "")
                        {
                            _member.ChangePassword(_member.GetPassword(), tempPassword);
                        }
                    }
                    Membership.UpdateUser(_member);
                    // Groups
                    foreach (ListItem li in _memberGroups.Items)
                    {
                        if (("," + _memberGroups.Value + ",").IndexOf("," + li.Value + ",") > -1)
                        {
                            if (!Roles.IsUserInRole(_member.UserName, li.Value))
                            {
                                Roles.AddUserToRole(_member.UserName, li.Value);
                            }
                        }
                        else if (Roles.IsUserInRole(_member.UserName, li.Value))
                        {
                            Roles.RemoveUserFromRole(_member.UserName, li.Value);
                        }
                    }
                }

                ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editMemberSaved", base.getUser()), "");
            }
        }
コード例 #6
0
        /// <summary>
        /// Date Modified:  11/Nov/2015
        /// Modified By:    Josephine Monteza
        /// (description)   Add LDAP change password
        /// ===================================
        /// </summary>
        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            try
            {
                string strNewPass = NewPassword.Text;
                string strDummyPassword;
                string sMsg = "";

                if (!strNewPass.Any(char.IsUpper))
                {
                    sMsg = "Password must have uppercase ";
                }
                if (!strNewPass.Any(char.IsLower))
                {
                    if (sMsg.Trim() == "")
                    {
                        sMsg = "Password must have lowercase letter. ";
                    }
                    else
                    {
                        sMsg = sMsg + " and lowercase letter. ";
                    }
                }
                else
                {
                    if (sMsg != "")
                    {
                        sMsg = sMsg + "letter. ";
                    }
                }

                if (sMsg != "")
                {
                    AlertMessage(sMsg);
                }
                else
                {
                    MembershipUser mUser = Membership.GetUser(User.Identity.Name);
                    strDummyPassword = mUser.ResetPassword();

                    if (mUser.ChangePassword(strDummyPassword, strNewPass))
                    {
                        MUser.ChangePasswordInLDAP(mUser.UserName, strNewPass);
                        SelectSpecialistViewType();
                        AlertMessage("Password successfully changed.");
                    }
                    else
                    {
                        AlertMessage("Password change failed. Please re-enter your password and try again.");
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Non alpha numeric characters in 'newPassword' needs to be greater than or equal to '1'.")
                {
                    AlertMessage("Password must be at least 8 characters long and a combination of Alpha-Numeric and Special Characters.");
                }
                else
                {
                    AlertMessage(ex.Message);
                }
            }
        }
コード例 #7
0
    protected void buttonNewPassword_OnClick(object sender, EventArgs e)
    {
        if (ddUsers.SelectedValue == Guid.Empty.ToString())
        {
            Utils.displayStatus(ref labelStatusEdit, Color.Red, "Du må velge en bruker først");
            return;
        }

        if (String.IsNullOrEmpty(tbUserNameE.Text))
        {
            Utils.displayStatus(ref labelStatusEdit, Color.Red, "Feltet for brukernavn kan ikke være tomt");
            return;
        }

        if (tbNewPassword.Text.Length < Membership.Provider.MinRequiredPasswordLength)
        {
            Utils.displayStatus(ref labelStatusEdit, Color.Red, "Passordet må ha minst " + Membership.Provider.MinRequiredPasswordLength.ToString() + " tegn");
            return;
        }

        Membership.ApplicationName = "/Lorakon";
        MembershipUser u = Membership.GetUser(tbUserNameE.Text, false);

        if (u == null)
        {
            Utils.displayStatus(ref labelStatusEdit, Color.Red, "Bruker '" + tbUserNameE.Text + "' finnes ikke");
            Membership.ApplicationName = "/LorakonAdmin";
            return;
        }

        try
        {
            string newPassword = u.ResetPassword();

            if (newPassword != null)
            {
                if (!u.ChangePassword(newPassword, tbNewPassword.Text))
                {
                    Utils.displayStatus(ref labelStatusEdit, Color.Red, "Forandre passord feilet");
                    return;
                }
            }
            else
            {
                Utils.displayStatus(ref labelStatusEdit, Color.Red, "Invalid password answer. Please re-enter and try again");
                return;
            }
        }
        catch (MembershipPasswordException ex)
        {
            Utils.displayStatus(ref labelStatusEdit, Color.Red, "Invalid password answer. Please re-enter and try again");
        }
        catch (Exception ex)
        {
            Utils.displayStatus(ref labelStatusEdit, Color.Red, ex.Message);
        }
        finally
        {
            Membership.ApplicationName = "/LorakonAdmin";
        }

        Utils.displayStatus(ref labelStatusEdit, Color.SeaGreen, "Nytt passord for bruker " + u.UserName + " er " + tbNewPassword.Text);
        tbNewPassword.Text = "";
    }
コード例 #8
0
 public static Boolean ChangeASPNETUserPassword(MembershipUser user, String oldPassword, String newPassword)
 {
     return(user.ChangePassword(oldPassword, newPassword));
 }
コード例 #9
0
        public static bool ChangePassword(string userName, string oldPassword, string newPasswd)
        {
            MembershipUser u = Membership.GetUser(userName, false);

            return(u.ChangePassword(oldPassword, newPasswd));
        }
コード例 #10
0
        public JsonResult Update(admin p)
        {
            try
            {
                if (p.name.Length < 3 || p.name.Length > 30 || p.password.Length < 8 || p.password.Length > 25)
                {
                    return(Json(false, JsonRequestBehavior.AllowGet));
                }
                admin oldAdmin = db.admins.FirstOrDefault(d => d.name == User.Identity.Name);
                ((IObjectContextAdapter)db).ObjectContext.Detach(oldAdmin);
                string oldPassword = oldAdmin.password;
                p.dateOfJoin = oldAdmin.dateOfJoin;
                p.lastPatientComplainsVieweddate = oldAdmin.lastPatientComplainsVieweddate;
                p.lastDoctorComplainsViewedDate  = oldAdmin.lastDoctorComplainsViewedDate;
                p.lastGeneralComplainViewedDate  = oldAdmin.lastGeneralComplainViewedDate;
                db.Entry(p).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                MembershipUser adminMember = Membership.GetUser();
                adminMember.Email = p.mail;
                if (p.password != oldPassword)
                {
                    var generatedPass = adminMember.ResetPassword();
                    adminMember.ChangePassword(generatedPass, p.password);
                }
                if (p.name != oldAdmin.name)
                {
                    Guid         userID = (Guid)adminMember.ProviderUserKey;
                    aspnet_Users user   = db.aspnet_Users.Where(us => us.UserId == userID).FirstOrDefault();
                    user.UserName        = p.name;
                    user.LoweredUserName = p.name.ToLower();
                }
                Membership.UpdateUser(adminMember);
                db.SaveChanges();;

                if (p.name != User.Identity.Name || p.password != oldPassword)
                {
                    FormsAuthentication.SignOut();
                    Session.Abandon();
                    var    oldAuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName];//my authenticated cookie
                    var    isPersistent  = FormsAuthentication.Decrypt(oldAuthCookie.Value).IsPersistent;
                    string userImage     = FormsAuthentication.Decrypt(oldAuthCookie.Value).UserData;
                    FormsAuthenticationTicket oldticket = FormsAuthentication.Decrypt(oldAuthCookie.Value);
                    string oldCookieName = oldticket.Name;
                    var    cookie        = FormsAuthentication.GetAuthCookie(p.name, isPersistent);
                    var    currentticket = FormsAuthentication.Decrypt(cookie.Value);
                    var    newticket     = new FormsAuthenticationTicket
                                               (oldticket.Version, currentticket.Name, oldticket.IssueDate, oldticket.Expiration, oldticket.IsPersistent, userImage, "/admin");
                    cookie.Value = FormsAuthentication.Encrypt(newticket);
                    Request.Cookies.Remove(oldCookieName);
                    if (isPersistent)
                    {
                        cookie.Expires = newticket.Expiration;
                    }
                    cookie.Path = newticket.CookiePath;
                    Response.Cookies.Add(cookie);
                }
                return(Json(new { mess = "your profile is updated successfully", result = true }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #11
0
        public void ChangePassword(string oldPassword, string newPassword)
        {
            MembershipUser u = Membership.GetUser();

            u.ChangePassword(oldPassword, newPassword);
        }
コード例 #12
0
        public bool ResetPassword(string Email, Control theControl)
        {
            MembershipUser user = null;

            if (!String.IsNullOrEmpty(Email))
            {
                MembershipUserCollection membershipCollection = Membership.FindUsersByEmail(Email);
                foreach (MembershipUser userEnum in membershipCollection)
                {
                    user = userEnum;
                    break;
                }
            }

            if (user != null)
            {
                Assembly _assembly = Assembly.GetExecutingAssembly();

                string sBody = String.Empty;
                using (StreamReader oTextStream = new StreamReader(_assembly.GetManifestResourceStream("Carrotware.CMS.Core.Security.EmailForgotPassMsg.txt"))) {
                    sBody = oTextStream.ReadToEnd();
                }

                if (user.IsLockedOut && user.LastLockoutDate < DateTime.Now.AddMinutes(-45))
                {
                    user.UnlockUser();
                }

                string tmpPassword = user.ResetPassword();                 // set to known password
                string newPassword = GenerateSimplePassword();             // create simpler password

                user.ChangePassword(tmpPassword, newPassword);             // set to simpler password

                EmailSender mailer = new EmailSender {
                    Recepient    = user.Email,
                    MailSubject  = "Password Reset",
                    TemplateFile = null,
                    Body         = sBody,
                    IsHTML       = false,
                    WebControl   = theControl
                };

                string strHTTPHost = "";
                try { strHTTPHost = HttpContext.Current.Request.ServerVariables["HTTP_HOST"] + ""; } catch { strHTTPHost = ""; }

                string strHTTPProto = "http://";
                try {
                    strHTTPProto = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"] + "";
                    if (strHTTPProto == "1")
                    {
                        strHTTPProto = "https://";
                    }
                    else
                    {
                        strHTTPProto = "http://";
                    }
                } catch { }

                strHTTPHost = strHTTPProto + strHTTPHost.ToLower();

                mailer.ContentPlaceholders.Add("{%%UserName%%}", user.UserName);
                mailer.ContentPlaceholders.Add("{%%Password%%}", newPassword);
                mailer.ContentPlaceholders.Add("{%%SiteURL%%}", strHTTPHost);
                if (SiteData.CurretSiteExists)
                {
                    mailer.ContentPlaceholders.Add("{%%Time%%}", SiteData.CurrentSite.Now.ToString());
                }
                else
                {
                    mailer.ContentPlaceholders.Add("{%%Time%%}", DateTime.Now.ToString());
                }

                mailer.SendMail();

                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #13
0
ファイル: NZManageUsers.ascx.cs プロジェクト: OOcm1987/Nexso
    /// <summary>
    /// Update information of the user (if user is administrator is not possible change the password)
    /// This Method also update the user information in DNN
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.UpdateCommandName)
        {
            if (e.Item is GridEditableItem)
            {
                GridEditableItem editItem  = (GridEditableItem)e.Item;
                TextBox          txtUserId = (TextBox)editItem.FindControl("txtUserId");
                int userId;
                if (txtUserId.Text == string.Empty)
                {
                    userId = 0;
                }
                else
                {
                    userId = Convert.ToInt32(txtUserId.Text);
                }

                // Get controls
                RadTextBox  txtEmail              = (RadTextBox)editItem.FindControl("txtEmail");
                RadTextBox  txtFirstName          = (RadTextBox)editItem.FindControl("txtFirstName");
                RadTextBox  txtLastName           = (RadTextBox)editItem.FindControl("txtLastName");
                RadTextBox  txtPhone              = (RadTextBox)editItem.FindControl("txtTelephone");
                RadTextBox  txtAddress            = (RadTextBox)editItem.FindControl("txtAddress");
                RadTextBox  txtLinkedIn           = (RadTextBox)editItem.FindControl("txtLinkedIn");
                RadTextBox  txtGoogle             = (RadTextBox)editItem.FindControl("txtGoogle");
                RadTextBox  txtTwitter            = (RadTextBox)editItem.FindControl("txtTwitter");
                RadTextBox  txtFacebook           = (RadTextBox)editItem.FindControl("txtFacebook");
                RadTextBox  txtSkype              = (RadTextBox)editItem.FindControl("txtSkypeName");
                RadComboBox ddLanguage            = (RadComboBox)editItem.FindControl("ddLanguage");
                RadComboBox ddCustomerType        = (RadComboBox)editItem.FindControl("ddCustomerType");
                RadComboBox ddNexsoEnrolment      = (RadComboBox)editItem.FindControl("ddNexsoEnrolment");
                RadComboBox ddUserTheme           = (RadComboBox)editItem.FindControl("ddUserTheme");
                RadComboBox ddUserBeneficiaries   = (RadComboBox)editItem.FindControl("ddUserBeneficiaries");
                RadComboBox ddUserSector          = (RadComboBox)editItem.FindControl("ddUserSector");
                RadTextBox  txtOtherSocialNetwork = (RadTextBox)editItem.FindControl("txtOtherSocialNetwork");
                CheckBox    chkNotifications      = (CheckBox)editItem.FindControl("chkNotifications");
                RadTextBox  txtPassword           = (RadTextBox)editItem.FindControl("txtPassword");
                if (userId == 0)
                {
                    if (txtEmail.Text != string.Empty)
                    {
                        int totalUsers = 0;
                        UserController.GetUsersByUserName(PortalId, txtEmail.Text, 1, 1, ref totalUsers);
                        if (totalUsers == 0)
                        {
                            //Update DNN Information
                            var objUser = new DotNetNuke.Entities.Users.UserInfo();
                            objUser.AffiliateID               = Null.NullInteger;
                            objUser.Email                     = txtEmail.Text;
                            objUser.FirstName                 = txtFirstName.Text;
                            objUser.IsSuperUser               = false;
                            objUser.LastName                  = txtLastName.Text;
                            objUser.PortalID                  = PortalController.GetCurrentPortalSettings().PortalId;
                            objUser.Username                  = txtEmail.Text;
                            objUser.DisplayName               = txtFirstName.Text + " " + txtLastName.Text;
                            objUser.Membership.LockedOut      = false;
                            objUser.Membership.Password       = txtPassword.Text;
                            objUser.Membership.Email          = objUser.Email;
                            objUser.Membership.Username       = objUser.Username;
                            objUser.Membership.UpdatePassword = false;
                            objUser.Membership.LockedOut      = false;
                            objUser.Membership.Approved       = true;
                            DotNetNuke.Security.Membership.UserCreateStatus objCreateStatus =
                                DotNetNuke.Entities.Users.UserController.CreateUser(ref objUser);
                            if (objCreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
                            {
                                UserInfo myDnnUser = objUser;
                                myDnnUser.Profile.InitialiseProfile(myDnnUser.PortalID);
                                myDnnUser.Profile.SetProfileProperty("FirstName", txtFirstName.Text);
                                myDnnUser.Profile.SetProfileProperty("LastName", txtLastName.Text);
                                UserController.UpdateUser(myDnnUser.PortalID, myDnnUser);
                                //Update Nexso information
                                userPropertyComponent = new UserPropertyComponent(objUser.UserID);
                                //Update DNN roles
                                if (!objUser.IsInRole("Registered Users"))
                                {
                                    var oDnnRoleController = new RoleController();

                                    RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, "Registered Users");
                                    oDnnRoleController.AddUserRole(this.PortalId, objUser.UserID, oCurrentRole.RoleID,
                                                                   System.DateTime.Now.AddDays(-1),
                                                                   DotNetNuke.Common.Utilities.Null.NullDate);
                                }
                                if (!objUser.IsInRole("NexsoUser"))
                                {
                                    var      oDnnRoleController = new RoleController();
                                    RoleInfo oCurrentRole       = oDnnRoleController.GetRoleByName(this.PortalId, "NexsoUser");
                                    oDnnRoleController.AddUserRole(this.PortalId, objUser.UserID, oCurrentRole.RoleID,
                                                                   System.DateTime.Now.AddDays(-1),
                                                                   DotNetNuke.Common.Utilities.Null.NullDate);
                                }
                                ExistEmail = false;
                            }
                            else
                            {
                                ExistEmail = true;
                                return;
                            }
                        }
                        else
                        {
                            ExistEmail = true;
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    userPropertyComponent = new UserPropertyComponent(userId);
                    if (txtEmail.Text != string.Empty)
                    {
                        UserInfo myDnnUser = DotNetNuke.Entities.Users.UserController.GetUser(PortalSettings.PortalId, userId, true);
                        myDnnUser.Profile.InitialiseProfile(myDnnUser.PortalID);
                        myDnnUser.Profile.SetProfileProperty("FirstName", txtFirstName.Text);
                        myDnnUser.Profile.SetProfileProperty("LastName", txtLastName.Text);

                        if (!myDnnUser.IsInRole("Administrators"))
                        {
                            if (txtPassword.Text != string.Empty)
                            {
                                MembershipUser usr = Membership.GetUser(myDnnUser.Username, false);
                                if (usr.IsLockedOut == true)
                                {
                                    usr.UnlockUser();
                                }
                                string resetPassword = usr.ResetPassword();
                                bool   sw            = usr.ChangePassword(resetPassword, txtPassword.Text);
                            }
                        }
                        // myDnnUser.Profile.SetProfileProperty("Password", txtPassword.Text);
                        UserController.UpdateUser(myDnnUser.PortalID, myDnnUser);
                        if (!myDnnUser.IsInRole("NexsoUser"))
                        {
                            var oDnnRoleController = new RoleController();

                            RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, "NexsoUser");
                            oDnnRoleController.AddUserRole(this.PortalId, myDnnUser.UserID, oCurrentRole.RoleID,
                                                           System.DateTime.Now.AddDays(-1),
                                                           DotNetNuke.Common.Utilities.Null.NullDate);
                        }
                    }
                }
                userPropertyComponent.UserProperty.FirstName = txtFirstName.Text;
                userPropertyComponent.UserProperty.LastName  = txtLastName.Text;
                userPropertyComponent.UserProperty.Telephone = txtPhone.Text;
                userPropertyComponent.UserProperty.email     = txtEmail.Text;
                userPropertyComponent.UserProperty.SkypeName = txtSkype.Text;
                userPropertyComponent.UserProperty.Twitter   = txtTwitter.Text;
                userPropertyComponent.UserProperty.FaceBook  = txtFacebook.Text;
                userPropertyComponent.UserProperty.Google    = txtGoogle.Text;
                userPropertyComponent.UserProperty.LinkedIn  = txtLinkedIn.Text;
                userPropertyComponent.UserProperty.Address   = txtAddress.Text;
                userPropertyComponent.UserProperty.Agreement = "A001";
                userPropertyComponent.UserProperty.AllowNexsoNotifications = Convert.ToInt32(chkNotifications.Checked);

                if (ddCustomerType.SelectedValue != string.Empty)
                {
                    userPropertyComponent.UserProperty.CustomerType = Convert.ToInt32(ddCustomerType.SelectedValue);
                }
                if (ddNexsoEnrolment.SelectedValue != string.Empty)
                {
                    userPropertyComponent.UserProperty.NexsoEnrolment = Convert.ToInt32(ddNexsoEnrolment.SelectedValue);
                }
                if (ddLanguage.SelectedValue != string.Empty)
                {
                    userPropertyComponent.UserProperty.Language = Convert.ToInt32(ddLanguage.SelectedValue);
                }

                if (userPropertyComponent.Save() > 0)
                {
                    SaveChkControl("Theme", ddUserTheme, userPropertyComponent.UserProperty.UserId);
                    SaveChkControl("Beneficiaries", ddUserBeneficiaries, userPropertyComponent.UserProperty.UserId);
                    SaveChkControl("Sector", ddUserSector, userPropertyComponent.UserProperty.UserId);
                }
                if (editItem.ItemIndex != -1)
                {
                    this.grdManageUsers.MasterTableView.Items[editItem.ItemIndex].Edit = false;
                }
                else
                {
                    e.Item.OwnerTableView.IsItemInserted = false;
                }

                this.grdManageUsers.MasterTableView.Rebind();
            }
        }
    }
コード例 #14
0
        /// <summary>
        /// Cambia el password de un usuario
        /// </summary>
        /// <param name="userName">Nombre del Usuario</param>
        /// <param name="pOldPassword">Password Viejo</param>
        /// <param name="pNewPassword">Password Nuevo</param>
        /// <param name="providerName">Nombre del proveedor de membership</param>
        /// <returns>Bool indicando el resultado de la operación</returns>
        public static Boolean ChangeUserPassword(String userName, String pOldPassword, String pNewPassword, string providerName)
        {
            MembershipUser wUser = GetMembershipUser(userName, providerName);

            return(wUser.ChangePassword(pOldPassword, pNewPassword));
        }
コード例 #15
0
    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);
    }
コード例 #16
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string username = txtusername.Text.Trim();
            string password = Membership.GeneratePassword(6, 1);

            try
            {
                MembershipUser mu = Membership.GetUser(username);

                if (mu != null)
                {
                    mu.ChangePassword(mu.ResetPassword(), password);
                }

                else
                {
                    lblmessage.Text = "Username " + txtusername.Text + " could not be found";
                    return;
                }
            }

            catch (MembershipPasswordException mpe)
            {
                lblmessage.Text = mpe.Message.ToString();
                return;
            }

            catch (Exception ex)
            {
                lblmessage.Text = ex.Message.ToString();
                return;
            }
            lblmessage.Text = "Password successfully reset to : " + "<b>" + password + "</b>";

            thescruffsterDataContext db = new thescruffsterDataContext();
            var name = db.SecretSantas.SingleOrDefault(x => x.Email == username).Name.Trim().ToLower();



            string nickname;

            switch (name)
            {
            case "tanja":
                nickname = "Sistah";
                break;

            case "christoph":
                nickname = "Big Nasty";
                break;

            case "jade":
                nickname = "Love";
                break;

            case "shelly":
                nickname = "Sis in law";
                break;

            case "delisa":
                nickname = "Sis in law";
                break;

            case "adam":
                nickname = "Twin";
                break;

            case "ray":
                nickname = "Bro in law";
                break;

            default:
                nickname = name;
                break;
            }


            //  SendEmail(username, password, nickname);
        }
    public bool ChangePasswordCustom(User user, string oldPassword,string newPassword)
    {
        //MembershipUserCollection MembershipUsers = new MembershipUserCollection();
           // MembershipUsers.Add( new MembershipUser(Membership.Provider.Name, user.Username, user.UserId, user.Email, null, null, user.IsApproved, user.IsLockedOut, user.CreateDate.Value, user.LastLoginDate.Value, user.LastActivityDate.Value, user.LastPasswordChangedDate.Value, user.LastLockoutDate.Value));
            //MembershipUsers[0].ChangePassword(oldPassword, newPassword);

            var membershipUser = new MembershipUser(Membership.Provider.Name, user.Username, user.UserId, user.Email, null, null, user.IsApproved, user.IsLockedOut, user.CreateDate.Value, user.LastLoginDate.Value, user.LastActivityDate.Value, user.LastPasswordChangedDate.Value, user.LastLockoutDate.Value);
            return membershipUser.ChangePassword(oldPassword, newPassword);
    }
コード例 #18
0
        protected void cmdSave_Click(object sender, EventArgs e)
        {
            try
            {
                //### validate provided input parameters
                //verify if the username already exists - if not, the user wants to change the username
                MembershipUser oldUser  = Membership.GetUser(lbUsers.SelectedItem.Text);
                MembershipUser newUser  = null;
                ProfileBase    profile  = null;
                string         userName = lbUsers.SelectedItem.Text;

                if (oldUser.UserName != txtUserName.Text)
                {
                    // the username was changed: delete the old user & create a new one
                    Membership.DeleteUser(oldUser.UserName);
                    newUser  = Membership.CreateUser(txtUserName.Text, txtPwd.Text, txtEmail.Text);
                    profile  = ProfileBase.Create(newUser.UserName);
                    userName = txtUserName.Text;
                    Roles.AddUserToRole(userName, cmbRole.SelectedItem.Text);
                }
                else
                {
                    //update the user
                    string oldPwd = oldUser.GetPassword();
                    oldUser.ChangePassword(oldPwd, txtPwd.Text);
                    oldUser.Email = txtEmail.Text;

                    Membership.UpdateUser(oldUser);

                    if (Roles.IsUserInRole(oldUser.UserName, C.eUserRoles.Administrateur.ToString()))
                    {
                        Roles.RemoveUserFromRole(oldUser.UserName, C.eUserRoles.Administrateur.ToString());
                    }
                    if (Roles.IsUserInRole(oldUser.UserName, C.eUserRoles.Utilisateur.ToString()))
                    {
                        Roles.RemoveUserFromRole(oldUser.UserName, C.eUserRoles.Utilisateur.ToString());
                    }

                    if (!Roles.IsUserInRole(oldUser.UserName, cmbRole.SelectedItem.Text))
                    {
                        Roles.AddUserToRole(oldUser.UserName, cmbRole.SelectedItem.Text);
                    }

                    profile = ProfileBase.Create(oldUser.UserName);
                }

                if (profile != null)
                {
                    profile["FirstName"] = txtFirstName.Text;
                    profile["LastName"]  = txtLastName.Text;

                    profile.Save();
                }

                RefreshUserList(userName);
            }
            catch (Exception ex)
            {
                var myCustomValidator = new CustomValidator();
                myCustomValidator.IsValid      = false;
                myCustomValidator.ErrorMessage = ex.Message;
                Page.Validators.Add(myCustomValidator);
            }
        }
コード例 #19
0
        protected void btnChgPwd_Click(object sender, EventArgs e)
        {
            int CurrentCustomerID = ThisCustomer.CustomerID;

            PopulateFields(ctrlLogin.Controls);

            String EMailField    = tbCustomerEmail.Text.ToLowerInvariant();
            String PasswordField = tbOldPassword.Text;
            String newpwd        = tbNewPassword.Text;
            String confirmpwd    = tbNewPassword2.Text;

            lblPwdChgErr.Text    = "";
            lblPwdChgErr.Visible = false;

            bool LoginOK = false;

            ThisCustomer = new Customer(EMailField, true);
            if (ThisCustomer.IsRegistered)
            {
                LoginOK = System.Web.Security.Membership.ValidateUser(EMailField, PasswordField);
                if (LoginOK)
                {
                    if (ThisCustomer.IsAdminUser)
                    {
                        Security.LogEvent("Admin Password Changed", "", ThisCustomer.CustomerID, ThisCustomer.CustomerID, 0);
                    }

                    MembershipUser user = System.Web.Security.Membership.GetUser(EMailField);

                    if (ValidatePassword(newpwd) && user.ChangePassword(PasswordField, newpwd))
                    {
                        pnlForm.Visible      = false;
                        ExecutePanel.Visible = true;
                        pnlChangePwd.Visible = false;

                        AppLogic.ExecuteSigninLogic(CurrentCustomerID, ThisCustomer.CustomerID);

                        String CustomerGUID = ThisCustomer.CustomerGUID.Replace("{", "").Replace("}", "");

                        SignInExecuteLabel.Text = AppLogic.GetString("signin.aspx.24", m_SkinID, ThisCustomer.LocaleSetting);

                        string sReturnURL = FormsAuthentication.GetRedirectUrl(CustomerGUID, ctrlLogin.RememberMeSet);
                        FormsAuthentication.SetAuthCookie(CustomerGUID, ctrlLogin.RememberMeSet);

                        if (sReturnURL.Length == 0)
                        {
                            sReturnURL = lblReturnURL.Text;
                        }
                        if (sReturnURL.Length == 0)
                        {
                            if (cbDoingCheckout.Checked)
                            {
                                sReturnURL = "~/shoppingcart.aspx";
                            }
                            else
                            {
                                sReturnURL = "~/default.aspx";
                            }
                        }
                        Response.AddHeader("REFRESH", "1; URL=" + Server.UrlDecode(sReturnURL));

                        ctrlRecoverPassword.Visible = false;
                    }
                }
                else
                {
                    lblPwdChgErr.Text   += "" + AppLogic.GetString("signin.aspx.29", m_SkinID, ThisCustomer.LocaleSetting);
                    lblPwdChgErr.Visible = true;
                    if (ThisCustomer.IsAdminUser)
                    {
                        ThisCustomer.UpdateCustomer(
                            /*CustomerLevelID*/ null,
                            /*EMail*/ null,
                            /*SaltedAndHashedPassword*/ null,
                            /*SaltKey*/ null,
                            /*DateOfBirth*/ null,
                            /*Gender*/ null,
                            /*FirstName*/ null,
                            /*LastName*/ null,
                            /*Notes*/ null,
                            /*SkinID*/ null,
                            /*Phone*/ null,
                            /*AffiliateID*/ null,
                            /*Referrer*/ null,
                            /*CouponCode*/ null,
                            /*OkToEmail*/ null,
                            /*IsAdmin*/ null,
                            /*BillingEqualsShipping*/ null,
                            /*LastIPAddress*/ null,
                            /*OrderNotes*/ null,
                            /*SubscriptionExpiresOn*/ null,
                            /*RTShipRequest*/ null,
                            /*RTShipResponse*/ null,
                            /*OrderOptions*/ null,
                            /*LocaleSetting*/ null,
                            /*MicroPayBalance*/ null,
                            /*RecurringShippingMethodID*/ null,
                            /*RecurringShippingMethod*/ null,
                            /*BillingAddressID*/ null,
                            /*ShippingAddressID*/ null,
                            /*GiftRegistryGUID*/ null,
                            /*GiftRegistryIsAnonymous*/ null,
                            /*GiftRegistryAllowSearchByOthers*/ null,
                            /*GiftRegistryNickName*/ null,
                            /*GiftRegistryHideShippingAddresses*/ null,
                            /*CODCompanyCheckAllowed*/ null,
                            /*CODNet30Allowed*/ null,
                            /*ExtensionData*/ null,
                            /*FinalizationData*/ null,
                            /*Deleted*/ null,
                            /*Over13Checked*/ null,
                            /*CurrencySetting*/ null,
                            /*VATSetting*/ null,
                            /*VATRegistrationID*/ null,
                            /*StoreCCInDB*/ null,
                            /*IsRegistered*/ null,
                            /*LockedUntil*/ null,
                            /*AdminCanViewCC*/ null,
                            /*BadLogin*/ 1,
                            /*Active*/ null,
                            /*PwdChangeRequired*/ null,
                            /*RegisterDate*/ null,
                            /*StoreId*/ null
                            );
                    }
                    return;
                }
            }
            else
            {
                lblPwdChgErr.Text    = "" + AppLogic.GetString("lat_signin_process.aspx.1", m_SkinID, ThisCustomer.LocaleSetting);
                lblPwdChgErr.Visible = pnlPasswordChangeError.Visible = true;
                return;
            }
        }
コード例 #20
0
    protected void btnSifreYenile_Click(object sender, EventArgs e)
    {
        try
        {
            MembershipUser mu        = Membership.GetUser();
            string         yeniSifre = txtYeniSifre.Text;
            bool           kontrol   = mu.ChangePassword(txtEskiSifre.Text, yeniSifre);

            if (!kontrol)
            {
                lblSifreDegistirmeSonuc.Text = "Eski şifrenizi kontrol ediniz!";
            }
            else
            {
                Membership.UpdateUser(mu);
                if (mu.UserName != "doxa")
                {
                    Roles.RemoveUserFromRole(mu.UserName, "User");
                }
                Panel1.Visible          = false;
                txtEskiSifre.Text       = "";
                txtYeniSifre.Text       = "";
                txtYeniSifreTekrar.Text = "";

                SmtpClient  smtp     = new SmtpClient();
                MailAddress sndr     = new MailAddress("*****@*****.**", "fatihyildizhan.com__Aktivasyon E-Postası ", Encoding.Default);
                MailAddress receiver = new MailAddress(mu.Email, "Sayın " + mu.UserName, Encoding.Default);
                MailMessage mail     = new MailMessage(sndr, receiver);

                string        onayKodu = Guid.NewGuid().ToString();
                ProfileCommon pf       = Profile.GetProfile(mu.UserName);
                pf.uyeINFO.OnayKodu = onayKodu;
                pf.Save();
                mail.Subject = "Üyelik Aktivasyonu";
                mail.Body    = "<P>Merhaba Sayın&nbsp;" + mu.UserName + ",</P><P>&nbsp;&nbsp;&nbsp; Aktivasyon Kodunuz : " + onayKodu + "</P><P>&nbsp;&nbsp;Aktivasyon için <A title=Tıkla... href=" + "https://www.fatihyildizhan.com/userOnay.aspx" + " target=_blank>Tıkla...</A></P><P>&nbsp;&nbsp; Beklenmedik bir hata oluştuğunda lütfen <A href=" + "mailto:[email protected]" + ">[email protected]</A> adresine mail atınız. Mesajınız en geç 1 gün içerisinde cevaplanacaktır.</P><P>Sitenin içeriği Programlama Dilleri, Programlar, Haberler ve Download bölümlerinden oluşmaktadır. İstek ve Önerileriniz için iletişim bölümünü kullanabilirsiniz...&nbsp;&nbsp;<BR><BR>Son Eklenen Özellikler...<BR><SPAN class=style7><BR class=style6></SPAN><STRONG><U><FONT size=2><SPAN class=style6><SPAN class=style7>*** SSL desteği eklenmiştir...Bilgileri sitenin altındaki logodan edinebilirsiniz;</SPAN></SPAN><BR><BR></FONT></U>** Haberler bölümünden RSS leri takip edebilirsiniz ;<BR>** Java Uygulamaları ;<BR>** C# Uygulamaları ;<BR><BR></STRONG>*** Programlama Dilleri'ndeki mevcut konular için RSS yayını başlamıştır;<BR>(Sayfanın altında RSS linkini bulabilirsiniz..)<BR><BR>*** Sql Cache Dependency ;<I><BR></I>(SqlCache Dependency Nedir ? Sayfayı herhangi bir değişiklik olana kadar serverda saklar ve sitenin çalışma performansını artırır.)<BR><BR>Şuanda Kullanabileceğiniz Özellikler...<BR><BR>*Programla Dillerine İstatistik;<BR>* Üyelik Sistemi ;<BR>-- Üyeler arası mesajlaşma ;<BR>&nbsp;&nbsp;&nbsp; -Gelen Kutusu, Yenile, Mesaj Oku...<BR>&nbsp;&nbsp;&nbsp; *Giden Kutusu Yakında...<BR>* E-Posta ile Aktivasyon İşlemi ;<BR>* Detaylı Üye Profili Oluşturma / Düzenleme ;<BR>* Her konu için örneğin: destek istemek , tavsiyede bulunmak için iletişim paneli ;<BR>* Basit şekilde Java / Uygulama İndirme ;<BR>* Yönetici için Admin Paneli ;<BR><BR>Yakında Kullanıma Sunulacak Özellikler...<BR><BR>* Üyelere özel site ayarları örneğin: Size özel arkaplan rengi , buton rengi , arayüz dili ..<BR>* Üyelere özel istatistik bilgileri ..<BR>* Diğer yazılım dilleri için uygulama indirebilme ..<BR><BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Görüşmek Üzere...<BR></P>";

                mail.BodyEncoding = Encoding.Default;
                mail.IsBodyHtml   = true;
                mail.Priority     = MailPriority.Normal;
                smtp.Send(mail);
                if (CheckBox1.Checked)
                {
                    mail.Subject = "Üyelik Bilgileri";
                    mail.Body    = "Merhaba Sayın " + mu.UserName + ",<br/> Üye bilgilerinizi başarıyla güncellediniz. Güncel Bilgileriniz Şunlar: <br/><br/> Kullanıcı Adınız: " + mu.UserName + "<br/> Şifreniz: " + yeniSifre + "<br/><br/>Siteye Giriş yapmak için aşağıdaki linki kullanabilirsiniz. <a href=" + "http://www.fatihyildizhan.com/index.aspx  <br/>Giriş Yapmak İçin Tıklayınız.</a> <br/><br/> Linkin üzerine geldiğinize alt scroll barda gideceği adresi görebilirsiniz...<br/><br/>Şuanda Kullanabileceğiniz Özellikler...<br/><br/>* Üyelik Sistemi ;<br/>* E-Posta ile Aktivasyon İşlemi ;<br/>*Detaylı Üye Profili Oluşturma / Düzenleme ;<br/>* Her konu için örneğin: destek istemek , tavsiyede bulunmak için iletişim paneli ;<br/>* Basit şekilde Java / Uygulama İndirme ;<br/>* Yönetici için Admin Paneli ;<br/><br/>Yakında Kullanıma Sunulacak Özellikler...<br/><br/>* Üyeler arası mesajlaşma ..<br/>* Üyelere özel site ayarları örneğin: Size özel arkaplan rengi , buton rengi , arayüz dili ..<br/>* Üyelere özel istatistik bilgileri ..<br/>* Diğer yazılım dilleri için uygulama indirebilme ..<br/>* Download bölümünden program indirebilme ..<br/>* Şifre değiştirebilme ..<br/><br/>Admin E-Posta Adresi: [email protected] <br/> www.fatihyildizhan.com";
                    yeniSifre    = "";
                    smtp.Send(mail);
                }
                Response.Redirect("https://www.fatihyildizhan.com/login.aspx");
            }
        }
        catch (Exception ex)
        {
            try
            {
                System.Net.Mail.SmtpClient  smtp     = new System.Net.Mail.SmtpClient();
                System.Net.Mail.MailAddress sndr     = new System.Net.Mail.MailAddress("*****@*****.**");
                System.Net.Mail.MailAddress receiver = new System.Net.Mail.MailAddress("*****@*****.**", "FyDoxaAdmin");
                string ip    = Request.ServerVariables["REMOTE_ADDR"].ToString();
                string zaman = DateTime.Now.ToLongTimeString();
                string hata  = "Inner Exception";
                if (Server.GetLastError().InnerException != null)
                {
                    hata = Server.GetLastError().InnerException.Message;
                }

                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(sndr, receiver);
                mail.Subject      = "User pwdchange aspx Hatası";
                mail.Body         = "Hata Oluşma Zamanı : " + zaman + " <br/> Ip Adresi : " + ip + " <br/> Yardımcı Link : " + Server.GetLastError().HelpLink + " <br/> Oluşan Son Hata : " + Server.GetLastError().ToString() + " <br/> Inner Exception : " + hata + "  <br/> Son Oluşan Hata'nın Data Bilgisi : " + Server.GetLastError().Data.ToString() + "Exception Adı : " + ex.ToString();
                mail.BodyEncoding = Encoding.Default;
                mail.IsBodyHtml   = true;
                mail.Priority     = System.Net.Mail.MailPriority.Normal;
                smtp.Send(mail);
            }
            catch (Exception)
            {
            }
            Response.Redirect(Request.RawUrl);
        }
    }
コード例 #21
0
    protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        #region automagically unlock user after set amount of time

        Login Login1 = GetLogin1();

        // get the current user's info
        MembershipUser usrInfo = Membership.GetUser(Login1.UserName, false);

        // if lockout datetime + lockout duration is less than datetime now
        if (usrInfo != null && usrInfo.IsLockedOut && usrInfo.LastLockoutDate.ToUniversalTime().AddMinutes(passwordAttemptLockoutDuration) < DateTime.UtcNow)
        {
            // then automatically Unlock user
            usrInfo.UnlockUser();
        }

        #endregion

        #region check for password expiration, auto reset password, and email new one to user

        // if auto password expiration is enabled on top of page
        if (passwordResetEnabled != true)
        {
            return;
        }

        // if last password changed date + reset duration is less than the date now
        if (usrInfo == null || usrInfo.LastPasswordChangedDate.ToUniversalTime().AddDays(passwordResetDuration) >= DateTime.UtcNow)
        {
            return;
        }

        // set user's approval to false so user can't login
        usrInfo.IsApproved = false;
        UpdateUserInfo(usrInfo);

        // Create random GUID for new password - (its nasty long but works if many thousands of users are present)
        Guid randomPasswordGuid = System.Guid.NewGuid();

        // declare variables for user name and password
        string username = Convert.ToString(usrInfo);
        string password = randomPasswordGuid.ToString();

        // get user name (use second membership provider from web.config - does not require question and answer)
        MembershipUser mu = Membership.Providers["dbSqlMemberShipProviderAdmin"].GetUser(username, false);

        // change user password to newly generated guid
        mu.ChangePassword(mu.ResetPassword(), password);

        // set user approval to true so user can now login with new guid password
        usrInfo.IsApproved = true;
        UpdateUserInfo(usrInfo);

        // let the user know that the password has expired.
        lblFailureText.Text    = usrInfo + ", As per our user policy, your account password has expired! An e-mail is being sent with your new credentials.";
        lblFailureText.Visible = true;

        // send new credentials to user via EMAIL
        try
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

            // determine the site's URL so we can use it in the email
            string urlBase = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;

            // get user's new password and  account email so we can email it - mu is already declared above
            string ePassword = mu.GetPassword();

            string eEmail           = mu.Email;
            string eFrom            = FromEmailAddress;
            string eFromDisplayName = "Site Administrator";
            string eSubject         = "Password Reset! - Your new credentials";

            message.To.Add(eEmail);
            message.From       = new MailAddress(eFrom, eFromDisplayName);
            message.Subject    = eSubject;
            message.Body       = "<p>Hello " + usrInfo + ",</p>" + " <p>Your password for " + urlBase + " have been reset:<br/>User Name: " + usrInfo + " <br />Your New Password: "******" <br /> Please use your new password to login to your account and change it to something you can remember.<br/><br/> Thank You!<br/>Webmaster.</p>";
            message.IsBodyHtml = true;
            message.Priority   = MailPriority.High;

            // cool! we only have declare the smtp. System.Net.Mail automatically finds it in web.config
            SmtpClient client = new SmtpClient();
            client.Send(message);
        }
        catch (Exception ex)
        {
            lblFailureText.Text   += " ERROR Sending Mail: " + ex.Message;
            lblFailureText.Visible = true;
        }
        finally
        {
            // do nothing
        }

        #endregion
    }
コード例 #22
0
        public static bool ChangePassword(string OldPassword, string NewPassword)
        {
            MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);

            return(CurrentUser.ChangePassword(OldPassword, NewPassword));
        }
コード例 #23
0
        /// Author:         Josephine Monteza
        /// Date Created:   03/Nov/2015
        /// Description:    Get all Immigartion Users with alternate email to reset pwd
        private void AddEditImmigrationOfficers()
        {
            DataTable dtUser = null;
            DataTable dt     = null;

            string sMsg = "";

            try
            {
                DateTime dtFrom = GlobalCode.Field2DateTime(uoTextBoxFrom.Text);
                DateTime dtTo   = GlobalCode.Field2DateTime(uoTextBoxTo.Text);

                List <UserList_LDAP> list = UserAccountBLL.GetUserList(dtFrom, dtTo, TravelMartVariable.RoleImmigration, true, false, "");
                string sAlternateEmail;
                string sUserName;
                string sPassword;

                string sLastName;
                string sFirstName;
                string sMiddleName;

                string sEmail;

                dt = new DataTable();
                DataColumn col = new DataColumn("UserName", typeof(string));
                dt.Columns.Add(col);
                DataRow row = dt.NewRow();

                for (int i = 0; i < list.Count; i++)
                {
                    sUserName       = list[i].UserName;
                    sAlternateEmail = list[i].AlternateEmail;
                    sLastName       = list[i].LastName;
                    sFirstName      = list[i].FirstName;
                    sMiddleName     = list[i].MiddleName;
                    sEmail          = list[i].Email;

                    MembershipUser mUser = Membership.GetUser(sUserName);
                    if (mUser.IsLockedOut)
                    {
                        mUser.UnlockUser();
                    }

                    sPassword = mUser.ResetPassword();
                    mUser.ChangePassword(sPassword, uoTextBoxNewPassword.Text);
                    mUser.LastActivityDate = DateTime.Now.AddMinutes(-Membership.UserIsOnlineTimeWindow);
                    Membership.UpdateUser(mUser);

                    //Add/modify from LDAP
                    sMsg = sMsg + "\n" + MUser.AddEditUserFromLDAP(sUserName, sFirstName, sLastName, sEmail, sPassword, "", sEmail);
                    MUser.ChangePasswordInLDAP(sUserName, uoTextBoxNewPassword.Text);

                    //remove this since they want Michael Jaworski to send the email manually to the users
                    //UserAccountBLL.EmailUserPassword(sUserName, sPassword, sAlternateEmail);

                    row      = dt.NewRow();
                    row[col] = sUserName;
                    dt.Rows.Add(row);
                }

                //extract the list instead
                dtUser = UserAccountBLL.GetImmigrationUsersToExtract(TravelMartVariable.RoleImmigration, true, uoTextBoxNewPassword.Text, dt);
                if (dtUser != null)
                {
                    if (dtUser.Rows.Count > 0)
                    {
                        CreateFile(dtUser);
                    }
                    else
                    {
                        sMsg = "No User Updated";
                    }
                }

                AlertMessage("Information: " + sMsg);
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message);
            }
            finally
            {
                if (dtUser != null)
                {
                    dtUser.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }
コード例 #24
0
        public string UpdatePassword(string username, string newPassword)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                Regex r = new Regex(PasswordExpression);
                if (!r.IsMatch(newPassword))
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "密码必须是由数字或字母组成的字符串,且最小6位,最大30位!");
                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }

                MembershipUser user = Membership.GetUser(username);
                if (user == null)
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "用户名不存在!");
                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }

                string oldPassword = user.ResetPassword();
                if (!user.ChangePassword(oldPassword, newPassword))
                {
                    sb.Append("<Rsp>");
                    sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                    sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", "修改密码失败,请正确输入并重试");
                    sb.Append("</Rsp>");
                    return(sb.ToString());
                }

                sb.Append("<Rsp>");
                sb.AppendFormat("<IsOk>{0}</IsOk>", true);
                sb.Append("<ErrorMsg></ErrorMsg>");
                sb.Append("</Rsp>");
                return(sb.ToString());
            }
            catch (MembershipPasswordException ex)
            {
                new CustomException(ex.Message, ex);
                StringBuilder sb = new StringBuilder();
                sb.Append("<Rsp>");
                sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", ex.Message);
                sb.Append("</Rsp>");
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                new CustomException(ex.Message, ex);
                StringBuilder sb = new StringBuilder();
                sb.Append("<Rsp>");
                sb.AppendFormat("<IsOk>{0}</IsOk>", false);
                sb.AppendFormat("<ErrorMsg>{0}</ErrorMsg>", ex.Message);
                sb.Append("</Rsp>");
                return(sb.ToString());
            }
        }
コード例 #25
0
        protected void grdUsers_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
        {
            ASPxTextBox tb1 = grdUsers.FindEditRowCellTemplateControl((GridViewDataColumn)grdUsers.Columns["Password"], "txtPWD1") as ASPxTextBox;
            ASPxTextBox tb2 = grdUsers.FindEditRowCellTemplateControl((GridViewDataColumn)grdUsers.Columns["Password"], "txtPWD2") as ASPxTextBox;

            if (grdUsers.IsNewRowEditing)
            {
                // Checks for null values.
                if (e.NewValues["UserName"] == null)
                {
                    e.Errors[grdUsers.Columns["UserName"]] = "User Name cannot be null";
                }

                if (e.NewValues["Email"] == null)
                {
                    e.Errors[grdUsers.Columns["Email"]] = "Email cannot be null";
                }

                if (e.Errors.Count > 0 || chkpwd(tb1.Text, tb2.Text) != null)
                {
                    e.RowError = "Please, correct all errors";
                }
                else
                {
                    string             username = e.NewValues["UserName"].ToString();
                    string             email    = e.NewValues["Email"].ToString();
                    GridViewDataColumn dc       = grdUsers.Columns["IsApproved"] as GridViewDataColumn;
                    ASPxCheckBox       cb       = grdUsers.FindEditRowCellTemplateControl(dc, "chkIsApproved") as ASPxCheckBox;
                    bool isapproved             = cb.Checked;

                    if (username.Length < 3)
                    {
                        e.Errors[grdUsers.Columns["UserName"]] = "User Name must be at least 3 characters long";
                    }

                    if (!(email.Contains("@") && email.Contains(".")))
                    {
                        e.Errors[grdUsers.Columns["Email"]] = "Email is not valid";
                    }
                    if (e.Errors.Count > 0)
                    {
                        e.RowError = "Please, correct all errors";
                    }
                    else
                    {
                        //Add User
                        MembershipCreateStatus status;
                        try
                        {
                            MembershipUser newUser = Membership.CreateUser(username, tb1.Text, email, null, null, isapproved, out status);
                            if (newUser == null)
                            {
                                e.RowError = GetErrorMessage(status);
                            }
                            else
                            {
                                //Get CompanyID of the User
                                string query           = "SELECT CompanyID FROM aspnet_Users WHERE UserName = @UserName";
                                List <SqlParameter> sp = new List <SqlParameter>()
                                {
                                    new SqlParameter()
                                    {
                                        ParameterName = "@UserName", SqlDbType = SqlDbType.NVarChar, Value = User.Identity.Name
                                    }
                                };
                                DataTable dt = DataBase.GetDT(sp, query, "ApplicationServices");

                                if (dt.Rows.Count > 0)
                                {
                                    //add CompanyID
                                    query = "UPDATE aspnet_Users SET CompanyID = @Param1 WHERE UserId = @UserId";
                                    sp    = new List <SqlParameter>()
                                    {
                                        new SqlParameter()
                                        {
                                            ParameterName = "@Param1", SqlDbType = SqlDbType.Int, Value = dt.Rows[0]["CompanyID"]
                                        },
                                        new SqlParameter()
                                        {
                                            ParameterName = "@UserId", SqlDbType = SqlDbType.UniqueIdentifier, Value = new Guid(newUser.ProviderUserKey.ToString())
                                        }
                                    };
                                    int aux = DataBase.UpdateDB(sp, query, "ApplicationServices");
                                }
                            }
                        }
                        catch
                        {
                            e.RowError = "An exception occurred creating the user";
                        }
                    }
                }
            }
            else
            {
                // Checks for null values.
                if (e.NewValues["Email"] == null)
                {
                    e.Errors[grdUsers.Columns["Email"]] = "Email cannot be null";
                }

                if (e.Errors.Count > 0)
                {
                    e.RowError = "Please, fill all fields";
                }
                else
                {
                    string email = e.NewValues["Email"].ToString();

                    if (!(email.Contains("@") && email.Contains(".")))
                    {
                        e.Errors[grdUsers.Columns["Email"]] = "Email is not valid";
                    }

                    if (e.Errors.Count > 0 || chkpwd(tb1.Text, tb2.Text) != null)
                    {
                        e.RowError = "Please, correct all errors";
                    }
                    else if (tb1.Text != "") //attempt to change password
                    {
                        string         strName = grdUsers.GetRowValues(grdUsers.EditingRowVisibleIndex, "UserName").ToString();
                        MembershipUser newuser = Membership.GetUser(strName);
                        try
                        {
                            string oldpwd = newuser.ResetPassword();

                            if (!newuser.ChangePassword(oldpwd, tb1.Text))
                            {
                                e.RowError = "Password change failed. Please re-enter your values and try again.";
                            }
                        }
                        catch (Exception e2)
                        {
                            e.RowError = "An exception occurred: " + Server.HtmlEncode(e2.Message) + ". Please re-enter your values and try again.";
                        }
                    }
                }
            }
        }
コード例 #26
0
ファイル: EditUser.aspx.cs プロジェクト: KerwinMa/Umbraco
        /// <summary>
        /// Handles the Click event of the saveUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        private void saveUser_Click(object sender, ImageClickEventArgs e)
        {
            if (base.IsValid)
            {
                try
                {
                    MembershipUser user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(u.LoginName, true);


                    string tempPassword = ((controls.passwordChanger)passw.Controls[0]).Password;
                    if (!string.IsNullOrEmpty(tempPassword.Trim()))
                    {
                        // make sure password is not empty
                        if (string.IsNullOrEmpty(u.Password))
                        {
                            u.Password = "******";
                        }
                        user.ChangePassword(u.Password, tempPassword);
                    }

                    // Is it using the default membership provider
                    if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is UsersMembershipProvider)
                    {
                        // Save user in membership provider
                        UsersMembershipUser umbracoUser = user as UsersMembershipUser;
                        umbracoUser.FullName = uname.Text.Trim();
                        umbracoUser.Language = userLanguage.SelectedValue;
                        umbracoUser.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue));
                        Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(umbracoUser);

                        // Save user details
                        u.Email    = email.Text.Trim();
                        u.Language = userLanguage.SelectedValue;
                    }
                    else
                    {
                        u.Name     = uname.Text.Trim();
                        u.Language = userLanguage.SelectedValue;
                        u.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue));
                        if (!(Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider))
                        {
                            Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(user);
                        }
                    }


                    u.LoginName = lname.Text;
                    //u.StartNodeId = int.Parse(startNode.Value);


                    int startNode;
                    if (!int.TryParse(contentPicker.Value, out startNode))
                    {
                        //set to default if nothing is choosen
                        if (u.StartNodeId > 0)
                        {
                            startNode = u.StartNodeId;
                        }
                        else
                        {
                            startNode = -1;
                        }
                    }
                    u.StartNodeId = startNode;


                    u.Disabled             = Disabled.Checked;
                    u.DefaultToLiveEditing = DefaultToLiveEditing.Checked;
                    u.NoConsole            = NoConsole.Checked;
                    //u.StartMediaId = int.Parse(mediaStartNode.Value);


                    int mstartNode;
                    if (!int.TryParse(mediaPicker.Value, out mstartNode))
                    {
                        //set to default if nothing is choosen
                        if (u.StartMediaId > 0)
                        {
                            mstartNode = u.StartMediaId;
                        }
                        else
                        {
                            mstartNode = -1;
                        }
                    }
                    u.StartMediaId = mstartNode;

                    u.clearApplications();

                    foreach (ListItem li in lapps.Items)
                    {
                        if (li.Selected)
                        {
                            u.addApplication(li.Value);
                        }
                    }

                    u.Save();

                    // save data
                    if (cName.Text != "")
                    {
                        Channel c;
                        try
                        {
                            c = new Channel(u.Id);
                        }
                        catch
                        {
                            c      = new Channel();
                            c.User = u;
                        }

                        c.Name                  = cName.Text;
                        c.FullTree              = cFulltree.Checked;
                        c.StartNode             = int.Parse(cContentPicker.Value);
                        c.MediaFolder           = int.Parse(cMediaPicker.Value);
                        c.FieldCategoriesAlias  = cCategories.SelectedValue;
                        c.FieldDescriptionAlias = cDescription.SelectedValue;
                        c.FieldExcerptAlias     = cExcerpt.SelectedValue;
                        c.DocumentTypeAlias     = cDocumentType.SelectedValue;

                        //
                        c.MediaTypeAlias        = Constants.Conventions.MediaTypes.Image; // [LK:2013-03-22] This was previously lowercase; unsure if using const will cause an issue.
                        c.MediaTypeFileProperty = Constants.Conventions.Media.File;
                        c.ImageSupport          = true;

                        c.Save();
                    }

                    ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editUserSaved", base.getUser()), "");
                }
                catch (Exception ex)
                {
                    ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", base.getUser()), "");
                    LogHelper.Error <EditUser>("Exception", ex);
                }
            }
            else
            {
                ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", base.getUser()), "");
            }
        }
コード例 #27
0
        protected void tmp_save(object sender, System.EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                if (Member.InUmbracoMemberMode())
                {
                    _document.LoginName = MemberLoginNameTxt.Text;
                    _document.Email     = MemberEmail.Text;

                    // Check if password should be changed
                    string tempPassword = ((controls.passwordChanger)MemberPasswordTxt.Controls[0]).Password;
                    if (tempPassword.Trim() != "")
                    {
                        _document.Password = tempPassword;
                    }

                    // Groups
                    foreach (ListItem li in _memberGroups.Items)
                    {
                        if (("," + _memberGroups.Value + ",").IndexOf("," + li.Value + ",") > -1)
                        {
                            if (!Roles.IsUserInRole(_document.LoginName, li.Value))
                            {
                                Roles.AddUserToRole(_document.LoginName, li.Value);
                            }
                        }
                        else if (Roles.IsUserInRole(_document.LoginName, li.Value))
                        {
                            Roles.RemoveUserFromRole(_document.LoginName, li.Value);
                        }
                    }
                    // refresh cache
                    _document.XmlGenerate(new System.Xml.XmlDocument());
                    _document.Save();
                }
                else
                {
                    m_Member.Email = MemberEmail.Text;
                    if (Membership.Provider.EnablePasswordRetrieval)
                    {
                        string tempPassword = ((controls.passwordChanger)MemberPasswordTxt.Controls[0]).Password;
                        if (tempPassword.Trim() != "")
                        {
                            m_Member.ChangePassword(m_Member.GetPassword(), tempPassword);
                        }
                    }
                    Membership.UpdateUser(m_Member);
                    // Groups
                    foreach (ListItem li in _memberGroups.Items)
                    {
                        if (("," + _memberGroups.Value + ",").IndexOf("," + li.Value + ",") > -1)
                        {
                            if (!Roles.IsUserInRole(m_Member.UserName, li.Value))
                            {
                                Roles.AddUserToRole(m_Member.UserName, li.Value);
                            }
                        }
                        else if (Roles.IsUserInRole(m_Member.UserName, li.Value))
                        {
                            Roles.RemoveUserFromRole(m_Member.UserName, li.Value);
                        }
                    }
                }

                this.speechBubble(BasePages.BasePage.speechBubbleIcon.save,
                                  ui.Text("speechBubbles", "editMemberSaved", base.getUser()), "");
            }
        }
コード例 #28
0
        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            MembershipUser currentUser = GetCurrentUser(userName);

            return(currentUser.ChangePassword(oldPassword, newPassword));
        }
コード例 #29
0
        public ActionResult CreateUser(UserData objuser)
        {
            try
            {
                if (objuser.UserId == null)
                {
                    MembershipUser newUser = Membership.CreateUser(objuser.name, objuser.Password);
                    if (newUser != null)
                    {
                        newUser.IsApproved = objuser.IsApproved;
                        newUser.Email      = objuser.Email;
                        Membership.UpdateUser(newUser);
                        Roles.AddUserToRoles(newUser.UserName, objuser.Roles);
                        TempData["Message"] = "User Created";
                        return(RedirectToAction("Index", "ManageUser"));
                    }
                }
                else
                {
                    Guid           newid = new Guid(objuser.UserId);
                    MembershipUser u     = Membership.GetUser(newid);
                    if (u != null)
                    {
                        //u.Email=objuser.Email ;
                        //Membership.UpdateUser(u);
                        //u.IsApproved= objuser.IsApproved;
                        //Membership.UpdateUser(u);
                        var rolessaved = Roles.GetRolesForUser(u.UserName);
                        if (!string.IsNullOrEmpty(objuser.Password))
                        {
                            u.ChangePassword(u.ResetPassword(), objuser.Password);
                        }

                        if (rolessaved.Count() > 0)
                        {
                            Roles.RemoveUserFromRoles(u.UserName, rolessaved);
                        }
                        Roles.AddUserToRoles(u.UserName, objuser.Roles);
                        var checkusername = context.aspnet_Users.Where(x => x.UserName == objuser.name && x.UserId != newid).Count();
                        var userdetails   = context.aspnet_Membership.Where(x => x.UserId == newid).FirstOrDefault();
                        if (userdetails != null)
                        {
                            userdetails.Email       = objuser.Email;
                            userdetails.IsApproved  = objuser.IsApproved;
                            userdetails.IsLockedOut = objuser.IsLockedOut;
                            userdetails.FailedPasswordAttemptCount = 0;
                            context.SaveChanges();
                        }
                        if (checkusername == 0)
                        {
                            var usernamedata = context.aspnet_Users.Where(x => x.UserId == newid).FirstOrDefault();
                            usernamedata.UserName = objuser.name;
                            context.SaveChanges();
                            TempData["Message"] = "User Updated";
                            return(RedirectToAction("Index", "ManageUser"));
                        }
                        else
                        {
                            TempData["Message"] = "Username already exist";
                        }
                    }
                    else
                    {
                        TempData["Message"] = "Username not exist";
                    }
                }
            }
            catch (MembershipCreateUserException e)
            {
                cm.ErrorExceptionLogingByService(e.ToString(), "ManageUser" + ":" + new StackTrace().GetFrame(0).GetMethod().Name, "CreateUser", "NA", "NA", "NA", "WEB");
                var msg = GetErrorMessage(e.StatusCode);
                TempData["Message"] = msg;
            }
            return(RedirectToAction("SaveUser", new { UserId = objuser.UserId }));
        }
コード例 #30
0
        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);

            return(currentUser.ChangePassword(oldPassword, newPassword));
        }
コード例 #31
0
 bool ChangePassword(MembershipUser user, string password, string newPassword)
 {
     return(user.ChangePassword(password, newPassword));
 }