Beispiel #1
0
    public static string UnlockUser(string userId = "")
    {
        Dictionary <string, string> result = new Dictionary <string, string>()
        {
            { "success", "" }, { "error", "" }
        };
        bool   success  = false;
        string errorMsg = string.Empty;
        Guid   userGuid = Guid.Empty;

        if (!Guid.TryParse(userId.Trim(), out userGuid) ||
            userGuid == Guid.Empty)
        {
            success  = false;
            errorMsg = "Registered user does not exist.";
        }
        else
        {
            MembershipUser mu = Membership.GetUser(userGuid);
            if (mu == null)
            {
                success  = false;
                errorMsg = "Registered user does not exist.";
            }
            else
            {
                success = mu.UnlockUser();
                if (!success)
                {
                    errorMsg = "Failed to unlock account.";
                }
            }
        }

        result["success"] = success.ToString();
        result["error"]   = errorMsg;

        return(JsonConvert.SerializeObject(result, Formatting.None));
    }
Beispiel #2
0
        public ActionResult Unlock(string userName)
        {
            JsonResponse response = new JsonResponse();

            MembershipUser user = membershipService.GetUser(userName);

            try
            {
                user.UnlockUser();
                response.Success      = true;
                response.Message      = "User unlocked successfully!";
                response.Locked       = false;
                response.LockedStatus = (response.Locked) ? "Locked" : "Unlocked";
            }
            catch (Exception)
            {
                response.Success = false;
                response.Message = "User unlocked failed.";
            }

            return(Json(response));
        }
Beispiel #3
0
        public void ChangeUser(RegisterModel register)
        {
            //http://maanehunden.wordpress.com/2009/12/17/things-to-remember-when-using-membership-updateusermembershipuser-user/
            MembershipUser user = Membership.GetUser(register.UserName, register.IsOnline);

            string[] relatedRoles = Roles.GetRolesForUser(register.UserName);
            //if (Membership.ValidateUser(register.UserName, register.Password))
            //{
            user.Comment = register.Comment;
            Membership.UpdateUser(user);
            user.Email = register.Email;
            Membership.UpdateUser(user);
            user.IsApproved = true;//register.IsApproved;
            Membership.UpdateUser(user);
            //if (register.IsLockedOut)
            user.UnlockUser();

            if (register.Password != null && register.Password.Length > 0 && register.OldPassword != null)
            {
                user.ChangePassword(register.OldPassword, register.Password);
            }

            if (relatedRoles != null && relatedRoles.Count() > 0)
            {
                //Removendo o usuario das roles atreladas a ele.
                Roles.RemoveUsersFromRoles(new string[] { register.UserName }, relatedRoles);
            }

            if (register.Roles != null && register.Roles.Count() > 0)
            {
                //Adicionando os papéis novamente
                foreach (var role in register.Roles)
                {
                    Roles.AddUsersToRoles(new string[] { register.UserName }, new string[] { role });
                }
            }
            //Membership.UpdateUser(user);
            //}
        }
Beispiel #4
0
    protected void ButtonReset_Click(object sender, EventArgs e)
    {
        try
        {
            HiddenField hf = (HiddenField)DetailsView1.FindControl("HFUserName");

            MembershipUser currUser = Membership.Providers["MySqlMembershipProviderReset"].GetUser(hf.Value.ToString(), false);
            currUser.ChangePassword(currUser.ResetPassword(), "CC_password1");
            currUser.Comment = "CHANGEPASS";
            if (currUser.IsLockedOut == true)
            {
                currUser.UnlockUser();
            }
            //LiteralConfirm.Text = "Password is: " + u.GetPassword();
            LabelResponse.Text = "Password Reset to 'CC_password1'.";
            messaging.SendEmail(currUser.Email.ToString(), "Password Reset", "Password has been reset, new password is CC_password1");
        }
        catch (Exception ex)
        {
            LabelResponse.Text = "Error: " + ex.ToString();
        }
    }
Beispiel #5
0
 protected void btnUnlock_Click(object sender, EventArgs e)
 {
     if (ddlUser.SelectedIndex > 0)
     {
         try
         {
             MembershipUser user = Membership.GetUser(ddlUser.SelectedItem.Text.Trim(), false);
             user.UnlockUser();
             string str = ddlUser.SelectedItem.Text.Trim() + " Unlocked successfully";
             ClientScript.RegisterStartupScript(GetType(), "success", "<script>alert('" + str + "')</script>");
         }
         catch (Exception ex)
         {
             ClientScript.RegisterStartupScript(GetType(), "Error", "<script>alert('" + ex.Message.ToString() + "')</script>");
         }
         btnClear_Click(sender, e);
     }
     else
     {
         ClientScript.RegisterStartupScript(GetType(), "Information", "<script>alert('Please select User Name')</script>");
     }
 }
Beispiel #6
0
        public ActionResult GetQuestion(string username)
        {
            MembershipUser mu = Membership.GetUser(username);

            if (mu != null)
            {
                if (mu.IsLockedOut)
                {
                    mu.UnlockUser();
                }
                return(Json(new
                {
                    Exist = true,
                    PasswordQuestion = mu.PasswordQuestion
                }));
            }

            return(Json(new
            {
                Exist = false
            }));
        }
