コード例 #1
0
        public static bool SendResetPasswordEmail(MembershipRequest request, SPWeb web)
        {
            Hashtable          xsltValues;
            MembershipSettings settings = new MembershipSettings(web);

            try
            {
                xsltValues = new Hashtable();
                xsltValues.Add("fba:MembershipRequest", request);
                return(Email.SendEmail(web, request.UserEmail, settings.ResetPasswordEmail, xsltValues));
            }
            catch (Exception ex)
            {
                Utils.LogError(ex);
                return(false);
            }
        }
コード例 #2
0
ファイル: RoleNew.aspx.cs プロジェクト: cbigott133/FBA-2016
 protected void OnSubmit(object sender, EventArgs e)
 {
     // add the role to the membership provider
     if (!Utils.BaseRoleProvider().RoleExists(txtRole.Text))
     {
         try
         {
             Utils.BaseRoleProvider().CreateRole(txtRole.Text);
             // redirect to roles list
             SPUtility.Redirect("FBA/Management/RolesDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context);
         }
         catch (Exception ex)
         {
             Utils.LogError(ex, true);
         }
     }
     else
     {
         lblMessage.Visible = true;
     }
 }
コード例 #3
0
        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);
        }
コード例 #4
0
 /// <summary>
 /// return a strongly typed view for the current data source control
 /// </summary>
 /// <param name="viewName"></param>
 /// <returns></returns>
 protected override DataSourceView GetView(string viewName)
 {
     // only retrieve a view if a membership provider can be found
     if (_view == null)
     {
         try
         {
             if (ViewName == "FBAUsersView")
             {
                 _view = new FBAUsersView(this, viewName);
             }
             else if (ViewName == "FBARolesView")
             {
                 _view = new FBARolesView(this, viewName);
             }
         }
         catch (Exception ex)
         {
             Utils.LogError(ex, true);
         }
     }
     return(_view);
 }
コード例 #5
0
        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"));
            }
        }
コード例 #6
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"));
            }
        }
コード例 #7
0
        protected override void OnCreatedUser(EventArgs e)
        {
            // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
            // Also, you can't use the original Site even with elevated privileges, otherwise it reverts back to anonymous.
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site2 = new SPSite(SPContext.Current.Site.ID, SPContext.Current.Site.Zone))
                {
                    using (SPWeb web2 = site2.OpenWeb(SPContext.Current.Web.ID))
                    {
                        // from this point allowunsafeupdates is required because the call is initiated from a browser with
                        // anonymouse rights only
                        web2.AllowUnsafeUpdates = true;

                        MembershipRequest request = new MembershipRequest();
                        request.UserEmail         = this.Email;
                        request.UserName          = this.UserName;
                        if (System.Web.Security.Membership.RequiresQuestionAndAnswer)
                        {
                            request.PasswordQuestion = this.Question;
                            request.PasswordAnswer   = this.Answer;
                        }
                        request.FirstName    = this.FirstName;
                        request.LastName     = this.LastName;
                        request.DefaultGroup = this._DefaultGroup;

                        request.SiteName = web2.Title;
                        request.SiteURL  = web2.Url;

                        MembershipSettings settings = new MembershipSettings(web2);

                        if (settings.ReviewMembershipRequests)
                        {
                            request.LoginCreatedUser = false;

                            if (!MembershipRequest.CopyToReviewList(request))
                            {
                                lblError.Text = this.UnknownErrorMessage;
                                return;
                            }
                        }
                        else
                        {
                            #region Process new user request if we're NOT using the Request List

                            if (!AutoGeneratePassword)
                            {
                                request.Password = this.Password;
                            }

                            request.ChangePasswordURL = Utils.GetAbsoluteURL(web2, settings.ChangePasswordPage);
                            request.LoginCreatedUser  = SPLoginCreatedUser;

                            try
                            {
                                MembershipRequest.ApproveMembership(request, web2);
                            }
                            catch (Exception ex)
                            {
                                Utils.LogError(ex);
                                this.lblCompleteSuccess.Text = this.UnknownErrorMessage;
                                return;
                            }


                            #endregion
                        }
                        this.MoveTo(this.CompleteStep);
                    }
                }
            });
        }
コード例 #8
0
ファイル: UserNew.aspx.cs プロジェクト: cbigott133/FBA-2016
        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");;
            }
        }
