using System; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using CMS.CMSHelper; using CMS.GlobalHelper; using CMS.SettingsProvider; using CMS.SiteProvider; using CMS.ExtendedControls; using CMS.UIControls; public partial class CMSModules_Membership_Pages_Users_User_Edit_General : CMSUsersPage { #region "Protected variables" protected int userId = 0; protected string password; protected string myCulture = string.Empty; protected string myUICulture = string.Empty; private UserInfo ui = null; private CurrentUserInfo currentUser = null; #endregion #region "Page events" protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; rfvFullName.ErrorMessage = GetString("Administration-User_New.RequiresFullName"); ucUserName.UseDefaultValidationGroup = false; // Register picture delete script ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PictDelConfirm", ScriptHelper.GetScript("function DeleteConfirmation(){ return confirm(" + ScriptHelper.GetString(GetString("MyProfile.PictDeleteConfirm")) + ");}")); CheckBoxLabelIsGlobalAdministrator.Enabled = currentUser.IsGlobalAdministrator; userId = QueryHelper.GetInteger("userid", 0); cultureSelector.DisplayAllCultures = true; if (userId > 0) { // Get user info object ui = UserInfoProvider.GetUserInfo(userId); CheckUserAvaibleOnSite(ui); EditedObject = ui; // Check that only global administrator can edit global administrator's accounts if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; ShowError(GetString("Administration-User_List.ErrorGlobalAdmin")); } if (!RequestHelper.IsPostBack()) { LoadData(); } } // Register help variable for user is external confirmation ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "IsExternal", ScriptHelper.GetScript("var isExternal = " + chkIsExternal.Checked.ToString().ToLowerCSafe() + ";")); // Javascript code for "Is external user" confirmation string javascript = ScriptHelper.GetScript( @"function CheckExternal() { var checkbox = document.getElementById('" + chkIsExternal.ClientID + @"') if(checkbox.checked && !isExternal) { if(!confirm('" + GetString("user.confirmexternal") + @"')) { checkbox.checked = false ; } }}"); // Register script to the page ScriptHelper.RegisterClientScriptBlock(this, typeof(string), ClientID + "CheckExternal", javascript); // Assign to ok button if (!chkIsExternal.Checked) { btnOk.OnClientClick = "CheckExternal()"; } // Display impersonation link if current user is global administrator and edited user is not global admin if (currentUser.IsGlobalAdministrator && (ui != null) && (ui.UserID != currentUser.UserID) && !ui.IsPublic()) { string message = GetImpersonalMessage(ui); // Header actions string[,] actions = new string[1, 11]; actions[0, 0] = HeaderActions.TYPE_LINKBUTTON; actions[0, 1] = GetString("Membership.Impersonate"); actions[0, 2] = "if (!confirm('" + message + "')) { return false; }"; actions[0, 4] = GetString("Membership.Impersonate"); actions[0, 5] = GetImageUrl("Objects/CMS_User/Impersonate.png"); actions[0, 6] = "impersonate"; actions[0, 8] = "true"; CurrentMaster.HeaderActions.Actions = actions; CurrentMaster.HeaderActions.ActionPerformed += new CommandEventHandler(HeaderActions_ActionPerformed); } // Set hide action if user extend validity of his own account if (ui.UserID == currentUser.UserID) { btnExtendValidity.OnClientClick = "window.top.HideWarning()"; } } protected void Page_PreRender(object sender, EventArgs e) { if (ui != null) { // Only admin who have currently access to site manager can disable access to site manager to others if (!ui.IsGlobalAdministrator || (currentUser.UserID == ui.UserID) || currentUser.UserSiteManagerDisabled) { // Only admin who have access to site manager can create another global admin if (currentUser.UserSiteManagerDisabled) { plcGlobalAdmin.Visible = false; } plcSiteManagerDisabled.Visible = false; } else { plcSiteManagerDisabled.Visible = true; } // Reset flag CheckBoxEnabled.Enabled = true; // Show warning message if (!ui.Enabled) { string description = null; if (ui.UserSettings.UserWaitingForApproval) { description = GetString("Administration-User_List.AccountLocked.WaitingForApproval"); } else { switch (UserAccountLockCode.ToEnum(ui.UserAccountLockReason)) { case UserAccountLockEnum.MaximumInvalidLogonAttemptsReached: description = GetString("Administration-User_List.AccountLocked.MaximumInvalidPasswordAttempts"); CheckBoxEnabled.Enabled = false; break; case UserAccountLockEnum.PasswordExpired: description = GetString("Administration-User_List.AccountLocked.PasswordExpired"); CheckBoxEnabled.Enabled = false; break; case UserAccountLockEnum.DisabledManually: description = GetString("Administration-User_List.AccountLocked.Disabledmanually"); break; } } ShowWarning(GetString("Administration-User_List.AccountLocked"), description, description); } // Check "modify" permission if (!currentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { btnExtendValidity.Enabled = btnResetLogonAttempts.Enabled = false; } // Display impersonation link if current user is global administrator if (CurrentMaster.HeaderActions.Actions != null) { var impersonateAction = CurrentMaster.HeaderActions.ActionsList.Find(a => a.CommandName == "impersonate"); if (impersonateAction != null) { if (currentUser.IsGlobalAdministrator && (ui != null) && (ui.UserID != currentUser.UserID) && !ui.IsPublic() && (!ui.IsGlobalAdministrator)) { string message = GetImpersonalMessage(ui); impersonateAction.OnClientClick = "if (!confirm('" + message + "')) { return false; }"; } else { impersonateAction.Visible = false; } } } } } /// /// Users actions. /// private void HeaderActions_ActionPerformed(object sender, CommandEventArgs e) { switch (e.CommandName) { case "impersonate": // Use user impersonate UserInfo ui = UserInfoProvider.GetUserInfo(userId); currentUser.UserImpersonate(ui); break; case ComponentEvents.SAVE: btnOk_Click(sender, EventArgs.Empty); break; } } /// /// Saves data of edited user from TextBoxes into DB. /// protected void btnOk_Click(object sender, EventArgs e) { // Check "modify" permission if (!currentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } string result = ValidateGlobalAndDeskAdmin(userId); // Find whether user name is valid if (result == String.Empty) { if (!ucUserName.IsValid()) { result = ucUserName.ValidationError; } } String userName = ValidationHelper.GetString(ucUserName.Value, String.Empty); if (result == String.Empty) { // Finds whether required fields are not empty result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result; } if ((result == String.Empty) && (ui != null)) { // If site prefixed allowed - ad site prefix if ((SiteID != 0) && UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName)) { if (!UserInfoProvider.IsSitePrefixedUser(userName)) { userName = UserInfoProvider.EnsureSitePrefixUserName(userName, CMSContext.CurrentSite); } } // Validation for site prefixed users if (!UserInfoProvider.IsUserNamePrefixUnique(userName, ui.UserID)) { result = GetString("Administration-User_New.siteprefixeduserexists"); } // Ensure same password password = ui.GetValue("UserPassword").ToString(); // Test for unique username UserInfo uiTest = UserInfoProvider.GetUserInfo(userName); if ((uiTest == null) || (uiTest.UserID == userId)) { if (ui == null) { ui = new UserInfo(); } bool globAdmin = ui.IsGlobalAdministrator; bool editor = ui.IsEditor; // Email format validation string email = txtEmail.Text.Trim(); if ((email != string.Empty) && (!ValidationHelper.IsEmail(email))) { ShowError(GetString("Administration-User_New.WrongEmailFormat")); return; } bool oldGlobal = ui.IsGlobalAdministrator; bool oldEditor = ui.IsEditor; if (ui.UserName != userName) { // Refresh the breadcrumb ScriptHelper.RefreshTabHeader(Page, null); } // Define domain variable string domains = null; // Get all user sites DataTable ds = UserInfoProvider.GetUserSites(userId, null, null, 0, "SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Rows) { domains += ValidationHelper.GetString(dr["SiteDomainName"], string.Empty) + ";"; } // Remove ";" at the end if (domains != null) { domains = domains.Remove(domains.Length - 1); } } else { DataSet siteDs = SiteInfoProvider.GetSites(null, null, "SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(siteDs)) { // Create list of available site domains domains = TextHelper.Join(";", SystemDataHelper.GetStringValues(siteDs.Tables[0], "SiteDomainName")); } } // Check limitations for Global administrator if (currentUser.IsGlobalAdministrator && CheckBoxLabelIsGlobalAdministrator.Checked && !oldGlobal) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, globAdmin)) { ShowError(GetString("License.MaxItemsReachedGlobal")); return; } } // Check limitations for editors if (CheckBoxIsEditor.Checked && !oldEditor) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Editors, VersionActionEnum.Insert, editor)) { ShowError(GetString("License.MaxItemsReachedEditor")); return; } } // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(email, ui)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return; } // Set properties ui.Email = email; ui.FirstName = txtFirstName.Text.Trim(); ui.FullName = txtFullName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.MiddleName = txtMiddleName.Text.Trim(); ui.UserName = userName; ui.Enabled = CheckBoxEnabled.Checked; ui.IsEditor = CheckBoxIsEditor.Checked; ui.UserIsHidden = chkIsHidden.Checked; // Only admins who have access to site manager can set this if (!currentUser.UserSiteManagerDisabled) { ui.UserSiteManagerDisabled = chkSiteManagerDisabled.Checked; // Only admin who have access to site manager can create another global admin ui.IsGlobalAdministrator = currentUser.IsGlobalAdministrator && CheckBoxLabelIsGlobalAdministrator.Checked; } ui.IsExternal = chkIsExternal.Checked; ui.UserIsDomain = chkIsDomain.Checked; ui.SetValue("UserPassword", password); ui.UserID = userId; ui.UserStartingAliasPath = txtUserStartingPath.Text.Trim(); LoadUserLogon(ui); // Set values of cultures. string culture = ValidationHelper.GetString(cultureSelector.Value, ""); ui.PreferredCultureCode = culture; if (lstUICulture.SelectedValue == "0") { ui.PreferredUICultureCode = ""; } else { // Set preferred UI culture UICultureInfo ciUI = UICultureInfoProvider.GetUICultureInfo(Convert.ToInt32(lstUICulture.SelectedValue)); ui.PreferredUICultureCode = ciUI.UICultureCode; } using (CMSActionContext context = new CMSActionContext()) { // Check whether the username of the currently logged user has been changed if (CurrentUserChangedUserName()) { // Ensure that an update search task will be created but NOT executed when updating the user context.EnableSmartSearchIndexer = false; } // Update the user UserInfoProvider.SetUserInfo(ui); // Check whether the username of the currently logged user has been changed if (CurrentUserChangedUserName()) { // Ensure that current user is not logged out if he changes his user name if (RequestHelper.IsFormsAuthentication()) { FormsAuthentication.SetAuthCookie(ui.UserName, false); // Update current user CMSContext.CurrentUser = new CurrentUserInfo(ui, true); } } } ShowChangesSaved(); } else { // If user exists ShowError(GetString("Administration-User_New.UserExists")); } } else { ShowError(result); } if ((ui.UserInvalidLogOnAttempts == 0) && (ui.UserAccountLockReason != UserAccountLockCode.FromEnum(UserAccountLockEnum.MaximumInvalidLogonAttemptsReached))) { btnResetLogonAttempts.Enabled = false; } LoadPasswordExpiration(ui); } #endregion #region "Protected methods" /// /// Returns the impersonalization message for current user. /// /// User info protected string GetImpersonalMessage(UserInfo ui) { string message = String.Empty; // Editor message if (ui.IsEditor) { message = GetString("Membership.ImperConfirmEditor"); } // Default user message else { message = GetString("Membership.ImperConfirmDefault"); } return message; } /// /// Loads data of edited user from DB into TextBoxes. /// protected void LoadData() { // Fill lstUICulture (loop over and localize them first) DataSet uiCultures = UICultureInfoProvider.GetUICultures(null, "UICultureName ASC"); LocalizeCultureNames(uiCultures); lstUICulture.DataSource = uiCultures.Tables[0].DefaultView; lstUICulture.DataTextField = "UICultureName"; lstUICulture.DataValueField = "UICultureID"; lstUICulture.DataBind(); lstUICulture.Items.Insert(0, GetString("Administration-User_Edit.Default")); lstUICulture.Items[0].Value = "0"; if (ui != null) { // Get user info properties txtEmail.Text = ui.Email; txtFirstName.Text = ui.FirstName; txtFullName.Text = ui.FullName; txtLastName.Text = ui.LastName; txtMiddleName.Text = ui.MiddleName; ucUserName.Value = ui.UserName; CheckBoxEnabled.Checked = ui.Enabled; CheckBoxIsEditor.Checked = ui.IsEditor; CheckBoxLabelIsGlobalAdministrator.Checked = ui.IsGlobalAdministrator; chkIsExternal.Checked = ui.IsExternal; chkIsDomain.Checked = ui.UserIsDomain; chkIsHidden.Checked = ui.UserIsHidden; chkSiteManagerDisabled.Checked = ui.UserSiteManagerDisabled; password = ui.GetValue("UserPassword").ToString(); // Disable username textbox for public user if (ui.IsPublic()) { ucUserName.Enabled = false; } myCulture = ui.PreferredCultureCode; myUICulture = ui.PreferredUICultureCode; lblInvalidLogonAttemptsNumber.Text = string.Format(GetString("general.attempts"), ui.UserInvalidLogOnAttempts); if (ui.UserInvalidLogOnAttempts > 0) { lblInvalidLogonAttemptsNumber.Style.Add(HtmlTextWriterStyle.Color, "Red"); } else { btnResetLogonAttempts.Enabled = (ui.UserAccountLockReason == UserAccountLockCode.FromEnum(UserAccountLockEnum.MaximumInvalidLogonAttemptsReached)); } LoadPasswordExpiration(ui); txtUserStartingPath.Text = ui.UserStartingAliasPath; } // Set content culture cultureSelector.Value = myCulture; if (!string.IsNullOrEmpty(myUICulture)) { // Set UI culture try { UICultureInfo ciUI = UICultureInfoProvider.GetUICultureInfo(myUICulture); lstUICulture.SelectedIndex = lstUICulture.Items.IndexOf(lstUICulture.Items.FindByValue(ciUI.UICultureID.ToString())); } catch { lstUICulture.SelectedIndex = lstUICulture.Items.IndexOf(lstUICulture.Items.FindByValue("0")); } } else { lstUICulture.SelectedIndex = lstUICulture.Items.IndexOf(lstUICulture.Items.FindByValue("0")); } if (ui != null) { // If new user lblCreatedInfo.Text = ui.UserCreated.ToString(); lblLastLogonTime.Text = ui.LastLogon.ToString(); LoadUserLogon(ui); if (ui.UserCreated == DataHelper.DATETIME_NOT_SELECTED) { lblCreatedInfo.Text = GetString("general.na"); } if (ui.LastLogon == DataHelper.DATETIME_NOT_SELECTED) { lblLastLogonTime.Text = GetString("general.na"); } } } /// /// Displays user's last logon information. /// /// User info protected void LoadUserLogon(UserInfo ui) { if ((ui.UserLastLogonInfo != null) && (ui.UserLastLogonInfo.ColumnNames != null)) { plcUserLastLogonInfo.Controls.Add(new LiteralControl("
")); foreach (string column in ui.UserLastLogonInfo.ColumnNames) { // Create new control to display last logon information Label lbl = new Label(); lbl.Text = HTMLHelper.HTMLEncode(TextHelper.LimitLength((string)ui.UserLastLogonInfo[column], 80, "...")) + "
"; lbl.ToolTip = HTMLHelper.HTMLEncode(column + " - " + (string)ui.UserLastLogonInfo[column]); plcUserLastLogonInfo.Controls.Add(lbl); } plcUserLastLogonInfo.Controls.Add(new LiteralControl("
")); } else { plcUserLastLogonInfo.Controls.Add(new LiteralControl(GetString("general.na") + "
")); } } /// /// Check whether current user is allowed to modify another user. Return "" or error message. /// /// Modified user protected string ValidateGlobalAndDeskAdmin(int userId) { string result = String.Empty; if (currentUser.IsGlobalAdministrator) { // User is global admin return result; } UserInfo userInfo = UserInfoProvider.GetUserInfo(userId); if (userInfo == null) { result = GetString("Administration-User.WrongUserId"); } else if (userInfo.IsGlobalAdministrator) { // Current user has lower permissions than given user result = GetString("Administration-User.NotAllowedToModify"); } return result; } /// /// Localizes culture names and sorts them in ascending order. /// /// DataSet containing the UI cultures private void LocalizeCultureNames(DataSet uiCultures) { // Localize all available UI cultures if (!DataHelper.DataSourceIsEmpty(uiCultures)) { for (int i = 0; i < uiCultures.Tables[0].Rows.Count; i++) { uiCultures.Tables[0].Rows[i]["UICultureName"] = ResHelper.LocalizeString(uiCultures.Tables[0].Rows[i]["UICultureName"].ToString()); } } uiCultures.Tables[0].DefaultView.Sort = "UICultureName ASC"; } /// /// Load user password expiration /// /// User info protected void LoadPasswordExpiration(UserInfo ui) { int expDays = 0; lblExpireIn.Style.Clear(); lblPassExpiration.Text = GetString("Administration-User_Edit_General.PasswordExpireIn"); if (!AuthenticationHelper.IsPasswordExpirationEnabled(CMSContext.CurrentSiteName, out expDays)) { lblExpireIn.Text = GetString("security.never"); btnExtendValidity.Enabled = (ui.UserAccountLockReason == UserAccountLockCode.FromEnum(UserAccountLockEnum.PasswordExpired)); } else { int dayDiff = (DateTime.Now - ui.UserPasswordLastChanged).Days - expDays; if (dayDiff >= 0) { lblPassExpiration.Text = GetString("Administration-User_Edit_General.PasswordExpired"); lblExpireIn.Style.Add(HtmlTextWriterStyle.Color, "Red"); } lblExpireIn.Text = string.Format(GetString("general.validity.days"), Math.Abs(dayDiff)); } } /// /// Reset user account lock status /// protected void btnResetLogonAttempts_Click(object sender, EventArgs e) { // Check "modify" permission if (!currentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } bool unlocked = false; if (ui.UserAccountLockReason == UserAccountLockCode.FromEnum(UserAccountLockEnum.MaximumInvalidLogonAttemptsReached)) { AuthenticationHelper.UnlockUserAccount(ui); unlocked = true; } else { ui.UserInvalidLogOnAttempts = 0; UserInfoProvider.SetUserInfo(ui); } LoadData(); lblInvalidLogonAttemptsNumber.Style.Clear(); if (unlocked) { ShowConfirmation(GetString("Administration-User.InvalidLogonAttemptsResetUnlock")); } else { ShowConfirmation(GetString("Administration-User.InvalidLogonAttemptsReset")); } } /// /// Reset user account lock status /// protected void btnExtendValidity_Click(object sender, EventArgs e) { // Check "modify" permission if (!currentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } bool unlocked = false; ui.UserPasswordLastChanged = DateTime.Now; if (ui.UserAccountLockReason == UserAccountLockCode.FromEnum(UserAccountLockEnum.PasswordExpired)) { AuthenticationHelper.UnlockUserAccount(ui); unlocked = true; } else { UserInfoProvider.SetUserInfo(ui); } LoadData(); if (unlocked) { ShowConfirmation(GetString("Administration-User.ExtendPasswordUnlock")); } else { ShowConfirmation(GetString("Administration-User.ExtendPassword")); } } #endregion #region "Private methods" /// /// Checks if currently logged user changes his user name. /// private bool CurrentUserChangedUserName() { return (currentUser != null) && (currentUser.UserID == ui.UserID) && (currentUser.UserName != ui.UserName); } #endregion }