protected void OnDelete(object sender, EventArgs e) { string userName = Request.QueryString["USERNAME"]; try { // delete user from FBA data store Utils.BaseMembershipProvider().DeleteUser(userName, true); // delete user from SharePoint try { this.Web.SiteUsers.Remove(Utils.EncodeUsername(userName)); this.Web.Update(); } catch { //left Empty because the user might not be in the SharePoint site yet. } } catch (Exception ex) { Utils.LogError(ex, true); } //Redirect to UsersDisp or Source, as long as source is not UserEdit.aspx - as that will no longer work as the user is deleted string url = "FBA/Management/UsersDisp.aspx"; SPUtility.DetermineRedirectUrl(url, SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context, null, out url); if (url.ToLower().Contains("useredit.aspx")) { url = "FBA/Management/UsersDisp.aspx"; SPUtility.DetermineRedirectUrl(url, SPRedirectFlags.RelativeToLayoutsPage, this.Context, null, out url); } SPUtility.Redirect(url, SPRedirectFlags.Default, this.Context); }
protected override void OnLoad(EventArgs e) { this.CheckRights(); // init _showRoles = (new MembershipSettings(SPContext.Current.Web)).EnableRoles; // get user info string userName = this.Request.QueryString["USERNAME"]; SPUser spuser = null; try { spuser = this.Web.AllUsers[Utils.EncodeUsername(userName)]; } catch { } MembershipUser user = Utils.BaseMembershipProvider().GetUser(userName, false); if (user != null) { if (!Page.IsPostBack) { // load user props if (spuser != null) { SPSite site = SPContext.Current.Site; SPWeb web = site.RootWeb; txtUsername.Text = spuser.Email; txtFullName.Text = spuser.Name; SPListItem userItem = web.SiteUserInfoList.GetItemById(spuser.ID); txtCMITLocation.Text = userItem["CMIT Location"] as string == null ? string.Empty : userItem["CMIT Location"] as string; txtTelephoneNumber.Text = userItem["Telephone Number"] as string == null ? string.Empty : userItem["Telephone Number"] as string; txtTitle.Text = userItem["CMITTitle"] as string == null ? string.Empty : userItem["CMITTitle"] as string; txtDatofProvisionaing.SelectedDate = (userItem["Date of provisioning"] as DateTime?).HasValue ? (userItem["Date of provisioning"] as DateTime?).Value : user.CreationDate; } else { txtUsername.Text = user.Email; txtFullName.Text = user.UserName; } txtUsername.Text = user.UserName; isActive.Checked = user.IsApproved; isLocked.Checked = user.IsLockedOut; isLocked.Enabled = user.IsLockedOut; // if roles activated display roles if (_showRoles) { RolesSection.Visible = true; GroupSection.Visible = false; try { // load roles string[] roles = Utils.BaseRoleProvider().GetAllRoles(); rolesList.DataSource = roles; rolesList.DataBind(); // select roles associated with the user for (int i = 0; i < roles.Length; i++) { ListItem item = rolesList.Items.FindByText(roles[i].ToString()); if (item != null) { item.Selected = Utils.BaseRoleProvider().IsUserInRole(user.UserName, roles[i].ToString()); } } } catch (Exception ex) { Utils.LogError(ex, true); } } // otherwise display groups else { GroupSection.Visible = true; RolesSection.Visible = false; try { // load groups groupList.DataSource = this.Web.SiteGroups; groupList.DataBind(); if (spuser != null) { // select groups associated with the user foreach (SPGroup group in spuser.Groups) { ListItem item = groupList.Items.FindByText(group.Name); if (item != null) { item.Selected = true; } } } } catch (Exception ex) { Utils.LogError(ex, true); } } } } else { SPUtility.TransferToErrorPage(LocalizedString.GetGlobalString("FBAPackWebPages", "UserNotFound")); } }
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 OnSubmit(object sender, EventArgs e) { // ModifiedBySolvion // bhi - 09.01.2012 // Reset message labels lblMessage.Text = lblAnswerMessage.Text = lblEmailMessage.Text = lblPasswordMessage.Text = lblQuestionMessage.Text = ""; // EndModifiedBySolvion bool _showRoles = (new MembershipSettings(SPContext.Current.Web)).EnableRoles; // check to see if username already in use MembershipUser user = Utils.BaseMembershipProvider().GetUser(txtUsername.Text, false); if (user == null) { try { // get site reference string provider = Utils.GetMembershipProvider(this.Site); // create FBA database user MembershipCreateStatus createStatus; if (Utils.BaseMembershipProvider().RequiresQuestionAndAnswer) { user = Utils.BaseMembershipProvider().CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, isActive.Checked, null, out createStatus); } else { user = Utils.BaseMembershipProvider().CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, null, null, isActive.Checked, null, out createStatus); } if (createStatus != MembershipCreateStatus.Success) { SetErrorMessage(createStatus); return; } if (user == null) { lblMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "UnknownError"); return; } bool groupAdded = false; if (_showRoles) { for (int i = 0; i < rolesList.Items.Count; i++) { if (rolesList.Items[i].Selected) { Utils.BaseRoleProvider().AddUsersToRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value }); } } // add user to SharePoint whether a role was selected or not AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text); } else { // add user to each group that was selected for (int i = 0; i < groupList.Items.Count; i++) { if (groupList.Items[i].Selected) { // add user to group SPGroup group = this.Web.SiteGroups[groupList.Items[i].Value]; group.AddUser( Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text, ""); // update group.Update(); groupAdded = true; } } // if no group selected, add to site with no permissions if (!groupAdded) { AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text); } } // Email User if ((emailUser.Checked == true)) { //InputFormTextBox txtEmailSubject = (InputFormTextBox)emailUser.FindControl("txtEmailSubject"); //InputFormTextBox txtEmailBody = (InputFormTextBox)emailUser.FindControl("txtEmailBody"); if ((!string.IsNullOrEmpty(txtEmailSubject.Text)) && (!string.IsNullOrEmpty(txtEmailBody.Text))) { Email.SendEmail(this.Web, user.Email, txtEmailSubject.Text, txtEmailBody.Text); } } SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context); } catch (Exception ex) { Utils.LogError(ex, true); } } else { lblMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "DuplicateUserName");; } }
protected void OnSubmit(object sender, EventArgs e) { // ModifiedBySolvion // bhi - 09.01.2012 // Reset message labels //lblMessage.Text = lblAnswerMessage.Text = lblEmailMessage.Text = lblPasswordMessage.Text = lblQuestionMessage.Text = ""; // EndModifiedBySolvion bool _showRoles = (new MembershipSettings(SPContext.Current.Web)).EnableRoles; // check to see if username already in use MembershipUser user = Utils.BaseMembershipProvider().GetUser(txtEmail.Text, false); if (user == null) { try { // get site reference string provider = Utils.GetMembershipProvider(this.Site); // create FBA database user MembershipCreateStatus createStatus; if (Utils.BaseMembershipProvider().RequiresQuestionAndAnswer) { user = Utils.BaseMembershipProvider().CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, isActive.Checked, null, out createStatus); } else { user = Utils.BaseMembershipProvider().CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text, null, null, isActive.Checked, null, out createStatus); } if (createStatus != MembershipCreateStatus.Success) { SetErrorMessage(createStatus); return; } if (user == null) { lblEmailMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "UnknownError"); return; } bool groupAdded = false; if (_showRoles) { for (int i = 0; i < rolesList.Items.Count; i++) { if (rolesList.Items[i].Selected) { Utils.BaseRoleProvider().AddUsersToRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value }); } } // add user to SharePoint whether a role was selected or not AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text); } else { // add user to each group that was selected for (int i = 0; i < groupList.Items.Count; i++) { if (groupList.Items[i].Selected) { // add user to group SPGroup group = this.Web.SiteGroups[groupList.Items[i].Value]; group.AddUser( Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text, ""); // update group.Update(); groupAdded = true; } } // if no group selected, add to site with no permissions if (!groupAdded) { AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text); } } SPSite site = SPContext.Current.Site; SPWeb web = site.RootWeb; SPList list = web.SiteUserInfoList; SPUser SPuser = web.AllUsers.GetByEmail(txtEmail.Text); SPListItem userItem = null; 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(); } // Email User if ((emailUser.Checked == true)) { if ((!string.IsNullOrEmpty(txtEmailSubject.Text)) && (!string.IsNullOrEmpty(txtEmailBody.Text))) { var emailBody = txtEmailBody.Text + Environment.NewLine + "Use your email as user name :" + txtEmail.Text + " and password as :" + txtPassword.Text + Environment.NewLine + "We recommand you to change your password when you login for first time."; Email.SendEmail(this.Web, user.Email, txtEmailSubject.Text, emailBody); } } SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context); } catch (Exception ex) { Utils.LogError(ex, true); } } else { lblEmailMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "DuplicateUserName");; } }
public static void ApproveMembership(MembershipRequest request, SPWeb web) { Hashtable xsltValues; MembershipCreateStatus createStatus; SPListItem debuggingInfoItem = null; MembershipSettings settings = new MembershipSettings(web); MembershipProvider membership = Utils.BaseMembershipProvider(web.Site); /* This is just for debugging */ try { SPList memberlist = web.GetList(Utils.GetAbsoluteURL(web, MembershipList.MEMBERSHIPREVIEWLIST)); if (memberlist.Fields.ContainsField("LastError")) { foreach (SPListItem addItem in memberlist.Items) { if (addItem["User Name"].ToString() == request.UserName) { debuggingInfoItem = addItem; /* bms added break to only loop through items needed */ break; } } } } catch { } /* Above is for debugging */ try { if (string.IsNullOrEmpty(request.UserName)) { throw new Exception("User name must not be null or empty."); } /* rdcpro: Allows providers that don't have password and question */ if (membership.RequiresQuestionAndAnswer && string.IsNullOrEmpty(request.PasswordQuestion)) { throw new Exception("You must specify a password question."); } if (membership.RequiresQuestionAndAnswer && string.IsNullOrEmpty(request.PasswordAnswer)) { throw new Exception("You must specify a password answer."); } if (string.IsNullOrEmpty(request.UserEmail)) { throw new Exception("Email address must not be null or empty."); } //create account /* bms Create password at a minimum of 7 characters or Min from provider if greater */ int passwordLength = 14; if (passwordLength < membership.MinRequiredPasswordLength) { passwordLength = membership.MinRequiredPasswordLength; } if (passwordLength < membership.MinRequiredNonAlphanumericCharacters) { passwordLength = membership.MinRequiredNonAlphanumericCharacters; } if (String.IsNullOrEmpty(request.Password)) { request.Password = System.Web.Security.Membership.GeneratePassword(passwordLength, membership.MinRequiredNonAlphanumericCharacters); } MembershipUser existingUser = Utils.BaseMembershipProvider(web.Site).GetUser(request.UserName, false); if (existingUser != null) { membership.DeleteUser(request.UserName, true); } MembershipUser newUser; //This section is to transaction Creating the user and sending the email try { // rdcpro: Changes to support providers that don't require question and answer. if (membership.RequiresQuestionAndAnswer) { //membership.CreateUser(request.UserName, tempPassword, request.UserEmail, request.PasswordQuestion, request.PasswordAnswer, true, out createStatus); newUser = membership.CreateUser(request.UserName, request.Password, request.UserEmail, request.PasswordQuestion, request.PasswordAnswer, true, null, out createStatus); } else { // With this method the MembershipCreateUserException will take care of things if the user can't be created, so no worry that createStatus is set to success //membership.CreateUser(.CreateUser(request.UserName, tempPassword, request.UserEmail); newUser = membership.CreateUser(request.UserName, request.Password, request.UserEmail, null, null, true, null, out createStatus); createStatus = MembershipCreateStatus.Success; } if (debuggingInfoItem != null) { if (debuggingInfoItem.Fields.ContainsField("LastError")) { debuggingInfoItem["LastError"] = "Created User"; debuggingInfoItem.SystemUpdate(); } } if (createStatus == MembershipCreateStatus.Success) { newUser.IsApproved = true; membership.UpdateUser(newUser); //Add the user to the default group if (!String.IsNullOrEmpty(request.DefaultGroup)) { web.SiteGroups[request.DefaultGroup].AddUser(Utils.EncodeUsername(request.UserName.ToLower(), web.Site), request.UserEmail, request.FirstName + " " + request.LastName, "Self Registration"); //Login the user if selected if (request.LoginCreatedUser) { Microsoft.SharePoint.IdentityModel.SPClaimsUtility.AuthenticateFormsUser(new Uri(web.Url), request.UserName, request.Password); } } if (debuggingInfoItem != null) { if (debuggingInfoItem.Fields.ContainsField("LastError")) { if (!String.IsNullOrEmpty(request.DefaultGroup)) { debuggingInfoItem["LastError"] = "Add User Has No Groups"; } else { debuggingInfoItem["LastError"] = "Add User To Groups"; } debuggingInfoItem.SystemUpdate(); } } //email user to confirm that request is approved xsltValues = new Hashtable(1); xsltValues.Add("fba:MembershipRequest", request); bool bSentMail = Email.SendEmail(web, request.UserEmail, settings.MembershipApprovedEmail, xsltValues); if (!bSentMail) { Utils.LogError("SendEmail failed"); throw new Exception("Error sending mail notification"); } if (debuggingInfoItem != null) { if (debuggingInfoItem.Fields.ContainsField("LastError")) { debuggingInfoItem["LastError"] = "Sent Email To New User: "******"Error creating user: "******"LastError")) { foreach (SPListItem addItem in memberlist.Items) { if (addItem["User Name"].ToString() == request.UserName) { addItem["LastError"] = AdduserExp.Message.ToString(); addItem.SystemUpdate(); break; } } } } catch { } // TODO: if CreateUser fails, the user in the MemberShipRequest list needs to be marked somehow so that the approver knows what the problem is. // Maybe the list should always have the "LastError" field, or else the status can have an extra error value in addition to pending | approved | rejected // Then in the calling code, we must not delete the item from the list! // Also, if we're handling an exception, we should set the status back to "Pending". // For now, we rethrow the exception which will cause the caller to fail, and prevent the delete. throw new Exception(AdduserExp.Message); } } catch (Exception ex) { //Add error information to list try { SPList memberlist = web.GetList(Utils.GetAbsoluteURL(web, MembershipList.MEMBERSHIPREVIEWLIST)); if (memberlist.Fields.ContainsField("LastError")) { foreach (SPListItem addItem in memberlist.Items) { if (addItem["User Name"].ToString() == request.UserName) { // This overwrites anything already in the LastError field. addItem["LastError"] = ex.Message.ToString(); addItem.SystemUpdate(); } } } } catch { } Utils.LogError(ex); throw new Exception(ex.Message); } }