コード例 #9
0
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs)
        {
            // only continue if a membership provider has been configured
            if (!Utils.IsProviderConfigured())
            {
                return(null);
            }

            // get site details
            SPSite site     = SPContext.Current.Site;
            string provider = Utils.GetMembershipProvider(site);

            if (provider == null)
            {
                return(null);
            }

            SPWeb web = site.RootWeb;

            string yes = LocalizedString.GetString("FBAPackFeatures", "Yes");

            string no = LocalizedString.GetString("FBAPackFeatures", "No");

            string cacheKey = String.Format("Visigo.SharePoint.FormsBasedAuthentication.FBAUsersView.{0}", provider);

            Dictionary <string, SPListItem> spUsers = _cache.Get(cacheKey) as Dictionary <string, SPListItem>;

            //Reload site user info list or grab from cache
            if (_owner.ResetCache || spUsers == null)
            {
                spUsers = new Dictionary <string, SPListItem>();

                // we only display users that have been added to SharePoint
                // we use the localized name, safe for non-English SharePoint servers
                SPList list = web.SiteUserInfoList; //web.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];

                // create query list
                SPQuery query = new SPQuery();
                query.Query = string.Format(
                    "<Where>" +
                    "<And>" +
                    "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq>" +
                    "<Contains><FieldRef Name='Name' /><Value Type='Text'>{0}</Value></Contains>" +
                    "</And>" +
                    "</Where>", provider);

                query.ViewFields = "<FieldRef Name='Name' /><FieldRef Name='LinkTitle' /><FieldRef Name='Email' /><FieldRef Name='Modified' /><FieldRef Name='Created' />";
                query.RowLimit   = 100000;
                //Convert SPListItemCollection to dictionary for fast lookup

                try
                {
                    SPListItemCollection userList = list.GetItems(query);

                    if (userList != null)
                    {
                        foreach (SPListItem item in userList)
                        {
                            string username    = item["Name"] as string;
                            string decodedName = Utils.DecodeUsername(username);
                            if (username != decodedName)
                            {
                                spUsers.Add(decodedName, item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex);
                    return(null);
                }

                _cache.Add(cacheKey, spUsers, null,
                           DateTime.UtcNow.AddMinutes(1.0),
                           System.Web.Caching.Cache.NoSlidingExpiration,
                           System.Web.Caching.CacheItemPriority.Normal, null);
            }

            //Create a datatable for returning the results
            DataTable users = new DataTable();

            users.Columns.Add("Title");
            users.Columns.Add("Name");
            users.Columns.Add("Email");
            users.Columns.Add("Modified", typeof(DateTime));
            users.Columns.Add("Created", typeof(DateTime));
            users.Columns.Add("Active");
            users.Columns.Add("Locked");
            users.Columns.Add("LastLogin", typeof(DateTime));
            users.Columns.Add("IsInSharePoint");

            int totalRecords = 0;
            int spUsersCount = spUsers.Count;
            int spUsersFound = 0;

            users.BeginLoadData();

            //Add all membership users to the datatable
            foreach (MembershipUser memberuser in Utils.BaseMembershipProvider(site).GetAllUsers(0, 100000, out totalRecords))
            {
                string   title          = null;
                string   email          = memberuser.Email;
                DateTime?modified       = null;
                DateTime?created        = null;
                string   isInSharepoint = no;

                SPListItem spUser = null;

                //See if there is a matching sharepoint user - if so grab the values
                if (spUsersFound < spUsersCount)
                {
                    if (spUsers.TryGetValue(memberuser.UserName.ToLower(), out spUser))
                    {
                        spUsersFound++;
                        title          = spUser["Title"] as string;
                        created        = spUser["Created"] as DateTime?;
                        modified       = spUser["Modified"] as DateTime?;
                        isInSharepoint = yes;
                        //Make sure the SharePoint email field has a value before copying it over
                        string spEmail = spUser["EMail"] as string;
                        if (!String.IsNullOrEmpty(spEmail))
                        {
                            email = spEmail;
                        }
                    }
                }

                //Add the matched up membership + sharepoint data to the datatable
                users.LoadDataRow(new object[] {
                    title,
                    memberuser.UserName,
                    email,
                    modified,
                    created,
                    memberuser.IsApproved ? yes : no,
                    memberuser.IsLockedOut ? yes : no,
                    memberuser.LastLoginDate,
                    isInSharepoint
                }, false);
            }

            users.EndLoadData();

            // sort if a sort expression available
            DataView dataView = new DataView(users);

            if (selectArgs.SortExpression != String.Empty)
            {
                dataView.Sort = selectArgs.SortExpression;
            }

            //Filter the data if a filter is provided
            if (_owner.SearchText.Length > 0)
            {
                dataView.RowFilter = string.Format("Name LIKE '%{0}%' OR Email LIKE '%{0}%' OR Title LIKE '%{0}%'", _owner.SearchText);
            }
            else
            {
                dataView.RowFilter = "";
            }

            // return as a DataList
            return((IEnumerable)dataView);
        }
コード例 #10
0
        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");;
            }
        }
コード例 #11
0
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs)
        {
            
            // only continue if a membership provider has been configured
            if (!Utils.IsProviderConfigured())
                return null;

            // get site details
            SPSite site = SPContext.Current.Site;
            string provider = Utils.GetMembershipProvider(site);
            if (provider == null)
                return null;
            
            SPWeb web = site.RootWeb;

            string yes = LocalizedString.GetString("FBAPackFeatures", "Yes");

            string no = LocalizedString.GetString("FBAPackFeatures", "No");

            // we only display users that have been added to SharePoint
            // we use the localized name, safe for non-English SharePoint servers
            SPList list = web.SiteUserInfoList; //web.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];

            // create query list
            SPQuery query = new SPQuery();
            query.Query = string.Format(
                "<Where>" +
                    "<And>" +
                        "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq>" +
                        "<Contains><FieldRef Name='Name' /><Value Type='Text'>{0}</Value></Contains>" +
                    "</And>" +
                "</Where>" +
                "<OrderBy>" +
                    "<FieldRef Name='LinkTitle' />" +
                "</OrderBy>", provider);

            query.ViewFields = "<FieldRef Name='Name' /><FieldRef Name='LinkTitle' /><FieldRef Name='Email' /><FieldRef Name='Modified' /><FieldRef Name='Created' />";

            // run query to get table of users
            DataTable users = null;
            try
            {
                users = list.GetItems(query).GetDataTable();
            }
            catch (Exception ex) 
            {
                Utils.LogError(ex);
                return null;
            }

            if (users == null)
            {
                users = new DataTable();
                users.Columns.Add("ID");
                users.Columns.Add("Title");
                users.Columns.Add("Name");
                users.Columns.Add("LinkTitle");
                users.Columns.Add("Email");
                users.Columns.Add("Modified", typeof(DateTime));
                users.Columns.Add("Created", typeof(DateTime));
            }

            users.Columns.Add("Active");
            users.Columns.Add("Locked");
            users.Columns.Add("LastLogin", typeof(DateTime));
            users.Columns.Add("IsInSharePoint");
            users.Columns.Add("CMITLocation");
            users.Columns.Add("TelephoneNumber");
            users.Columns.Add("CMITTitle");
            users.Columns.Add("Dateofprovisioning", typeof(DateTime));
            users.Columns.Add("NonProviderName");


            // Add additional user data to table
            foreach (DataRow row in users.Rows)
            {
                // remove provider name to get actual user name
                string userName = Utils.DecodeUsername(row["Name"].ToString());
                row["NonProviderName"] = userName;
            }

            int totalRecords = 0;

            foreach (MembershipUser memberuser in Utils.BaseMembershipProvider(site).GetAllUsers(0,100000, out totalRecords))
            {
                bool bFoundMember = false;
                foreach (DataRow row in users.Rows)
                {
                    if (memberuser.UserName.ToLower() == row["NonProviderName"].ToString().ToLower())
                    {
                        SPListItem userItem = web.SiteUserInfoList.GetItemById(Convert.ToInt32(row["ID"]));
                        row["Name"] = memberuser.UserName;
                        row["Active"] = memberuser.IsApproved ? yes : no;
                        row["Locked"] = memberuser.IsLockedOut ? yes : no;
                        row["LastLogin"] = memberuser.LastLoginDate;
                        row["IsInSharePoint"] = yes;
                        row["CMITLocation"] = userItem["CMIT Location"] as string ==null? string.Empty: userItem["CMIT Location"] as string;
                        row["TelephoneNumber"] = userItem["Telephone Number"] as string ==null? string.Empty : userItem["Telephone Number"] as string;
                        row["CMITTitle"] = userItem["CMITTitle"] as string ==null ? string.Empty : userItem["CMITTitle"] as string;
                        row["Dateofprovisioning"] = (userItem["Date of provisioning"] as DateTime?).HasValue ? (userItem["Date of provisioning"] as DateTime?).Value : memberuser.CreationDate;

                        bFoundMember = true;
                        //users.Rows[i].Delete();
                        break;
                    }
                }
                if (!bFoundMember)
                {
                    //Add member to the data table
                    DataRow datanewuser = users.NewRow();
                    datanewuser["Name"] = memberuser.UserName;
                    datanewuser["Email"] = memberuser.Email;
                    datanewuser["Active"] = memberuser.IsApproved ? yes : no;
                    datanewuser["Locked"] = memberuser.IsLockedOut ? yes : no;
                    datanewuser["LastLogin"] = memberuser.LastLoginDate;
                    datanewuser["IsInSharePoint"] = no;
                    users.Rows.Add(datanewuser);
                }
                
            }

            //Remove users that weren't found in SharePoint
            for(int i = users.Rows.Count - 1; i >= 0; i--)
            {
                if (users.Rows[i]["IsInSharePoint"].ToString() != yes && users.Rows[i]["IsInSharePoint"].ToString() != no)
                {
                    users.Rows[i].Delete();
                }
            }

            // sort if a sort expression available
            DataView dataView = new DataView(users);
            if (selectArgs.SortExpression != String.Empty)
            {
                dataView.Sort = selectArgs.SortExpression;
            }

            //Filter the data if a filter is provided
            if (_owner.SearchText.Length > 0)
            {
                dataView.RowFilter = string.Format("Name LIKE '%{0}%' OR Email LIKE '%{0}%' OR Title LIKE '%{0}%'", _owner.SearchText);
            }
            else
            {
                dataView.RowFilter = "";
            }

            // return as a DataList            
            return (IEnumerable)dataView;
        }      
コード例 #12
0
        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);
            }
        }