Beispiel #7
0
        public ActionResult AdminResetPassword(string user)
        {
            if (!(ModelState.IsValid && Roles.IsUserInRole("Administrator")))
            {
                Response.Redirect("~/Unauthorized");
                return(View());
            }

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

            if (currentUser.IsLockedOut)
            {
                currentUser.UnlockUser();
            }

            string newpassword = currentUser.ResetPassword();

            //Send email to user with new password
            try
            {
                EmailOutbox outEmail = helper.getEmailOutboxForPurpose("password reset");

                string emailBody = "Your password for the Pocket Job Coach has been reset to the temporary password '" + newpassword + "'. Please login and change your password now at http://pjc.gear.host";
                Email.send(outEmail, currentUser.Email, "Pocket Job Coach Password Reset", emailBody);

                Response.Redirect("~/Account/List");
            }
            catch (Exception e)
            {
                debug.createDebugMessageInDatabase(e.ToString());

                Response.Redirect("~/Unauthorized");
            }
            ModelState.AddModelError("", "Password has been reset for " + currentUser.UserName);

            return(View());
        }
        public ActionResult Password(string id, ChangePassword model)
        {
            InfoFormat("User #{0} is changing password for user #{1}...", User.Identity.Name, id);
            MembershipUser user = Membership.GetUser(id);

            if (user == null)
            {
                WarnFormat("Non-existing user #{0}!", id);
                return(new HttpNotFoundResult());
            }

            try
            {
                string reset = user.ResetPassword();
                user.ChangePassword(reset, model.NewPassword);
                SetTempOkMessage("Password for user {0} was changed", model.UserName);
                return(RedirectToAction("index"));
            }catch (MembershipPasswordException mpex)
            {
                Error("Password exception, while changing password for user #" + id, mpex);
                if (mpex.Message.Contains("locked"))
                {
                    user.UnlockUser();
                    SetTempErrorMessage("User {0} was locked, tried to unlock it. Please try changing password again.", model.UserName);
                    return(RedirectToAction("index"));
                }
                ModelState.AddModelError("", mpex.Message);
            }catch (Exception ex)
            {
                Error("Error changing password for user #" + id, ex);
                ModelState.AddModelError("", ex.Message);
            }

            return(View(new ChangePassword {
                UserName = user.UserName
            }));
        }
Beispiel #9
0
        public HttpResponseMessage ResetPassword(string userName)
        {
            MembershipUser user = Membership.GetUser(userName);

            if (user != null)
            {
                if (user.IsLockedOut == true)
                {
                    user.UnlockUser();
                }
                string            oldPassword = user.ResetPassword();
                PasswordGenerator Pwg         = new PasswordGenerator();
                string            newPassword = Pwg.GeneratePassword(6, 32, 1, 1, 1, 1);
                user.ChangePassword(oldPassword, newPassword);

                //TO DO: add send email function.

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }
        }
Beispiel #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                return;
            }

            if (Request["unlock"] != null)
            {
                MembershipUser membershipUser = UserManager.GetUser(Request["unlock"]);
                if (membershipUser != null)
                {
                    membershipUser.UnlockUser();
                }
            }
            else if (Request["delete"] != null)
            {
                MembershipUser currentUser = UserManager.GetUser();
                if (currentUser != null && Request["delete"] != currentUser.UserName)
                {
                    UserManager.DeleteUser(Request["delete"]);
                }
            }
        }
Beispiel #11
0
        private bool AutoUnlockUser(string username)
        {
            MembershipUser mu = this.GetUser(username, false);

            if ((mu != null) &&
                (mu.IsLockedOut) &&
                (mu.LastLockoutDate.ToUniversalTime().AddMinutes(autoUnlockTimeout) < DateTime.UtcNow))
            {
                bool retval = mu.UnlockUser();
                if (retval)
                {
                    return(true);
                }
                else
                {
                    return(false);    //something went wrong with the unlock
                }
            }
            else
            {
                return(false);       //not locked out in the first place
            }
            //or still in lockout period
        }
        public void UnlockUser()
        {
            MembershipCreateStatus status;

            Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
            Assert.IsFalse(Membership.ValidateUser("foo", "bar2"));
            Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
            Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
            Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
            Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));

            // the user should be locked now so the right password should fail
            Assert.IsFalse(Membership.ValidateUser("foo", "barbar!"));

            MembershipUser user = Membership.GetUser("foo");

            Assert.IsTrue(user.IsLockedOut);

            Assert.IsTrue(user.UnlockUser());
            user = Membership.GetUser("foo");
            Assert.IsFalse(user.IsLockedOut);

            Assert.IsTrue(Membership.ValidateUser("foo", "barbar!"));
        }
Beispiel #13
0
        protected void ActivateDeactivateButton_Click(object sender, EventArgs e)
        {
            if (UsersListBox.SelectedItem != null)
            {
                MembershipUser user = Membership.GetUser(UsersListBox.SelectedItem.Value);

                if (user.IsLockedOut)
                {
                    user.UnlockUser();
                    messageText = "Le compte a été débloqué.";
                    Message.Show(MessageType.Success, messageText, this);
                }
                else
                {
                    messageText = "Le compte n'était pas bloqué.";
                    Message.Show(MessageType.Error, messageText, this);
                }
            }
            else
            {
                messageText = "Aucun utilisateur sélectionné.";
                Message.Show(MessageType.Error, messageText, this);
            }
        }
