Exemplo n.º 1
0
        private static void SetSecurityOnRessouces(SPWeb Web, SPList List)
        {
            // list permission levels
            foreach (SPRoleDefinition PermLevel in Web.RoleDefinitions)
            {
                Console.WriteLine(string.Format("Role: {0}, ID: {1}", PermLevel.Name, PermLevel.Id));
            }

            // list groups
            foreach (SPGroup gp in Web.SiteGroups)
            {
                Console.WriteLine(string.Format("Group: {0}", gp.Name));
            }

            // break rights inheritance - boolean: copy permissions
            List.BreakRoleInheritance(false);

            // assign permissions to class\katja
            Web.SiteUsers.Add(@"class\katja", "*****@*****.**", "Katja", "a test user");

            SPUser usrKatja = Web.SiteUsers[@"class\katja"]; //login name

            if (usrKatja != null)
            {
                usrKatja.Name  = "Katja";
                usrKatja.Email = "*****@*****.**";
                usrKatja.Update();

                // create a new permission level
                SPRoleDefinition PermLevelFull = Web.RoleDefinitions["Full Control"];

                SPRoleAssignment KatjaAssign =
                    new SPRoleAssignment(usrKatja.LoginName, usrKatja.Email, usrKatja.Name, usrKatja.Notes);

                // Bind Assignment to definition
                KatjaAssign.RoleDefinitionBindings.Add(PermLevelFull);

                List.RoleAssignments.Add(KatjaAssign);

                List.Update();
            }
        }
 public void UpdateUser(UserObject user)
 {
     if (user == null)
     {
         return;
     }
     if (string.IsNullOrEmpty(user.UserName))
     {
         return;
     }
     try
     {
         SPUser sharepointUser = GetUserObject(user.UserName);
         if (sharepointUser == null)
         {
             return;
         }
         if (user.Email != string.Empty)
         {
             sharepointUser.Email = user.Email;
         }
         if (user.Name != string.Empty)
         {
             sharepointUser.Name = user.Name;
         }
         if (user.Notes != string.Empty)
         {
             sharepointUser.Notes = user.Notes;
         }
         sharepointUser.Update();
     }
     catch (Exception ex)
     {
         var log = new AppEventLog(AppException.ExceptionMessage(ex, "UpdateUser", "ClsHelper"));
         log.WriteToLog();
     }
 }
Exemplo n.º 3
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"));
            }
        }
        /// <summary>
        /// Ensures the users.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Ensure User Response Object</returns>
        public EnsureUserRequestResponse EnsureUsers(EnsureUserRequestResponse request)
        {
            EnsureUserRequestResponse response = new EnsureUserRequestResponse();

            if (request != null && request.Users != null && request.Users.Count > 0)
            {
                Guid siteId = SPContext.Current.Site.ID;
                Guid webId  = SPContext.Current.Web.ID;

                List <User> users = new List <User>();
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(siteId))
                    {
                        using (SPWeb web = site.OpenWeb(webId))
                        {
                            bool unsafeUpdateStatus = web.AllowUnsafeUpdates;
                            try
                            {
                                web.AllowUnsafeUpdates = true;

                                foreach (var user in request.Users)
                                {
                                    SPUser spuser = default(SPUser);

                                    if (user.LoginName.Contains("|"))
                                    {
                                        spuser = web.EnsureUser(user.LoginName);
                                    }
                                    else
                                    {
                                        spuser = web.EnsureUser(user.EmailId);
                                    }

                                    if (spuser != null)
                                    {
                                        if (string.IsNullOrEmpty(spuser.Email) && !string.IsNullOrEmpty(user.EmailId))
                                        {
                                            spuser.Email = user.EmailId;
                                            spuser.Update();
                                        }

                                        user.LoginName = spuser.LoginName;

                                        users.Add(user);
                                    }
                                }

                                response.Users = users;
                            }
                            catch
                            {
                                throw;
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = unsafeUpdateStatus;
                            }
                        }
                    }
                });
            }

            return(response);
        }
Exemplo n.º 5
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            SPSite site   = SPContext.Current.Site;
            SPWeb  mySite = SPContext.Current.Web;

            mySite.AllowUnsafeUpdates = true;

            pnlEdit.Visible   = false;
            GridView1.Visible = true;
            Hashtable myHash = new Hashtable();
            SPUser    user   = mySite.AllUsers[HiddenUsername.Value];


            bool hasGroup = false;
            bool addGroup = false;

            foreach (SPGroup group in user.Groups)
            {
                try
                {
                    string g = mySite.Groups[group.Name].Name;
                    hasGroup = true;
                }
                catch
                {
                }
            }

            bool setSiteAdmin = false;

            if (Request["Groups"] != null)
            {
                string[] groups = Request["Groups"].Split(',');
                if (groups.Length > 0)
                {
                    foreach (string group in groups)
                    {
                        if (group == "@")
                        {
                            setSiteAdmin = true;
                        }
                        else
                        {
                            try
                            {
                                myHash.Add(group, "");
                                mySite.Groups[group].AddUser(user);
                                addGroup = true;
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            foreach (SPGroup g in mySite.SiteGroups)
            {
                string group = g.Name;
                if (mySite.SiteGroups[group].CanCurrentUserEditMembership)
                {
                    if (!myHash.Contains(group))
                    {
                        try
                        {
                            mySite.Groups[group].RemoveUser(user);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            if (mySite.UserIsSiteAdmin)
            {
                if (setSiteAdmin)
                {
                    user.IsSiteAdmin = true;
                    user.Update();
                }
                else
                {
                    user.IsSiteAdmin = false;
                    user.Update();
                }
            }

            Microsoft.SharePoint.Utilities.SPUtility.Redirect("epmlive/sitepermissions.aspx?", Microsoft.SharePoint.Utilities.SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
        }
        //这个没用,可以注释掉,Onload 成功后直接就 Redirect 掉了 ,除非以后成功后还容许在这个界面上设置一些用户属性
        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      = txtEmail.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;
                    }


                    // update sharepoint user info
                    if (spuser != null)
                    {
                        spuser.Email = txtEmail.Text;
                        spuser.Name  = txtFullName.Text;
                        spuser.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"));
            }
        }