Beispiel #14
0
    protected void ButtonNewUser_Click(object sender, EventArgs e)
    {
        MembershipCreateStatus _return;
        //SnitzMembershipProvider provider = (SnitzMembershipProvider)Membership.Providers["SnitzMembershipProvider"];


        MembershipUser mu = Membership.CreateUser(tbxUserName.Text, tbxPassword.Text, tbxEmail.Text, ".", ".", cbxApproval.Checked, null, out _return);

        switch (_return)
        {
        case MembershipCreateStatus.DuplicateUserName:
            LabelInsertMessage.Text = "Username already exists. Please enter a different user name.";
            break;

        case MembershipCreateStatus.DuplicateEmail:
            LabelInsertMessage.Text = "A username for that e-mail address already exists. Please enter a different e-mail address.";
            break;

        case MembershipCreateStatus.InvalidPassword:
            LabelInsertMessage.Text = "The password provided is invalid. Please enter a valid password value.";
            break;

        case MembershipCreateStatus.InvalidEmail:
            LabelInsertMessage.Text = "The e-mail address provided is invalid. Please check the value and try again.";
            break;

        case MembershipCreateStatus.InvalidAnswer:
            LabelInsertMessage.Text = "The password retrieval answer provided is invalid. Please check the value and try again.";
            break;

        case MembershipCreateStatus.InvalidQuestion:
            LabelInsertMessage.Text = "The password retrieval question provided is invalid. Please check the value and try again.";
            break;

        case MembershipCreateStatus.InvalidUserName:
            LabelInsertMessage.Text = "The user name provided is invalid. Please check the value and try again.";
            break;

        case MembershipCreateStatus.ProviderError:
            LabelInsertMessage.Text = "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            break;

        case MembershipCreateStatus.UserRejected:
            LabelInsertMessage.Text = "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            break;

        case MembershipCreateStatus.Success:
            LabelInsertMessage.Text      = "Member " + tbxUserName.Text + " Inserted Successfully.";
            LabelInsertMessage.ForeColor = Color.Green;
            new SnitzMembershipProvider().UnlockUser(tbxUserName.Text);
            foreach (ListItem item in roles.Items)
            {
                if (item.Selected)
                {
                    Roles.AddUserToRole(tbxUserName.Text, item.Value);
                }
            }

            if (cbxSendEmail.Checked)
            {
                SendEmail(tbxUserName.Text, tbxPassword.Text);
            }
            mu.UnlockUser();
            break;

        default:
            LabelInsertMessage.Text = "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            break;
        }

        tbxUserName.Text     = "";
        tbxPassword.Text     = "";
        tbxEmail.Text        = "";
        cbxApproval.Checked  = false;
        cbxSendEmail.Checked = false;
    }
 public void Unlock(MembershipUser user)
 {
     user.UnlockUser();
 }
Beispiel #16
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();
            }
        }
Beispiel #17
0
//        public async Task<ActionResult> Edit([Bind(Include = "Email,Id")] EditUserViewModel editUser, params string[] selectedRole)
        public async Task <ActionResult> Edit(EditUserViewModel editUser, params string[] selectedRole)
        {
            if (!Security.IsValid("/Admin/Users"))
            {
                return(Redirect("~/"));
            }

            //MembershipUser u = Membership.GetUser(editUser.UserName, false);
            IList <string> userRoles;

            userRoles = await UserManager.GetRolesAsync(editUser.Id);

            editUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
            {
                Selected = userRoles.Contains(x.Name),
                Text     = x.Name,
                Value    = x.Name
            });

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(editUser.Id);

                string test = user.PasswordHash;
                if (user == null)
                {
                    return(HttpNotFound());
                }

                user.UserName  = editUser.UserName;
                user.Email     = editUser.Email;
                user.FirstName = editUser.FirstName;
                user.LastName  = editUser.LastName;
                user.MemberID  = editUser.MemberID ?? 0;

                userRoles = await UserManager.GetRolesAsync(user.Id);

                selectedRole = selectedRole ?? new string[] { };

                var result = await UserManager.AddToRolesAsync(user.Id, selectedRole.Except(userRoles).ToArray <string>());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(editUser));
                }
                result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToArray <string>());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(editUser));
                }

                if (!String.IsNullOrEmpty(editUser.Password))
                {
                    string passwordToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                    result = await UserManager.ResetPasswordAsync(user.Id, passwordToken, editUser.Password);

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        return(View(editUser));
                    }
                }

                if (await UserManager.IsLockedOutAsync(user.Id))
                {
                    MembershipUser u = Membership.GetUser(editUser.UserName, false);

                    u.UnlockUser();
                    await UserManager.ResetAccessFailedCountAsync(user.Id);
                }
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", "Something failed.");

            return(View(editUser));
        }
Beispiel #18
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)
            {
                HttpRequest request   = HttpContext.Current.Request;
                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

                string strHTTPHost = String.Empty;
                try { strHTTPHost = request.ServerVariables["HTTP_HOST"].ToString().Trim(); } catch { strHTTPHost = String.Empty; }

                string hostName = strHTTPHost.ToLowerInvariant();

                string strHTTPPrefix = "http://";
                try {
                    strHTTPPrefix = request.ServerVariables["SERVER_PORT_SECURE"] == "1" ? "https://" : "http://";
                } catch { strHTTPPrefix = "http://"; }

                strHTTPHost = String.Format("{0}{1}", strHTTPPrefix, strHTTPHost).ToLowerInvariant();

                sBody = sBody.Replace("{%%UserName%%}", user.UserName);
                sBody = sBody.Replace("{%%Password%%}", newPassword);
                sBody = sBody.Replace("{%%SiteURL%%}", strHTTPHost);
                sBody = sBody.Replace("{%%Version%%}", CurrentDLLVersion);
                sBody = sBody.Replace("{%%AdminFolderPath%%}", String.Format("{0}{1}", strHTTPHost, SiteData.AdminFolderPath));

                if (SiteData.CurretSiteExists)
                {
                    sBody = sBody.Replace("{%%Time%%}", SiteData.CurrentSite.Now.ToString());
                }
                else
                {
                    sBody = sBody.Replace("{%%Time%%}", DateTime.Now.ToString());
                }

                EmailHelper.SendMail(null, user.Email, String.Format("Reset Password {0}", hostName), sBody, false);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #19
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
            {
                CheckBox lChkSelect;
                Label    lAlternateEmail;
                Label    lUserName;
                Label    lLastName;
                Label    lFirstName;
                //Label lMiddleName;
                Label lEmail;

                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();

                if (uoUserList.Items.Count > 0)
                {
                    for (int i = 0; i < uoUserList.Items.Count; i++)
                    {
                        lChkSelect = (CheckBox)uoUserList.Items[i].FindControl("uoCheckBoxSelect");
                        if (lChkSelect.Checked)
                        {
                            lUserName       = (Label)uoUserList.Items[i].FindControl("uoLblUName");
                            lAlternateEmail = (Label)uoUserList.Items[i].FindControl("uoLabelAltEmail");
                            lLastName       = (Label)uoUserList.Items[i].FindControl("uoLabelLName");
                            lFirstName      = (Label)uoUserList.Items[i].FindControl("uoLabelFName");
                            lEmail          = (Label)uoUserList.Items[i].FindControl("uoLabelEmail");


                            sUserName       = lUserName.Text;
                            sAlternateEmail = lAlternateEmail.Text;
                            sLastName       = lLastName.Text;
                            sFirstName      = lFirstName.Text;
                            // sMiddleName = "";
                            sEmail = lEmail.Text;

                            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);

                            UserAccountBLL.LDAPImmigrationUpdate(sUserName, sEmail, sAlternateEmail, false);

                            //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";
                    }
                }
                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();
                }
            }
        }
Beispiel #20
0
        public void UnlockUser(string username)
        {
            MembershipUser user = Membership.GetUser(username);

            user.UnlockUser();
        }
Beispiel #21
0
    public static void Main(string[] args)
    {
        string userName;
        string password;
        bool   unlockUser;

        if (args.Length < 1)
        {
            Console.WriteLine("Please enter a username (IE sitecore\\admin:");
            userName = Console.ReadLine();
        }
        else
        {
            userName = args[0];
        }

        if (args.Length < 2)
        {
            Console.WriteLine("Please enter a password:"******"Should the user be unlocked? [y,n] (default y)");
            string unlockUserResponse = Console.ReadLine();
            unlockUser = string.IsNullOrEmpty(unlockUserResponse) || unlockUserResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase) || unlockUserResponse.Equals("yes", StringComparison.InvariantCultureIgnoreCase);
        }
        else
        {
            unlockUser = args[2].Equals("true", StringComparison.InvariantCulture);
        }

        MembershipUser user = Membership.GetUser(userName, false);

        if (user == null)
        {
            Console.WriteLine("User not found");
            return;
        }

        if (unlockUser)
        {
            bool isUnlocked = user.UnlockUser();
            Console.WriteLine(isUnlocked ? "User has been unlocked" : "User has not been unlocked");
        }

        if (string.IsNullOrEmpty(password))
        {
            Console.WriteLine("Password cannot be empty, please try again");
            return;
        }

        string oldPassword            = user.ResetPassword();
        bool   passwordHasBeenChanged = user.ChangePassword(oldPassword, password);

        if (passwordHasBeenChanged)
        {
            Console.WriteLine("Password has been changed");
        }
    }
Beispiel #22
0
        //public IList<PageView> SavedPageViews
        //{
        //    get { return datauser.SavedPageViews; }
        //}

        #endregion

        #region Public Methods

        public bool Unlock()
        {
            return(AuthenticatedUser.UnlockUser());
        }
    public static object CambiarContrasena(string PasswordOld, string PasswordNew, string PreguntaSelect, string respuestaSecreta)
    {
        try
        {
            string PreguntaSecreta = "";

            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                string usuarioActual = Thread.CurrentPrincipal.Identity.Name;

                MembershipUser usuario = Membership.GetUser(usuarioActual);
                if (Membership.ValidateUser(usuarioActual, PasswordOld))
                {
                    PreguntaSecreta = usuario.PasswordQuestion;
                    if (PreguntaSecreta.Equals(PreguntaSelect))
                    {
                        try
                        {
                            usuario.ChangePassword(usuario.ResetPassword(respuestaSecreta), PasswordNew);
                            usuario.UnlockUser();

                            return(new
                            {
                                Ok = "OK",
                                mensaje = "Se ha actualizado correctamente la contraseña."
                            });
                        }
                        catch (MembershipPasswordException se)
                        {
                            string ses = se.ToString();
                            return(new
                            {
                                Ok = "DATOS",
                                mensaje = "Algunos de los datos ingresados no son correctos."
                            });
                        }
                    }
                    else
                    {
                        return(new
                        {
                            Ok = "DATOS",
                            mensaje = "Algunos de los datos ingresados no son correctos."
                        });
                    }
                }
                else
                {
                    return(new
                    {
                        Ok = "no",
                        mensaje = "La contraseña ingresada no es la correcta."
                    });
                }
            }
            return(new
            {
                Ok = "OK",
                PREGUNTAS = _GetPreguntas(),
            });
        }

        catch (Exception ex)
        {
            return(new
            {
                OK = "Error Consultando información inicial.",
                mensaje = ex.Message + ex.StackTrace
            });
        }
    }
Beispiel #24
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        //int comma = ListBox1.Items[x].Value.IndexOf(",");
        //int bar = ListBox1.Items[x].Value.IndexOf("|");
        //int customerid = Convert.ToInt16(ListBox1.Items[x].Value.Substring(0, comma));
        //string MemberUsername = ListBox1.Items[x].Value.Substring(comma + 1, bar - comma - 1);
        //string MemberEmail = ListBox1.Items[x].Value.Substring(bar + 1);

        //customer = DataRepository.CustomerProvider.GetByCustomerId(customerid);
        //customerprofile = DataRepository.CustomerProfileProvider.GetByCustomerId(customer.CustomerId)[0];
        //countrylookup = DataRepository.CountryLookupProvider.GetByCountryId(customer.Country);
        //customersite = DataRepository.CustomerSiteProvider.GetByCustomerSiteId(customerprofile.CustomerSite);
        //teacher = DataRepository.TeacherProvider.GetByTeacherId(customerprofile.Teacher);
        //Guid MemGuid = new Guid(customer.AspnetMembershipUserId.ToString());
        //MembershipUser user = Membership.GetUser(MemGuid);
        try
        {
            int x          = ListBox1.SelectedIndex;
            int customerid = Convert.ToInt16(ListBox1.Items[x].Value);
            customer = DataRepository.CustomerProvider.GetByCustomerId(customerid);
            Guid           MemGuid        = new Guid(customer.AspnetMembershipUserId.ToString());
            MembershipUser user           = Membership.GetUser(MemGuid);
            string         MemberUsername = user.UserName.ToString();
            string         MemberEmail    = user.Email;
            countrylookup = DataRepository.CountryLookupProvider.GetByCountryId(customer.Country);
            try
            {
                customerprofile = DataRepository.CustomerProfileProvider.GetByCustomerId(customer.CustomerId)[0];
                customersite    = DataRepository.CustomerSiteProvider.GetByCustomerSiteId(customerprofile.CustomerSite);
                teacher1        = DataRepository.TeacherProvider.GetByTeacherId(customerprofile.Teacher);
            }
            catch (Exception ex)
            {
                customerprofile = new CustomerProfile();
            }

            if (CheckBox1.Checked)
            {
                CheckBox1.Checked = false;
                CheckBox1.Enabled = false;
                Button2.Enabled   = false;

                if (customer.MembershipExpiration <= DateTime.Today)
                {
                    customer.MembershipExpiration = DateTime.Today.AddYears(1);
                }
                else
                {
                    customer.MembershipExpiration = customer.MembershipExpiration.AddYears(1);
                }
                customer.MembershipRenewal = DateTime.Today;
                customer.IsRenewal         = 1;
                customer.BillFacility      = 1;

                switch (customer.MembershipStatus)
                {
                case 0:
                    customer.MembershipCost = 50;
                    break;

                case 1:
                    customer.MembershipCost = 50;
                    break;

                case 2:
                    customer.MembershipCost = 50;
                    break;

                case 3:
                    customer.MembershipCost = 50;
                    break;

                case 4:
                    customer.MembershipCost = 100;
                    break;

                case 5:
                    customer.MembershipStatus = 2;
                    customer.MembershipCost   = 50;
                    break;

                case 6:
                    customer.MembershipStatus = 3;
                    customer.MembershipCost   = 50;
                    break;

                case 7:
                    customer.MembershipStatus = 4;
                    customer.MembershipCost   = 100;
                    break;

                case 97:
                    customer.MembershipCost = 0;
                    break;

                case 98:
                    customer.MembershipCost = 0;
                    break;

                case 99:
                    customer.MembershipCost = 0;
                    break;

                default:
                    customer.MembershipStatus = 2;
                    customer.MembershipCost   = 50;
                    break;
                }
                DataRepository.CustomerProvider.Update(customer);

                user.IsApproved = true;
                if (user.IsLockedOut)
                {
                    user.UnlockUser();
                }
                Membership.UpdateUser(user);

                Label5.Text  = customer.FirstName;
                Label7.Text  = customer.LastName;
                Label9.Text  = MemberUsername;
                Label11.Text = MemberEmail;
                if (!customer.Address1.ToLower().Equals("none"))
                {
                    Label13.Text = customer.Address1;
                }
                else
                {
                    Label13.Text = "";
                }
                Label15.Text = customer.Address2;
                if (!customer.City.ToLower().Equals("none"))
                {
                    Label17.Text = customer.City;
                }
                else
                {
                    Label17.Text = "";
                }
                if (!customer.State.ToLower().Equals("none"))
                {
                    Label19.Text = customer.State;
                }
                else
                {
                    Label19.Text = "";
                }
                if (!customer.Zip.ToLower().Equals("none"))
                {
                    Label21.Text = customer.Zip;
                }
                else
                {
                    Label21.Text = "";
                }
                if (customer.Address1.ToLower().Equals("none") && customer.Country.Equals(248))
                {
                    Label23.Text = "";
                }
                else
                {
                    Label23.Text = countrylookup.CountryName;
                }
                Label25.Text = customer.PhoneHome;
                Label27.Text = customer.PhoneWork;
                Label29.Text = customer.PhoneMobile;
                Label31.Text = customer.Fax;
                Label33.Text = customersite.SiteName;
                Label35.Text = teacher.FirstName + " " + teacher.LastName;
                Label37.Text = user.CreationDate.ToLongDateString();
                Label39.Text = customer.MembershipExpiration.ToLongDateString();
                switch (customer.MembershipStatus)
                {
                case 0:
                    Label41.Text = "Expired";
                    break;

                case 1:
                    Label41.Text = "Member";
                    break;

                case 2:
                    Label41.Text = "Full Teaching";
                    break;

                case 3:
                    Label41.Text = "Full Fitting";
                    break;

                case 4:
                    Label41.Text = "Full Teaching & Fitting";
                    break;

                case 97:
                    Label41.Text = "Comp Teaching";
                    break;

                case 98:
                    Label41.Text = "Comp Fitting";
                    break;

                case 99:
                    Label41.Text = "Comp Teaching & Fitting";
                    break;

                default:
                    Label41.Text = "Missing";
                    break;
                }

                Label3.ForeColor = System.Drawing.Color.BlueViolet;
                Label3.Text      = "The member's account has been renewed. Your facility will be charged the annual"
                                   + " renewal fee on your next monthly invoice.";

                ListBox1.Items.Clear();
            }
            else
            {
                Label3.ForeColor = System.Drawing.Color.Maroon;
                Label3.Text      = "You must click in the checkbox acknowledging that the renewal fee will be billed"
                                   + " to your facility.";
            }
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
        }
    }
Beispiel #25
0
        protected void RedemptionMemberRadGrid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "manage")
            {
                Guid UserId = (Guid)((GridDataItem)e.Item).GetDataKeyValue("UserId");

                Response.Redirect("MemberUpdate.aspx?userid=" + UserId.ToString());
            }

            //Reset password to be in link client page
            //if (e.CommandName == "resetpassword")
            //{
            //    Guid UserId = (Guid)((GridDataItem)e.Item).GetDataKeyValue("UserId");

            //    Response.Redirect("MemberResetPassword.aspx?userid=" + UserId.ToString());
            //}
            if (e.CommandName == "enable")
            {
                Guid           UserId          = (Guid)((GridDataItem)e.Item).GetDataKeyValue("UserId");
                MembershipUser aMembershipUser = Membership.GetUser(UserId);
                LinkButton     enableLB        = e.Item.FindControl("enableLB") as LinkButton;
                aMembershipUser.IsApproved = !aMembershipUser.IsApproved;
                Membership.UpdateUser(aMembershipUser);
                RedemptionMemberRadGrid.Rebind();
                //if (aMembershipUser.IsApproved)
                //{ enableLB.Text = "Disable"; }
                //else { enableLB.Text = "Enable"; }
                //TBA
                if (aMembershipUser.IsApproved)
                {
                    Logger.LogInfo(Membership.GetUser().UserName + "- disabled member username:"******"- enabled member username:"******"unlock")
            {
                Guid           UserId          = (Guid)((GridDataItem)e.Item).GetDataKeyValue("UserId");
                MembershipUser aMembershipUser = Membership.GetUser(UserId);
                aMembershipUser.UnlockUser();
                Membership.UpdateUser(aMembershipUser);
                RedemptionMemberRadGrid.Rebind();
                //if (aMembershipUser.IsApproved)
                //{ enableLB.Text = "Disable"; }
                //else { enableLB.Text = "Enable"; }
                //TBA
                Logger.LogInfo(Membership.GetUser().UserName + "- unlock member username:"******"linkclient")
            {
                Guid UserId = (Guid)((GridDataItem)e.Item).GetDataKeyValue("UserId");

                Response.Redirect("MemberClient.aspx?userid=" + UserId.ToString());
            }
        }
        public bool UnlockUser(string userName)
        {
            MembershipUser user = Membership.GetUser(userName);

            return(user.UnlockUser());
        }
        /// <summary>
        /// Modified By: Charlene Remotigue
        /// Date Modified: 03/03/2012
        /// Description: add unlock user and reset password
        /// --------------------------------------------------
        /// Modified By:    Josephine Gad
        /// Date Modified:  03/03/2012
        /// Description:    Reset users last activity date when Reset and Unlock
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void uoUserList_ItemCommand(object sender, System.Web.UI.WebControls.ListViewCommandEventArgs e)
        {
            string strLogDescription;
            string strFunction;

            if (e.CommandName == "Delete")
            {
                UserAccountBLL.DeleteUser(e.CommandArgument.ToString());


                DateTime dateNow          = CommonFunctions.GetCurrentDateTime();
                string   sUserNameDeleted = e.CommandArgument.ToString();

                string   sUser    = sUserNameDeleted;
                string[] sUserArr = sUser.Split("::".ToCharArray());

                if (sUserArr.Count() > 0)
                {
                    MUser.DeactivateUserInLDAP(GlobalCode.Field2String(sUserArr[2]));
                }

                //Insert log audit trail (Gabriel Oquialda - 17/11/2011)
                strLogDescription = "User account deleted. (flagged as inactive) " + sUserNameDeleted;
                strFunction       = "uoUserList_ItemCommand";


                BLL.AuditTrailBLL.InsertLogAuditTrail(0, "", strLogDescription, strFunction, Path.GetFileName(Request.Path),
                                                      CommonFunctions.GetDateTimeGMT(dateNow), DateTime.Now, uoHiddenFieldUser.Value);

                GetUsers("", "");
            }

            else if (e.CommandName == "Unlock")
            {
                MembershipUser mUser = Membership.GetUser(e.CommandArgument.ToString());
                mUser.UnlockUser();
                mUser.LastActivityDate = DateTime.Now.AddMinutes(-Membership.UserIsOnlineTimeWindow);
                Membership.UpdateUser(mUser);
                AlertMessage("User " + e.CommandArgument.ToString() + " successfully unlocked.");
            }
            else if (e.CommandName == "Reset")
            {
                Label userRole = new Label();

                userRole = (Label)e.Item.FindControl("Label2");

                MembershipUser mUser = Membership.GetUser(e.CommandArgument.ToString());
                if (mUser.IsLockedOut)
                {
                    mUser.UnlockUser();
                }

                string str = mUser.ResetPassword();
                mUser.LastActivityDate = DateTime.Now.AddMinutes(-Membership.UserIsOnlineTimeWindow);
                Membership.UpdateUser(mUser);


                MUser.ChangePasswordInLDAP(mUser.UserName, str);

                string      sEmail         = mUser.Email.ToString();
                HiddenField AlterNateEmail = (HiddenField)e.Item.FindControl("uoHiddenFieldAlternateEmail");


                if (userRole.Text.ToString() == TravelMartVariable.RoleImmigration)
                {
                    if (AlterNateEmail.Value != "")
                    {
                        sEmail = AlterNateEmail.Value.ToString();
                    }
                }


                SendEmail(e.CommandArgument.ToString(), sEmail, str);
                //AlertMessage("User password successfully reset. New password will be emailed to user.");
                AlertMessage("New password has been sent to " + sEmail.ToString() + ".");
            }
        }
Beispiel #28
0
        protected void OnSubmit(object sender, EventArgs e)
        {
            // get user info
            string userName = this.Request.QueryString["USERNAME"];
            SPUser spuser   = null;

            // This could be done with EnsureUsers, which won't throw an exception if the user hasn't logged on to the site.
            try
            {
                spuser = this.Web.AllUsers[Utils.EncodeUsername(userName)];
            }
            catch
            {
            }
            MembershipUser user = Utils.BaseMembershipProvider().GetUser(userName, false);

            // check user exists
            if (user != null)
            {
                try
                {
                    // TODO: If we want the Email to be used for the user account, we need to delete the user and create a new one with the new email address.
                    // This will mean we need to iterate over the groups that the user is a member of, in all site collections in all web apps, and add the new user
                    // to those groups.  In the meantime, we allow the email to be changed, but this won't update the account username.

                    // update membership provider info
                    user.Email      = txtUsername.Text;
                    user.IsApproved = isActive.Checked;

                    //Unlock Account
                    if (user.IsLockedOut && !isLocked.Checked)
                    {
                        user.UnlockUser();
                    }
                    try
                    {
                        Utils.BaseMembershipProvider().UpdateUser(user);
                    }
                    catch (System.Configuration.Provider.ProviderException ex)
                    {
                        lblMessage.Text = ex.Message;
                        return;
                    }

                    // if roles enabled add/remove user to selected role(s)
                    if (_showRoles)
                    {
                        for (int i = 0; i < rolesList.Items.Count; i++)
                        {
                            if (rolesList.Items[i].Selected)
                            {
                                if (!Utils.BaseRoleProvider().IsUserInRole(user.UserName, rolesList.Items[i].Value))
                                {
                                    Utils.BaseRoleProvider().AddUsersToRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value });
                                }
                            }
                            else
                            {
                                if (Utils.BaseRoleProvider().IsUserInRole(user.UserName, rolesList.Items[i].Value))
                                {
                                    Utils.BaseRoleProvider().RemoveUsersFromRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value });
                                }
                            }
                        }
                    }
                    // or add/remove user to selected group(s)
                    else
                    {
                        for (int i = 0; i < groupList.Items.Count; i++)
                        {
                            string groupName = groupList.Items[i].Value;

                            // determine whether user is in group
                            bool userInGroup = false;

                            if (spuser != null)
                            {
                                foreach (SPGroup group in spuser.Groups)
                                {
                                    if (group.Name == groupName)
                                    {
                                        userInGroup = true;
                                        break;
                                    }
                                }
                            }

                            // if selected add user to group
                            if (groupList.Items[i].Selected)
                            {
                                // only add if not already in group
                                if (!userInGroup)
                                {
                                    //Add the user to SharePoint if they're not already a SharePoint user
                                    if (spuser == null)
                                    {
                                        try
                                        {
                                            spuser = this.Web.EnsureUser(Utils.EncodeUsername(userName));
                                        }
                                        catch (Exception ex)
                                        {
                                            lblMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "ErrorAddingToSharePoint");
                                            Utils.LogError(ex, false);
                                            return;
                                        }
                                    }
                                    this.Web.SiteGroups[groupName].AddUser(spuser);
                                }
                            }
                            // else remove user from group
                            else
                            {
                                // only attempt remove if actually in the group
                                if (userInGroup)
                                {
                                    this.Web.SiteGroups[groupName].RemoveUser(spuser);
                                }
                            }
                        }
                    }

                    SPSite     site     = SPContext.Current.Site;
                    SPWeb      web      = site.RootWeb;
                    SPList     list     = web.SiteUserInfoList;
                    SPListItem userItem = null;
                    // update sharepoint user info
                    if (spuser != null)
                    {
                        spuser.Email = txtUsername.Text;
                        spuser.Name  = txtFullName.Text;
                        spuser.Update();

                        try
                        {
                            userItem = list.GetItemById(spuser.ID);
                        }
                        catch (Exception ex)
                        {
                            Utils.LogError(ex);
                        }

                        if (userItem != null)
                        {
                            userItem["CMIT Location"]        = txtCMITLocation.Text;
                            userItem["CMITTitle"]            = txtTitle.Text;
                            userItem["Telephone Number"]     = txtTelephoneNumber.Text;
                            userItem["Date of provisioning"] = txtDatofProvisionaing.SelectedDate;
                            userItem.Update();
                        }
                    }

                    SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context);
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex, true);
                }
            }
            else
            {
                SPUtility.TransferToErrorPage(LocalizedString.GetGlobalString("FBAPackWebPages", "UserNotFound"));
            }
        }
    protected void OnCommand(object sender, CommandEventArgs e)
    {
        //Event handler for cancel button clicked
        MembershipUser member = null;

        try {
            switch (e.CommandName)
            {
            case "Close":
                Response.Redirect("~/Admin/Memberships.aspx?username="******"OK":
                if (!Page.IsValid)
                {
                    return;
                }
                bool isNewMember = this.mUserName.Length == 0;
                if (isNewMember)
                {
                    //Validate username as unique
                    if (Membership.FindUsersByName(this.txtUserName.Text.Trim()).Count > 0)
                    {
                        throw new ApplicationException("User name " + this.txtUserName.Text.Trim() + " is already in use; please provide a unique username.");
                    }

                    //Create a new user
                    MembershipCreateStatus status;
                    member = Membership.CreateUser(this.txtUserName.Text.Trim(), this.txtPassword.Text.Trim(), this.txtEmail.Text.Trim(), null, null, this.chkApproved.Checked, out status);
                    if (member == null)
                    {
                        throw new ApplicationException("New member could not be created by the Membership system; no explanation provided (i.e. member==null).");
                    }

                    member.Comment = this.txtComments.Text;
                    Membership.UpdateUser(member);
                    switch (status)
                    {
                    case MembershipCreateStatus.Success:
                        //Update profile (add user to guest role 'cause anonymous user cannot have a profile)
                        ProfileCommon profileCommon = new ProfileCommon();
                        ProfileCommon profile       = profileCommon.GetProfile(this.txtUserName.Text);
                        profile.Company         = this.cboCustomer.SelectedItem.Text;
                        profile.UserFullName    = this.txtFullName.Text.Trim();
                        profile.Type            = this.cboType.SelectedValue;
                        profile.ClientVendorID  = this.cboCustomer.SelectedValue;
                        profile.StoreSearchType = this.cboStoreSearchType.SelectedValue;
                        profile.StoreNumber     = this.txtStoreNumber.Text;
                        profile.PasswordReset   = this.chkPWReset.Checked;
                        profile.WebServiceUser  = this.optRole.Items[3].Selected;
                        profile.Save();

                        //Update roles
                        if (this.optRole.Items[0].Selected)
                        {
                            Roles.AddUserToRole(this.txtUserName.Text.Trim(), MembershipServices.GUESTROLE);
                        }
                        if (this.optRole.Items[1].Selected)
                        {
                            Roles.AddUserToRole(this.txtUserName.Text.Trim(), MembershipServices.ADMINROLE);
                            for (int i = 0; i < this.chkRoles.Items.Count; i++)
                            {
                                if (this.chkRoles.Items[i].Selected)
                                {
                                    Roles.AddUserToRole(this.mUserName, this.chkRoles.Items[i].Value);
                                }
                            }
                        }
                        if (this.optRole.Items[2].Selected)
                        {
                            Roles.AddUserToRole(this.txtUserName.Text.Trim(), MembershipServices.TRACKINGROLE);
                        }
                        if (this.optRole.Items[3].Selected)
                        {
                            Roles.AddUserToRole(this.txtUserName.Text.Trim(), MembershipServices.TRACKINGWSROLE);
                        }
                        Master.ShowMessageBox(this.txtUserName.Text + " was created successfully.");
                        this.btnSubmit.Enabled = false;
                        break;

                    case MembershipCreateStatus.DuplicateEmail: Master.ShowMessageBox("Failed to create new member- DuplicateEmail."); break;

                    case MembershipCreateStatus.DuplicateProviderUserKey: Master.ShowMessageBox("Failed to create new member- DuplicateProviderUserKey"); break;

                    case MembershipCreateStatus.DuplicateUserName: Master.ShowMessageBox("Failed to create new member- DuplicateUserName"); break;

                    case MembershipCreateStatus.InvalidAnswer: Master.ShowMessageBox("Failed to create new member- InvalidAnswer"); break;

                    case MembershipCreateStatus.InvalidEmail: Master.ShowMessageBox("Failed to create new member- InvalidEmail"); break;

                    case MembershipCreateStatus.InvalidPassword: Master.ShowMessageBox("Failed to create new member- InvalidPassword"); break;

                    case MembershipCreateStatus.InvalidProviderUserKey: Master.ShowMessageBox("Failed to create new member- InvalidProviderUserKey"); break;

                    case MembershipCreateStatus.InvalidQuestion: Master.ShowMessageBox("Failed to create new member- InvalidQuestion"); break;

                    case MembershipCreateStatus.InvalidUserName: Master.ShowMessageBox("Failed to create new member- InvalidUserName"); break;

                    case MembershipCreateStatus.ProviderError: Master.ShowMessageBox("Failed to create new member- ProviderError"); break;

                    case MembershipCreateStatus.UserRejected: Master.ShowMessageBox("Failed to create new member- UserRejected"); break;
                    }
                }
                else
                {
                    //Update existing user if account is not locked
                    member = Membership.GetUser(this.mUserName);
                    if (member.IsLockedOut)
                    {
                        Master.ShowMessageBox(this.mUserName + " account must be unlocked before updating.");
                        return;
                    }
                    //Membership
                    if (member.GetPassword() != this.txtPassword.Text)
                    {
                        member.ChangePassword(member.GetPassword(), this.txtPassword.Text);
                    }
                    member.Comment    = this.txtComments.Text;
                    member.IsApproved = this.chkApproved.Checked;
                    member.Email      = this.txtEmail.Text;
                    Membership.UpdateUser(member);

                    //Profile
                    ProfileCommon profileCommon = new ProfileCommon();
                    ProfileCommon profile       = profileCommon.GetProfile(this.mUserName);
                    profile.ClientVendorID  = this.cboCustomer.SelectedValue;
                    profile.StoreSearchType = this.cboStoreSearchType.SelectedValue;
                    profile.Company         = this.cboCustomer.SelectedItem.Text;
                    profile.StoreNumber     = this.txtStoreNumber.Text;
                    profile.PasswordReset   = this.chkPWReset.Checked;
                    profile.Type            = this.cboType.SelectedValue;
                    profile.UserFullName    = this.txtFullName.Text;
                    profile.WebServiceUser  = this.optRole.Items[3].Selected;
                    profile.Save();

                    //Roles
                    for (int i = 0; i < this.optRole.Items.Count; i++)
                    {
                        if (this.optRole.Items[i].Selected && !Roles.IsUserInRole(this.mUserName, this.optRole.Items[i].Value))
                        {
                            Roles.AddUserToRole(this.mUserName, this.optRole.Items[i].Value);
                        }
                        if (!this.optRole.Items[i].Selected && Roles.IsUserInRole(this.mUserName, this.optRole.Items[i].Value))
                        {
                            Roles.RemoveUserFromRole(this.mUserName, this.optRole.Items[i].Value);
                        }
                    }
                    for (int i = 0; i < this.chkRoles.Items.Count; i++)
                    {
                        if (this.chkRoles.Items[i].Selected && !Roles.IsUserInRole(this.mUserName, this.chkRoles.Items[i].Value))
                        {
                            Roles.AddUserToRole(this.mUserName, this.chkRoles.Items[i].Value);
                        }
                        if (!this.chkRoles.Items[i].Selected && Roles.IsUserInRole(this.mUserName, this.chkRoles.Items[i].Value))
                        {
                            Roles.RemoveUserFromRole(this.mUserName, this.chkRoles.Items[i].Value);
                        }
                    }
                    this.btnSubmit.Enabled = false;
                    Master.ShowMessageBox(this.txtUserName.Text + " was updated successfully.");
                }
                break;

            case "Unlock":
                //Unlock user if locked out
                member = Membership.GetUser(this.txtUserName.Text, false);
                if (member.IsLockedOut)
                {
                    if (member.UnlockUser())
                    {
                        Master.ShowMessageBox(this.txtUserName.Text + " account was unlocked successfully.");
                        try {
                            if (!member.IsLockedOut)
                            {
                                this.txtPassword.Text = member.GetPassword();
                            }
                        }
                        catch (Exception ex) { Master.ReportError(ex, 3); }
                        this.chkLockedOut.Checked = member.IsLockedOut;
                    }
                    else
                    {
                        Master.ShowMessageBox(this.txtUserName.Text + " account failed to unlock.");
                    }
                }
                OnValidateForm(null, EventArgs.Empty);
                break;
            }
        }
        catch (Exception ex) { Master.ReportError(ex, 3); }
    }
Beispiel #30
0
 protected void btnUnlock_Click(object sender, EventArgs e)
 {
     SelectedUser.UnlockUser();
 }