Ejemplo n.º 1
0
 /// <summary>
 /// Метод, возвращающий права для группы по умолчанию, в зависимости от карточки и её статуса
 /// </summary>
 /// <param name="Group">Группа</param>
 /// <returns></returns>
 private static AccessData GetGroupAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies)
 {
     AccessData result = new AccessData();
     switch (Item.ParentList.Title)
     {
         default: break;
         case GlobalConstants.ListNames.ControlMeasures:
             {
             }
             break;
         case GlobalConstants.ListNames.Request:
             {
             }
             break;
         case GlobalConstants.ListNames.Inbox:
             {
             }
             break;
         case GlobalConstants.ListNames.Outbox:
             {
             }
             break;
     }
     return result;
 }
        private void AssertSPListHost(SPList targetList, SPGroup securityGroup, SecurityRoleLinkDefinition securityRoleLinkModel)
        {
            var web = targetList.ParentWeb;
            var role = web.RoleDefinitions[securityRoleLinkModel.SecurityRoleName];

            // check if roleAssignment has current  role

            TraceUtils.WithScope(traceScope =>
            {
                traceScope.WriteLine(string.Format("Validate model:[{0}] securableObject:[{1}]", securityRoleLinkModel, targetList));

                traceScope.WithTraceIndent(trace =>
                {
                    // asserting it exists
                    traceScope.WriteLine(string.Format("Validating existance..."));

                    var roleAssignment = targetList
                                            .RoleAssignments
                                            .OfType<SPRoleAssignment>()
                                            .FirstOrDefault(r => r.Member.ID == securityGroup.ID);

                    Assert.IsNotNull(roleAssignment);

                    traceScope.WriteLine(string.Format("Validating role presence..."));
                    roleAssignment.RoleDefinitionBindings.Contains(role);

                    traceScope.WriteLine(string.Format("Role [{0}] exists!", securityRoleLinkModel.SecurityRoleName));
                });
            });
        }
Ejemplo n.º 3
0
        public GroupNode(SPGroup group)
        {
            this.Tag = group;
            this.SPParent = group.ParentWeb;
            //this.WebNode = webNode;

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
        private void ProcessSPGroupHost(SPGroup modelHost, SPGroup securityGroup, SecurityRoleLinkDefinition securityRoleLinkModel)
        {
            // TODO
            // need common validation infrastructure
            var web = securityGroup.ParentWeb;

            var securityRoleAssignment = new SPRoleAssignment(securityGroup);
            var roleDefinition = web.RoleDefinitions[securityRoleLinkModel.SecurityRoleName];

            if (!securityRoleAssignment.RoleDefinitionBindings.Contains(roleDefinition))
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = null,
                    ObjectType = typeof(SPRoleDefinition),
                    ObjectDefinition = securityRoleLinkModel,
                    ModelHost = modelHost
                });

                securityRoleAssignment.RoleDefinitionBindings.Add(roleDefinition);
            }
            else
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = roleDefinition,
                    ObjectType = typeof(SPRoleDefinition),
                    ObjectDefinition = securityRoleLinkModel,
                    ModelHost = modelHost
                });
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = roleDefinition,
                ObjectType = typeof(SPRoleDefinition),
                ObjectDefinition = securityRoleLinkModel,
                ModelHost = modelHost
            });

            web.RoleAssignments.Add(securityRoleAssignment);
            web.Update();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Determines whether The specified user is part of the specified SharePoint user group.
        /// This method will also check users in the active directory groups if any are in the SharePoint group.
        /// </summary>
        /// <param name="user">The SharePoint user.</param>
        /// <param name="group">The SharePoint group.</param>
        /// <returns>True if the user is part of the specified group.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// user or group is null
        /// </exception>
        public bool IsUserInGroup(SPUser user, SPGroup group)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (group == null)
            {
                throw new ArgumentNullException("group");
            }

            var usersInGroup = this.GetUsersInPrincipal(group);
            return HasUserInList(usersInGroup, user);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Метод возвращает необходимые состояния кнопок для карточки КМ
        /// </summary>
        /// <param name="Item">Текущий Item</param>
        /// <param name="State">Текущий статус карточки</param>
        /// <returns></returns>
        private static AccessData GetCMAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies)
        {
            AccessData result = new AccessData();

            bool IsExpert = Group.Name == GlobalConstants.Groups.Expert;

            bool InCompany = Companies.Any(Company => Item[GlobalConstants.ControlMeasure_Fields.CompanyName].ToString().Contains(Company));

            bool Approver = new SPFieldUserValue(Web, Item[GlobalConstants.ControlMeasure_Fields.Approver].ToString()).User.ID == Web.CurrentUser.ID;

            bool Responsible = new SPFieldUserValue(Web, Item[GlobalConstants.ControlMeasure_Fields.Responsible].ToString()).User.ID == Web.CurrentUser.ID;

            bool InMailingList = new SPFieldUserValueCollection(Web, Item[GlobalConstants.ControlMeasure_Fields.MailingList].ToString()).Any(User => User.User.ID == Web.CurrentUser.ID);

            bool AuditorOrAdministrator = Group.Name == GlobalConstants.Groups.Administrator || Group.Name == GlobalConstants.Groups.Auditor;

            result.Edit.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Edit.Visible = State;

            result.Bind.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Bind.Visible = State;

            result.CreateNewRequestCM.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) && (!AuditorOrAdministrator);
            result.CreateNewRequestCM.Visible = State;

            result.ExcelExport.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert)&& (!AuditorOrAdministrator);
            result.ExcelExport.Visible = State;

            result.ToAffirmation.Enabled = ((InCompany || Responsible || InMailingList) && IsExpert) && (!AuditorOrAdministrator);
            result.ToAffirmation.Visible = State;

            result.ToWork.Enabled = (Approver && IsExpert) && (!AuditorOrAdministrator);
            result.ToWork.Visible = State;

            result.ToRework.Enabled = (Approver && IsExpert) && (!AuditorOrAdministrator);
            result.ToRework.Visible = State;

            result.Close.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Close.Visible = State;

            //
            //Нужно доделать доступность кнопок в зависимости от дополнительных параметров, как-то : указана ли компания, какой текущий статус карточки и тд тп
            //
            //                                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            return result;
        }
 /// <summary>
 /// Grants list level permissions to a target sharepoint on the HTS site.
 /// </summary>
 /// <param name="spTargetGroup">Represents an instance of a HTS security group.</param>
 /// <param name="spAssignRoleType">Represents an instance of a target HTS role type.</param>
 /// <param name="spTargetList">Represents an instance of the target list where we grant the security group permission to.</param>
 private static void GrantGroupListLevelPermisisons(SPGroup spTargetGroup, SPRoleType spAssignRoleType, SPList spTargetList)
 {
     if (spTargetList.HasUniqueRoleAssignments == false)
     {
         spTargetList.BreakRoleInheritance(true);
     }
     /* Remove the user from the role assignment. */
     spTargetList.RoleAssignments.Remove(spTargetGroup);
     SPRoleAssignment roleAssign = new SPRoleAssignment(spTargetGroup);
     SPRoleDefinition roleDef = spTargetList.ParentWeb.RoleDefinitions.GetByType(spAssignRoleType);
     roleAssign.RoleDefinitionBindings.Add(roleDef);
     spTargetList.RoleAssignments.Add(roleAssign);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns a list presenting the SharePoint Security Groups for the current web that have a specified permission associated with them
        /// </summary>
        /// <param name="webUrl">The URL for the SP site</param>
        /// <param name="permissionLevel">The permission level the groups must have</param>
        /// <returns>A list of groups (wrapped by a ResponseObject)</returns>
        internal GetSecurityGroupsResponse GetSecurityGroups(GlymaPermissionLevel permissionLevel)
        {
            GetSecurityGroupsResponse result = new GetSecurityGroupsResponse()
            {
                HasError = false
            };
            IList <GlymaSecurityGroup> results = new List <GlymaSecurityGroup>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(WebUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPRoleDefinition roleDefinition = null;
                            try
                            {
                                // Check if the role exists, if it does a definition will exist
                                roleDefinition = web.RoleDefinitions[GlymaPermissionLevelHelper.GetPermissionLevelName(permissionLevel)];
                            }
                            catch (Exception)
                            {
                                //if unable to find the role definition it will throw an exception
                            }

                            if (roleDefinition != null)
                            {
                                SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                                foreach (SPRoleAssignment roleAssignment in roleAssignments)
                                {
                                    bool hasRoleDefinition = false;
                                    foreach (
                                        SPRoleDefinition definition in roleAssignment.RoleDefinitionBindings)
                                    {
                                        if (definition.Id == roleDefinition.Id)
                                        {
                                            //The role exists for this role assignment
                                            hasRoleDefinition = true;
                                            break;
                                        }
                                    }

                                    if (hasRoleDefinition)
                                    {
                                        SPGroup group = roleAssignment.Member as SPGroup;
                                        //we only want to look at groups
                                        if (group != null)
                                        {
                                            GlymaSecurityGroup glymaGroup = new GlymaSecurityGroup();
                                            glymaGroup.DisplayName        = group.Name;

                                            SecurableContext securableContext = this.GetSecurableContext();
                                            glymaGroup.SecurableContextId     = securableContext.SecurableContextId;

                                            GlymaSecurityGroupContext sgc = new GlymaSecurityGroupContext(this, securableContext.SecurableContextId, group.ID, web.ID);
                                            Group glGroup = sgc.GetGroup(group.Name);
                                            if (glGroup == null)
                                            {
                                                glGroup = sgc.CreateGroup(group.Name);
                                            }
                                            if (glGroup != null)
                                            {
                                                glymaGroup.GroupId = glGroup.GroupId;
                                                results.Add(glymaGroup);
                                            }
                                            else
                                            {
                                                result.HasError     = true;
                                                result.ErrorMessage = "Failed to create the Group in the Glyma Security Database.";
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                results = new List <GlymaSecurityGroup>(); //there was no role by this name, it has no groups
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                //If an error occurs getting the group listing return no groups
                result.HasError     = true;
                result.ErrorMessage = ex.Message;
            }
            if (!result.HasError)
            {
                result.Result = results;
            }
            return(result);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            SPGroup publishersGroup = WorkBox.OwningTeam.PublishersGroup(SPContext.Current.Site);

            if (publishersGroup != null)
            {
                if (publishersGroup.ContainsCurrentUser)
                {
                    userCanPublishToPublic = true;
                }
            }

            if (!IsPostBack)
            {
                if (Request.QueryString["selectedItemsIDsString"] != null && Request.QueryString["selectedListGUID"] != null)
                {
                    manager = new WBRecordsManager(SPContext.Current.Web.CurrentUser.LoginName);
                    string   selectedListGUID = Request.QueryString["selectedListGUID"];
                    string[] selectedItemsIDs = Request.QueryString["selectedItemsIDsString"].ToString().Split('|');

                    WBLogging.Debug("Before creating the WBProcessObject");

                    process = new WBPublishingProcess(WorkBox, selectedListGUID, selectedItemsIDs);

                    WBLogging.Debug("Created the WBProcessObject");

                    PublishingProcessJSON.Value = WBUtils.SerializeToCompressedJSONForURI(process);

                    String html = "";

                    WBLogging.Debug("Created the WBProcessObject and serialised " + PublishingProcessJSON.Value);

                    if (process.ItemIDs.Count == 0)
                    {
                        WBLogging.Debug("process.ItemIDs.Count == 0");
                        html += "<i>No documents selected!</i>";
                    }
                    else
                    {
                        html += "<table cellpadding='0px' cellspacing='5px'>";

                        foreach (String itemID in process.ItemIDs)
                        {
                            String filename = process.MappedFilenames[itemID];

                            WBLogging.Debug("list through item with name: " + filename);
                            html += "<tr><td align='center'><img src='" + WBUtils.DocumentIcon16(filename) + "' alt='Icon for file " + filename + "'/></td><td align='left'>" + filename + "</td></tr>\n";

                            String fileType = WBUtils.GetExtension(filename);
                            if (!fileTypes.Contains(fileType))
                            {
                                fileTypes.Add(fileType);
                            }
                        }

                        html += "</table>";

                        List <string> disallowedFileTypes = manager.GetFileTypesDisallowedFromBeingPublishedToPublic(fileTypes);

                        if (String.IsNullOrEmpty(WorkBox.OwningTeam.InformationAssetOwnerLogin))
                        {
                            PublicWebSiteButton.Enabled          = false;
                            PublicNotAllowedMessage.Text         = "You cannot publish to the public website because the owning team of this work box does not have an assigned Information Asset Owner(IAO)";
                            PublicExtranetButton.Enabled         = false;
                            PublicExtranetNotAllowedMessage.Text = "You cannot publish to the public website because the owning team of this work box does not have an assigned Information Asset Owner(IAO)";
                        }
                        else if (!WorkBox.OwningTeam.IsCurrentUserTeamMember())
                        {
                            PublicWebSiteButton.Enabled          = false;
                            PublicNotAllowedMessage.Text         = "You cannot publish to the public website from here because you are not a member of this work box's owning team";
                            PublicExtranetButton.Enabled         = false;
                            PublicExtranetNotAllowedMessage.Text = "You cannot publish to the public website from here because you are not a member of this work box's owning team";
                        }
                        else if (disallowedFileTypes.Count > 0)
                        {
                            PublicWebSiteButton.Enabled          = false;
                            PublicNotAllowedMessage.Text         = "The following file types have not been approved for publishing to a public website: " + String.Join(", ", disallowedFileTypes.ToArray());
                            PublicExtranetButton.Enabled         = false;
                            PublicExtranetNotAllowedMessage.Text = "The following file types have not been approved for publishing to a public website: " + String.Join(", ", disallowedFileTypes.ToArray());
                        }
                    }

                    DocumentsBeingPublished.Text = html;
                }
                else
                {
                    ErrorMessageLabel.Text = "There was an error with the passed through values";
                }
            }
            else
            {
                process         = WBUtils.DeserializeFromCompressedJSONInURI <WBPublishingProcess>(PublishingProcessJSON.Value);
                process.WorkBox = WorkBox;
            }
        }
 public static SPGroup GetAssociatedMemberGroup(this SPGroup group)
 {
     return(group.ParentWeb.AssociatedMemberGroup);
 }
Ejemplo n.º 11
0
        //internal async Task EnsureVisitor(GenericXmlSecurityToken xmlToken)
        internal void EnsureVisitor(GenericXmlSecurityToken xmlToken)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xmlToken.TokenXml.OuterXml);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsmgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

            XmlNodeList names          = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='name']/saml:AttributeValue", nsmgr);
            XmlNodeList userlogonnames = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userlogonname']/saml:AttributeValue", nsmgr);
            XmlNodeList userids        = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userid']/saml:AttributeValue", nsmgr);
            //string namefirst = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='name']/saml:AttributeValue", nsmgr)[1].InnerText;
            //string userlogonname = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userlogonname']/saml:AttributeValue", nsmgr)[1].InnerText;
            //string userid = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userid']/saml:AttributeValue", nsmgr)[1].InnerText;

            Guid id = SPContext.Current.Site.ID;

            //await Task.Run(() => SPSecurity.RunWithElevatedPrivileges(delegate()
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPWeb elevatedWeb = new SPSite(id).OpenWeb())
                {
                    elevatedWeb.AllowUnsafeUpdates = true;
                    List <SPUser> spUsers          = new List <SPUser>();

                    foreach (XmlNode node in names)
                    {
                        try
                        {
                            SPUser spUserbyname = elevatedWeb.EnsureUser(node.InnerText);

                            if (!spUsers.Any <SPUser>(u => u.ID == spUserbyname.ID))
                            {
                                spUsers.Add(spUserbyname);
                            }
                            //break;
                        }
                        catch (Exception ex)
                        {
                            ProviderLogging.LogError(ex);
                        }
                    }
                    foreach (XmlNode node in userlogonnames)
                    {
                        try
                        {
                            SPUser spUserbyname = elevatedWeb.EnsureUser(node.InnerText);
                            if (!spUsers.Any <SPUser>(u => u.ID == spUserbyname.ID))
                            {
                                spUsers.Add(spUserbyname);
                            }
                            //break;
                        }
                        catch (Exception ex)
                        {
                            ProviderLogging.LogError(ex);
                        }
                    }


                    foreach (XmlNode node in userids)
                    {
                        try
                        {
                            SPUser spUserbyname = elevatedWeb.EnsureUser(node.InnerText);
                            if (!spUsers.Any <SPUser>(u => u.ID == spUserbyname.ID))
                            {
                                spUsers.Add(spUserbyname);
                            }
                            //break;
                        }
                        catch (Exception ex)
                        {
                            ProviderLogging.LogError(ex);
                        }
                    }

                    elevatedWeb.Update();

                    try
                    {
                        if (spUsers != null && spUsers.Count > 0)
                        {
                            SPGroup usersGroup   = elevatedWeb.SiteGroups.GetByID(7);
                            SPGroup visitorGroup = elevatedWeb.AssociatedVisitorGroup;

                            foreach (SPUser user in spUsers)
                            {
                                usersGroup.AddUser(user);
                                visitorGroup.AddUser(user);
                            }

                            /*
                             * if(usersGroup != null)
                             * {
                             *
                             *  usersGroup.AddUser(spUser);
                             * }
                             *
                             * //.SiteGroups.Web.AssociatedVisitorGroup;
                             * if (visitorGroup != null)
                             * {
                             *  visitorGroup.AddUser(spUser);
                             * }
                             */
                        }
                    }
                    catch (Exception ex)
                    {
                        ProviderLogging.LogError(ex);
                    }
                    finally
                    {
                        elevatedWeb.Update();
                    }

                    elevatedWeb.AllowUnsafeUpdates = false;
                }
            });
            //}));
        }
Ejemplo n.º 12
0
        public void setUpGroups()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(myWebToPublish.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPUser owner = null;
                        try
                        {
                            owner = web.SiteUsers[_username];
                        }catch {}
                        string aowner   = "";
                        string amember  = "";
                        string avisitor = "";
                        string strEPMLiveGroupsPermAssignments = "";
                        Guid lockweb = EPMLiveCore.CoreFunctions.getLockedWeb(web);
                        if (lockweb != Guid.Empty)
                        {
                            using (SPWeb lweb = web.Site.OpenWeb(lockweb))
                            {
                                aowner   = EPMLiveCore.CoreFunctions.getConfigSetting(lweb, "EPMLiveNewProjectRoleOwners");
                                amember  = EPMLiveCore.CoreFunctions.getConfigSetting(lweb, "EPMLiveNewProjectRoleMembers");
                                avisitor = EPMLiveCore.CoreFunctions.getConfigSetting(lweb, "EPMLiveNewProjectRoleVisitors");
                                strEPMLiveGroupsPermAssignments = EPMLiveCore.CoreFunctions.getConfigSetting(lweb, "EPMLiveGroupsPermAssignments");
                            }
                        }

                        web.Update();

                        //=========Owner Group========================
                        SPRole roll = web.Roles["Full Control"];
                        try
                        {
                            if (aowner != "")
                            {
                                web.AssociatedOwnerGroup = web.SiteGroups.GetByID(int.Parse(aowner));
                                roll.AddGroup(web.SiteGroups.GetByID(int.Parse(aowner)));
                            }
                            else
                            {
                                web.AssociatedOwnerGroup = GetSiteGroup(web, web.Title + " Administrators", owner);
                                roll.AddGroup(web.SiteGroups[web.Title + " Administrators"]);
                            }
                        }
                        catch (Exception ex)
                        {
                            myLog.WriteEntry("Error Setting up Owner Group: " + ex.Message + ex.StackTrace, EventLogEntryType.Error, 334);
                        }
                        //=========Member Group========================
                        try
                        {
                            if (amember != "")
                            {
                                web.AssociatedMemberGroup = web.SiteGroups.GetByID(int.Parse(amember));
                                roll = web.Roles["Contribute"];
                                roll.AddGroup(web.SiteGroups.GetByID(int.Parse(amember)));
                            }
                            else
                            {
                                web.AssociatedMemberGroup = GetSiteGroup(web, web.Title + " Members", owner);
                                roll = web.Roles["Contribute"];
                                roll.AddGroup(web.SiteGroups[web.Title + " Members"]);
                            }
                        }
                        catch (Exception ex)
                        {
                            myLog.WriteEntry("Error Setting up Member Group: " + ex.Message + ex.StackTrace, EventLogEntryType.Error, 334);
                        }
                        //=========Visitor Group========================
                        try
                        {
                            if (avisitor != "")
                            {
                                web.AssociatedVisitorGroup = web.SiteGroups.GetByID(int.Parse(avisitor));
                                roll = web.Roles["Read"];
                                roll.AddGroup(web.SiteGroups.GetByID(int.Parse(avisitor)));
                            }
                            else
                            {
                                web.AssociatedVisitorGroup = GetSiteGroup(web, web.Title + " Visitors", owner);
                                roll = web.Roles["Read"];
                                roll.AddGroup(web.SiteGroups[web.Title + " Visitors"]);
                            }
                        }
                        catch (Exception ex)
                        {
                            myLog.WriteEntry("Error Setting up Visitor Group: " + ex.Message + ex.StackTrace, EventLogEntryType.Error, 334);
                        }
                        web.Update();

                        if (strEPMLiveGroupsPermAssignments.Length > 1)
                        {
                            string[] strOuter = strEPMLiveGroupsPermAssignments.Split(new string[] { "|~|" }, StringSplitOptions.None);
                            foreach (string strInner in strOuter)
                            {
                                string[] strInnerMost = strInner.Split('~');
                                SPGroup spGroup       = web.SiteGroups.GetByID(Convert.ToInt32(strInnerMost[0]));
                                //Persist groups & permissions to the database
                                if (spGroup != null)
                                {
                                    SPRoleAssignment spRA = new SPRoleAssignment(spGroup);
                                    spRA.RoleDefinitionBindings.Add(web.RoleDefinitions.GetById(Convert.ToInt32(strInnerMost[1])));
                                    web.RoleAssignments.Add(spRA);
                                }
                            }
                        }
                        web.Update();
                    }
                }
            });
        }
        private Hashtable checkMetadataState()
        {
            Hashtable metadataProblems = new Hashtable();

            if (OwningTeamField.Text.Equals(""))
            {
                metadataProblems.Add(WorkBox.COLUMN_NAME__OWNING_TEAM, "You must enter the owning team.");
            }

            if (InvolvedTeamsField.Text.Equals(""))
            {
                metadataProblems.Add(WorkBox.COLUMN_NAME__INVOLVED_TEAMS, "You must enter at least one involved team.");
            }

            if (RecordsType.Text.Equals(""))
            {
                metadataProblems.Add(WorkBox.COLUMN_NAME__RECORDS_TYPE, "You must enter a records type for this document.");
            }
            else
            {
                // So here we'll load up the actual records type so that we can check what other metadata is required:
                documentRecordsType = new WBRecordsType(recordsTypeTaxonomy, RecordsTypeUIControlValue.Value);

                if (documentRecordsType != null)
                {
                    if (!documentRecordsType.AllowDocumentRecords)
                    {
                        metadataProblems.Add(WorkBox.COLUMN_NAME__RECORDS_TYPE, "You cannot publish documents of this records type. Please choose another.");
                    }


                    if (documentRecordsType.IsFunctionalAreaEditable)
                    {
                        if (FunctionalAreaField.Text == "")
                        {
                            metadataProblems.Add(WorkBox.COLUMN_NAME__FUNCTIONAL_AREA, "The functional area must be set.");
                        }
                    }

                    bool    userCanPublishToPublic = false;
                    SPGroup publishersGroup        = WorkBox.OwningTeam.PublishersGroup(SPContext.Current.Site);
                    if (publishersGroup != null)
                    {
                        if (publishersGroup.ContainsCurrentUser)
                        {
                            userCanPublishToPublic = true;
                        }
                    }

                    if (userCanPublishToPublic)
                    {
                        if (!documentRecordsType.IsZoneAtLeastMinimum(ProtectiveZone.Text))
                        {
                            if (ProtectiveZone.Text == WBRecordsType.PROTECTIVE_ZONE__PUBLIC_EXTRANET)
                            {
                                metadataProblems.Add(WorkBox.COLUMN_NAME__PROTECTIVE_ZONE, "You can only publish to the public extranet zone if the records type has that zone explicitly set. This records type has the minimum zone set as: " + documentRecordsType.DocumentMinimumProtectiveZone);
                            }
                            else
                            {
                                metadataProblems.Add(WorkBox.COLUMN_NAME__PROTECTIVE_ZONE, "The selected protective zone does not meet the minimum requirement for this records type of: " + documentRecordsType.DocumentMinimumProtectiveZone);
                            }
                        }
                    }
                    else
                    {
                        if (ProtectiveZone.Text != WBRecordsType.PROTECTIVE_ZONE__PROTECTED)
                        {
                            metadataProblems.Add(WorkBox.COLUMN_NAME__PROTECTIVE_ZONE, "In this work box you only have permissions to publish to the internal records library.");
                        }
                    }

                    if (documentRecordsType.IsDocumentReferenceIDRequired)
                    {
                        if (ReferenceID.Text.Equals(""))
                        {
                            metadataProblems.Add(WorkBox.COLUMN_NAME__REFERENCE_ID, "You must enter a reference ID for this records type.");
                        }
                    }

                    if (documentRecordsType.IsDocumentReferenceDateRequired)
                    {
                        if (ReferenceDate.IsDateEmpty)
                        {
                            metadataProblems.Add(WorkBox.COLUMN_NAME__REFERENCE_DATE, "You must enter a reference date for this records type.");
                        }
                    }

                    if (documentRecordsType.IsDocumentSeriesTagRequired)
                    {
                        if (SeriesTagDropDownList.SelectedValue.Equals(""))
                        {
                            metadataProblems.Add(WorkBox.COLUMN_NAME__SERIES_TAG, "You must select a series tag for this records type.");
                        }
                    }

                    if (documentRecordsType.IsDocumentScanDateRequired)
                    {
                        if (ScanDate.IsDateEmpty)
                        {
                            metadataProblems.Add(WorkBox.COLUMN_NAME__SCAN_DATE, "You must enter a scan date for this records type.");
                        }
                    }
                }
                else
                {
                    metadataProblems.Add(WorkBox.COLUMN_NAME__RECORDS_TYPE, "Could not find this records type.");
                }
            }

            if (destinationType.Equals(WorkBox.PUBLISHING_OUT_DESTINATION_TYPE__PUBLIC_WEB_SITE) &&
                !ProtectiveZone.SelectedValue.Equals(WBRecordsType.PROTECTIVE_ZONE__PUBLIC))
            {
                if (!metadataProblems.ContainsKey(WorkBox.COLUMN_NAME__PROTECTIVE_ZONE))
                {
                    metadataProblems.Add(WorkBox.COLUMN_NAME__PROTECTIVE_ZONE, "Only documents marked as 'Public' can be published to the Public Web Site");
                }
            }

            return(metadataProblems);
        }
        private void ProcessSPSecurableObjectHost(SPSecurableObject targetSecurableObject, SPGroup securityGroup,
            SecurityRoleLinkDefinition securityRoleLinkModel)
        {
            //// TODO
            // need common validation infrastructure 
            var web = ExtractWeb(targetSecurableObject);

            var roleAssignment = new SPRoleAssignment(securityGroup);

            var role = ResolveSecurityRole(web, securityRoleLinkModel);

            if (!roleAssignment.RoleDefinitionBindings.Contains(role))
            {
                if (roleAssignment.RoleDefinitionBindings.Count == 1
                         && roleAssignment.RoleDefinitionBindings[0].Type == SPRoleType.Reader)
                {
                    roleAssignment.RoleDefinitionBindings.RemoveAll();
                }

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = null,
                    ObjectType = typeof(SPRoleDefinition),
                    ObjectDefinition = securityRoleLinkModel,
                    ModelHost = targetSecurableObject
                });

                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security role link");

                roleAssignment.RoleDefinitionBindings.Add(role);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security role link");

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = role,
                    ObjectType = typeof(SPRoleDefinition),
                    ObjectDefinition = securityRoleLinkModel,
                    ModelHost = targetSecurableObject
                });

            }

            targetSecurableObject.RoleAssignments.Add(roleAssignment);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = role,
                ObjectType = typeof(SPRoleDefinition),
                ObjectDefinition = securityRoleLinkModel,
                ModelHost = targetSecurableObject
            });
        }
Ejemplo n.º 15
0
        private void ProcessSPSecurableObjectHost(SPSecurableObject targetSecurableObject, SPGroup securityGroup,
                                                  SecurityRoleLinkDefinition securityRoleLinkModel)
        {
            //// TODO
            // need common validation infrastructure
            var web = ExtractWeb(targetSecurableObject);

            var roleAssignment = new SPRoleAssignment(securityGroup);

            var role = ResolveSecurityRole(web, securityRoleLinkModel);

            if (!roleAssignment.RoleDefinitionBindings.Contains(role))
            {
                if (roleAssignment.RoleDefinitionBindings.Count == 1 &&
                    roleAssignment.RoleDefinitionBindings[0].Type == SPRoleType.Reader)
                {
                    roleAssignment.RoleDefinitionBindings.RemoveAll();
                }

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = null,
                    ObjectType       = typeof(SPRoleDefinition),
                    ObjectDefinition = securityRoleLinkModel,
                    ModelHost        = targetSecurableObject
                });

                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security role link");

                roleAssignment.RoleDefinitionBindings.Add(role);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security role link");

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = role,
                    ObjectType       = typeof(SPRoleDefinition),
                    ObjectDefinition = securityRoleLinkModel,
                    ModelHost        = targetSecurableObject
                });
            }

            targetSecurableObject.RoleAssignments.Add(roleAssignment);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = role,
                ObjectType       = typeof(SPRoleDefinition),
                ObjectDefinition = securityRoleLinkModel,
                ModelHost        = targetSecurableObject
            });
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Adds the group members (including AD group members) to the 'To' property of the email information.
 /// Only users who have emails are added.
 /// </summary>
 /// <param name="group">The SharePoint group.</param>
 /// <param name="emailInformation">The email information.</param>
 public void AddGroupMembersToRecipients(SPGroup group, EmailInfo emailInformation)
 {
     var users = this.userHelper.GetUsersInPrincipal(group);
     var userEmails = users.Where(u => !string.IsNullOrEmpty(u.Email)).Select(u => u.Email).ToList();
     userEmails.ForEach(ue => emailInformation.To.Add(ue));
 }
 private bool isUserinGroup(SPGroup isgroup, SPUser oUser)
 {
     Boolean bUserIsInGroup = false;
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         if (oUser != null)
         {
             foreach (SPUser item in isgroup.Users)
             {
                 if (item.LoginName == oUser.LoginName)
                 {
                     bUserIsInGroup = true;
                     break;
                 }
             }
         }
     });
     return bUserIsInGroup;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Метод возвращает необходимые состояния кнопок для карточки Исходящего документа
        /// </summary>
        /// <param name="Item">Текущий Item</param>
        /// <param name="State">Текущий статус карточки</param>
        /// <returns></returns>
        private static AccessData GetOutboxAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies)
        {
            AccessData result = new AccessData();

            bool IsExpert = Group.Name == GlobalConstants.Groups.Expert;

            bool InCompany = Companies.Any(Company => Item[GlobalConstants.OutboxCorrespondence_Fields.Company].ToString().Contains(Company));

            bool InMailingList = new SPFieldUserValueCollection(Web, Item[GlobalConstants.OutboxCorrespondence_Fields.DeliveryList].ToString()).Any(User => User.User.ID == Web.CurrentUser.ID);

            bool AuditorOrAdministrator = Group.Name == GlobalConstants.Groups.Administrator || Group.Name == GlobalConstants.Groups.Auditor;

            result.Bind.Enabled = ((InCompany || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Bind.Visible = State;

            result.Edit.Enabled = ((InCompany || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Edit.Visible = State;

            result.Notifications.Enabled = ((InCompany || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Notifications.Visible = State;

            //
            //Нужно доделать доступность кнопок в зависимости от дополнительных параметров, как-то : указана ли компания, какой текущий статус карточки и тд тп
            //
            //                                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            return result;
        }
Ejemplo n.º 19
0
        public void execute(SPSite site, SPWeb web, Guid listId, int itemId, int userid, string data)
        {
            SPList            list        = null;
            SPListItem        li          = null;
            GridGanttSettings settings    = null;
            List <string>     cNewGrps    = null;
            List <string>     fields      = null;
            SPUser            orignalUser = null;
            EnhancedLookupConfigValuesHelper valueHelper = null;
            SPList             lookupPrntList            = null;
            GridGanttSettings  prntListSettings          = null;
            SPFieldLookupValue lookupVal  = null;
            SPListItem         targetItem = null;

            try
            {
                list     = web.Lists[listId];
                li       = list.GetItemById(itemId);
                settings = new GridGanttSettings(list);
                cNewGrps = new List <string>();
                bool isSecure = false;
                try
                {
                    isSecure = settings.BuildTeamSecurity;
                }
                catch { }

                orignalUser = web.AllUsers.GetByID(userid);

                string safeTitle = !string.IsNullOrEmpty(li.Title) ? GetSafeGroupTitle(li.Title) : string.Empty;

                if (string.IsNullOrEmpty(safeTitle) && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                {
                    safeTitle = GetSafeGroupTitle(li.Name); //Assign Name instead of Title - This should perticularly happen with Document libraries.
                }
                if (isSecure)
                {
                    if (!li.HasUniqueRoleAssignments)
                    {
                        web.AllowUnsafeUpdates = true;
                        safeGroupTitle         = safeTitle;

                        safeTitle = GetIdenticalGroupName(site.ID, web.ID, safeTitle, 0);

                        // step 1 perform actions related to "parent item"
                        // ===============================================
                        Dictionary <string, SPRoleType> pNewGrps = null;
                        try
                        {
                            pNewGrps = AddBasicSecurityGroups(web, safeTitle, orignalUser, li);

                            li.BreakRoleInheritance(false);

                            foreach (KeyValuePair <string, SPRoleType> group in pNewGrps)
                            {
                                SPGroup g = web.SiteGroups[group.Key];
                                AddNewItemLvlPerm(li, web, group.Value, g);
                                g = null;
                            }

                            AddBuildTeamSecurityGroups(web, settings, li);
                        }
                        catch { }
                        finally
                        {
                            pNewGrps = null;
                        }
                    }
                }


                // step 2 perform actions related to "child item"
                // ====================================
                // find lookups that has security enabled
                string lookupSettings = settings.Lookups;
                //string rawValue = "Region^dropdown^none^none^xxx|State^autocomplete^Region^Region^xxx|City^autocomplete^State^State^xxx";
                valueHelper = new EnhancedLookupConfigValuesHelper(lookupSettings);

                if (valueHelper == null)
                {
                    return;
                }

                fields = valueHelper.GetSecuredFields();

                bool bHasLookup = false;

                foreach (string fld in fields)
                {
                    SPFieldLookup lookup = null;
                    try
                    {
                        lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                    }
                    catch { }

                    if (lookup == null)
                    {
                        continue;
                    }

                    lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                    prntListSettings = new GridGanttSettings(lookupPrntList);
                    string sVal = string.Empty;
                    try
                    {
                        sVal = li[fld].ToString();
                    }
                    catch { }
                    if (!string.IsNullOrEmpty(sVal))
                    {
                        bHasLookup = true;
                        break;
                    }
                }
                if (bHasLookup)
                {
                    // has security fields
                    if (fields.Count > 0)
                    {
                        // if the list is not a security list itself
                        if (isSecure)
                        {
                            li.BreakRoleInheritance(false);
                        }

                        foreach (string fld in fields)
                        {
                            SPFieldLookup lookup = null;
                            try
                            {
                                lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                            }
                            catch { }

                            if (lookup == null)
                            {
                                continue;
                            }

                            lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                            prntListSettings = new GridGanttSettings(lookupPrntList);
                            bool isEnableSecurity = false;
                            bool isParentSecure   = false;
                            try
                            {
                                isParentSecure = prntListSettings.BuildTeamSecurity;
                            }
                            catch { }

                            string[]  LookupArray = settings.Lookups.Split('|');
                            string[]  sLookupInfo = null;
                            Hashtable hshLookups  = new Hashtable();
                            foreach (string sLookup in LookupArray)
                            {
                                if (sLookup != "")
                                {
                                    sLookupInfo = sLookup.Split('^');
                                    hshLookups.Add(sLookupInfo[0], sLookupInfo);
                                }
                            }
                            try
                            {
                                if (sLookupInfo != null && sLookupInfo[4].ToLower() == "true")
                                {
                                    isEnableSecurity = true;
                                }
                                else
                                {
                                    isEnableSecurity = false;
                                }
                            }
                            catch { isEnableSecurity = false; }

                            // skip fields with empty lookup values
                            string sVal = string.Empty;
                            try { sVal = li[fld].ToString(); }
                            catch { }
                            if (string.IsNullOrEmpty(sVal))
                            {
                                continue;
                            }

                            lookupVal  = new SPFieldLookupValue(sVal.ToString());
                            targetItem = lookupPrntList.GetItemById(lookupVal.LookupId);
                            if (!targetItem.HasUniqueRoleAssignments)
                            {
                                continue;
                            }
                            else
                            {
                                //EPML-4422: When a project is not using unique security, and a child list like tasks is set to Inherit security from the project lookup, It sets the task to unique, but does not add any groups. It should not get set to Unique.
                                if (!isSecure && isParentSecure && isEnableSecurity)
                                {
                                    web.AllowUnsafeUpdates = true;
                                    li.BreakRoleInheritance(false);
                                }
                            }

                            SPRoleAssignmentCollection raCol = targetItem.RoleAssignments;
                            string itemMemberGrp             = "Member";
                            foreach (SPRoleAssignment ra in raCol)
                            {
                                // add their groups to this item but change permission lvl
                                if (ra.Member.Name.Contains(itemMemberGrp))
                                {
                                    SPRoleAssignment newRa  = new SPRoleAssignment(ra.Member);
                                    SPRoleDefinition newDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                    newRa.RoleDefinitionBindings.Add(newDef);
                                    li.RoleAssignments.Add(newRa);
                                }
                                else
                                {
                                    li.RoleAssignments.Add(ra);
                                }

                                cNewGrps.Add(ra.Member.Name);
                            }
                        }
                    }
                }
                ProcessSecurity(site, list, li, userid);

                // we wait until all groups have been created to createworkspace
                // only if there isn't a current process creating ws
                WorkspaceTimerjobAgent.QueueWorkspaceJobOnHoldForSecurity(site.ID, web.ID, list.ID, li.ID);
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                list             = null;
                li               = null;
                lookupPrntList   = null;
                prntListSettings = null;
                settings         = null;
                cNewGrps         = null;
                fields           = null;
                orignalUser      = null;
                valueHelper      = null;
                lookupVal        = null;
                targetItem       = null;
                fields           = null;
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
Ejemplo n.º 20
0
 public SPGroupInstance(ScriptEngine engine, SPGroup group)
     : base(new SPPrincipalInstance(engine, group), group)
 {
     m_group = group;
     PopulateFunctions(GetType(), BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
 }
Ejemplo n.º 21
0
        public void AddBuildTeamSecurityGroups(SPWeb ew, GridGanttSettings settings, SPListItem eI)
        {
            string teamPerm = string.Empty;

            try
            {
                teamPerm = settings.BuildTeamPermissions;
            }
            catch { }
            if (!string.IsNullOrEmpty(teamPerm))
            {
                string[] strOuter = settings.BuildTeamPermissions.Split(new string[] { "|~|" }, StringSplitOptions.None);
                //SPListItem eI = ew.Lists[base.ListUid].GetItemById(base.ItemID);

                foreach (string strInner in strOuter)
                {
                    string[]         strInnerMost = strInner.Split('~');
                    SPGroup          g            = null;
                    SPRoleDefinition r            = null;

                    try
                    {
                        g = ew.SiteGroups.GetByID(Convert.ToInt32(strInnerMost[0]));
                        r = ew.RoleDefinitions.GetById(Convert.ToInt32(strInnerMost[1]));
                    }
                    catch { }
                    if (g != null && r != null)
                    {
                        if (r.Type != SPRoleType.Guest)
                        {
                            SPRoleAssignment assign = new SPRoleAssignment(g);
                            assign.RoleDefinitionBindings.Add(r);
                            AddNewItemLvlPerm(eI, ew, assign);

                            //Adding users with Full Control permission levels to Owners group.
                            if (r.Type == SPRoleType.Administrator) //Full Control Permission Level
                            {
                                //Add users to Owners group.
                                SPUserCollection groupUsers = g.Users;

                                foreach (SPRoleAssignment role in eI.RoleAssignments)
                                {
                                    try
                                    {
                                        if (role.Member.GetType() == typeof(SPGroup))
                                        {
                                            SPGroup group = (SPGroup)role.Member;
                                            if (group.Name.EndsWith("Owner"))
                                            {
                                                try
                                                {
                                                    foreach (SPUser user in groupUsers)
                                                    {
                                                        group.AddUser(user);
                                                    }
                                                    group.Update();
                                                }
                                                catch { }
                                            }
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }
                        else
                        {
                            // create our custom limited access role
                            SPRoleDefinition roleDef = new SPRoleDefinition();

                            try
                            {
                                roleDef = ew.RoleDefinitions["Limited Access Permission"];
                            }
                            catch (SPException)
                            {
                                ew.AllowUnsafeUpdates = true;
                                // give it a name and description
                                roleDef.Name        = "Limited Access Permission";
                                roleDef.Description = "Identical to standard Limited Access rights. Used to provide access to parent objects of uniquely permissioned content";
                                // apply the base permissions required
                                roleDef.BasePermissions = SPBasePermissions.ViewFormPages | SPBasePermissions.Open | SPBasePermissions.BrowseUserInfo | SPBasePermissions.UseClientIntegration | SPBasePermissions.UseRemoteAPIs;
                                // add it to the web
                                ew.RoleDefinitions.Add(roleDef);
                                ew.Update();
                            }

                            try
                            {
                                SPRoleAssignment assign = new SPRoleAssignment(g);
                                assign.RoleDefinitionBindings.Add(roleDef);
                                AddNewItemLvlPerm(eI, ew, assign);
                            }
                            catch { }
                        }
                    }
                }
            }

            //return createdGrps;
        }
Ejemplo n.º 22
0
 public SPGroupInstance(ObjectInstance prototype, SPGroup group)
     : base(prototype, group)
 {
     m_group = group;
 }
Ejemplo n.º 23
0
        }//ItemQueries

        static void GrantPermissions(SPWeb web, SPListItem ccpItem, SPListItem item)
        {
            try
            {
                string userType        = (string)ccpItem["UserType"];                  //user type
                string _user           = (string)ccpItem["User"];                      //user
                string userValue       = new SPFieldUserValue(web, _user).LookupValue; //user value
                string permissionLevel = (string)ccpItem["Permission"];                //set permission level
                string level           = (string)ccpItem["Level"];                     //location of where security object applies



                if (userType != null && _user != null)
                {
                    if (userType == "Active Directory")
                    {
                        try
                        {
                            SPUser           itemAccount    = web.EnsureUser(userValue);
                            SPRoleDefinition itemRole       = web.RoleDefinitions[permissionLevel];
                            SPRoleAssignment itemAssignment = new SPRoleAssignment(itemAccount);
                            itemAssignment.RoleDefinitionBindings.Add(itemRole);
                            item.RoleAssignments.Add(itemAssignment);
                        }
                        catch (SPException e)
                        {
                            item["Permission Log"] = e.Message;
                            item.Update();
                        }
                    }
                    else if (userType == "SharePoint")
                    {
                        try
                        {
                            SPGroup          group          = web.SiteGroups[userValue];
                            SPRoleDefinition itemRole       = web.RoleDefinitions[permissionLevel];
                            SPRoleAssignment itemAssignment = new SPRoleAssignment(group);
                            itemAssignment.RoleDefinitionBindings.Add(itemRole);
                            item.RoleAssignments.Add(itemAssignment);
                        }
                        catch (SPException e)
                        {
                            item["Permission Log"] = e.Message;
                            item.Update();
                        }
                    }
                }//(userType != null && _user != null)
                else
                {
                    //Log
                    item["Permission Log"]    = "Null UserType and User Values.Verify security object is in SharePoint Groups and Active Directory. Check Permission Log for Details.";
                    item["Permission Status"] = "Verify Permissions and Check Permission Log for Details.";
                    item.Update();
                }
            }
            catch (Exception e)
            {
                //Log
                item["Permission Log"]    = e.Message;
                item["Permission Status"] = "Verify Permissions and Check Permission Log for Details.";
                item.Update();
            }
        } //GrantPermissions()
Ejemplo n.º 24
0
 public SPPrincipalInfo(SPGroup group)
 {
     FillPropertiesFrom(group);
 }
 private static bool CheckListLevelPermissions(SPList spTargetList, SPRoleType spAssignRoleType, SPGroup spTargetGroup)
 {
     bool ListLevelPermissionsExists = false;
     foreach (SPRoleAssignment roleAssignment in spTargetList.RoleAssignments)
     {
         if (roleAssignment.Member.Name == spTargetGroup.Name)
         {
             SPRoleDefinition currentRoleDef = spTargetList.ParentWeb.RoleDefinitions.GetByType(spAssignRoleType);
             SPRoleDefinitionBindingCollection spRoleDefs = roleAssignment.RoleDefinitionBindings;
             foreach (SPRoleDefinition spRoleDef in spRoleDefs)
             {
                 if (spRoleDef == currentRoleDef)
                 {
                     ListLevelPermissionsExists = true;
                 }
             }
         }
     }
     return ListLevelPermissionsExists;
 }
Ejemplo n.º 26
0
 public SPDGServerGroup(SPGroup group) : base(group.ID, group.LoginName, group.Name)
 {
     _group = @group;
 }
Ejemplo n.º 27
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(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");;
            }
        }
Ejemplo n.º 28
0
 public static bool InGroup(this SPUser spUser, SPGroup spGroup)
 {
     return spUser.Groups.Cast<SPGroup>()
       .Any(g => g.ID == spGroup.ID);
 }
Ejemplo n.º 29
0
        public static Dictionary <string, SPRoleType> AddBasicSecurityToWorkspace(SPWeb eleWeb, string safeTitle, SPUser owner)
        {
            var safeGroupTitle = string.Empty;

            safeGroupTitle = CoreFunctions.GetSafeGroupTitle(safeTitle);

            eleWeb.AllowUnsafeUpdates = true;
            Dictionary <string, SPRoleType> pNewGroups = new Dictionary <string, SPRoleType>();

            string[] grps     = new[] { "Owner", "Member", "Visitor" };
            SPGroup  ownerGrp = null;

            // add groups and set group owners
            foreach (string grp in grps)
            {
                string  finalName = string.Empty;
                SPGroup testGrp   = null;
                try
                {
                    testGrp = eleWeb.SiteGroups[safeGroupTitle + " " + grp];
                }
                catch { }
                //Commented code is no longer use and commented to resolve Jira Id 2321
                //if (testGrp != null)
                //{
                //    finalName = testGrp.Name;
                //}
                //else
                //{
                try
                {
                    finalName = CoreFunctions.AddGroup(eleWeb, safeGroupTitle, grp, owner, eleWeb.CurrentUser, string.Empty);
                    eleWeb.Update();
                }
                catch { }
                //}

                SPGroup    finalGrp = eleWeb.SiteGroups[finalName];
                SPRoleType rType;
                switch (grp)
                {
                case "Owner":
                    ownerGrp       = finalGrp;
                    rType          = SPRoleType.Administrator;
                    finalGrp.Owner = owner;
                    finalGrp.AddUser(owner);
                    finalGrp.Update();
                    eleWeb.Update();
                    break;

                default:
                    rType          = SPRoleType.Reader;
                    finalGrp.Owner = ownerGrp;
                    finalGrp.Update();
                    eleWeb.Update();
                    break;
                }
                pNewGroups.Add(finalGrp.Name, rType);
            }

            // now set groups to become web's owner, member, visitor
            SPGroup group = null;
            SPRole  roll  = null;

            foreach (KeyValuePair <string, SPRoleType> g in pNewGroups)
            {
                if (g.Key.Contains("Owner"))
                {
                    group = eleWeb.SiteGroups[g.Key];
                    eleWeb.AssociatedOwnerGroup = group;
                    roll = eleWeb.Roles["Full Control"];
                    roll.AddGroup(group);
                }
                else if (g.Key.Contains("Member"))
                {
                    group = eleWeb.SiteGroups[g.Key];
                    eleWeb.AssociatedOwnerGroup = group;
                    roll = eleWeb.Roles["Contribute"];
                    roll.AddGroup(group);
                }
                else if (g.Key.Contains("Visitor"))
                {
                    group = eleWeb.SiteGroups[g.Key];
                    eleWeb.AssociatedOwnerGroup = group;
                    roll = eleWeb.Roles["Read"];
                    roll.AddGroup(group);
                }
            }

            eleWeb.Update();

            return(pNewGroups);
        }
        /// <summary>
        /// Grants permissions to a group for a specific site.
        /// </summary>
        /// <param name="spGroup">Represents a SharePoint group</param>
        /// <param name="sPRoleType">Represents the permission to grant to the target group.</param>
        /// <param name="spWeb">Represents an instance of the Homework Tracking Site as a SPWeb object.</param>
        private static void GrantGroupSiteLevelPermissions(SPGroup spTargetGroup, SPRoleType sPRoleType, SPWeb spWeb)
        {
            if (!spWeb.IsRootWeb)
            {

                if (spWeb.HasUniqueRoleAssignments == false)
                {
                    spWeb.BreakRoleInheritance(true);
                }
                /* Adding the School Administration group. */
                spWeb.RoleAssignments.Remove(spTargetGroup);
                SPRoleAssignment roleAssign = new SPRoleAssignment(spTargetGroup);
                SPRoleDefinition roleDef = spWeb.RoleDefinitions.GetByType(sPRoleType);
                roleAssign.RoleDefinitionBindings.Add(roleDef);
                spWeb.RoleAssignments.Add(roleAssign);

            }
        }
Ejemplo n.º 31
0
        internal static void ToItem <T>(T entity, SPListItem listItem, List <string> propertiesToSet = null)
        {
            var itemType = entity.GetType();
            var props    = itemType.GetProperties();

            foreach (PropertyInfo prop in props)
            {
                if (CommonHelper.IsPropertyNotMapped(prop))
                {
                    continue;
                }

                Assert.IsPropertyVirtual(prop);

                if (propertiesToSet != null && propertiesToSet.Count > 0)
                {
                    if (propertiesToSet.Contains(prop.Name) == false)
                    {
                        continue;
                    }
                }

                string spName;

                // var fieldAttrs = prop.GetCustomAttributes(typeof(FieldAttribute), false);
                var fieldAttrs = Attribute.GetCustomAttributes(prop, typeof(FieldAttribute));
                CustomFieldProvider customFieldProvider = null;
                if (fieldAttrs.Length != 0)
                {
                    spName = ((FieldAttribute)fieldAttrs[0]).Name;
                    if (spName == null)
                    {
                        spName = prop.Name;
                    }
                    customFieldProvider = ((FieldAttribute)fieldAttrs[0]).FieldProvider;
                }
                else
                {
                    spName = FieldMapper.TranslateToFieldName(prop.Name);
                }
                if (FieldMapper.IsReadOnlyField(spName) == false)
                {
                    continue;                                               // skip fields that cant be set
                }
                var propValue = prop.GetValue(entity, null);

                if (propValue == null)
                {
                    listItem[spName] = null;
                    continue;
                }

                if (prop.PropertyType == typeof(string))
                {
                    listItem[spName] = propValue;
                    continue;
                }

                if (prop.PropertyType == typeof(DateTime))
                {
                    // update DateTime field with empty value thrown exception
                    if (((DateTime)propValue) != DateTime.MinValue)
                    {
                        listItem[spName] = propValue;
                    }
                    continue;
                }

                if (prop.PropertyType == typeof(User))
                {
                    // domain user or group
                    Assert.IsPropertyVirtual(prop);

                    var user = (User)propValue;

                    SPFieldUserValue spUserValue = FieldMapper.ToUserValue(user, listItem.Web);

                    listItem[spName] = spUserValue;

                    continue;
                }

                // handle lookup fields
                if (typeof(Item).IsAssignableFrom(prop.PropertyType))
                {
                    Assert.IsPropertyVirtual(prop);

                    if (customFieldProvider == null)
                    {
                        var item   = (Item)propValue;
                        var lookup = new SPFieldLookupValue(item.Id, item.Title);
                        listItem[spName] = lookup;
                    }
                    else
                    {
                        var providerType = customFieldProvider.GetType();
                        var method       = providerType.GetMethod("SetLookupItem");

                        if (method.DeclaringType == typeof(CustomFieldProvider))
                        {
                            throw new SharepointCommonException(string.Format("Must override 'SetLookupItem' in {0} to get custom lookups field working.", providerType));
                        }

                        var value = customFieldProvider.SetLookupItem(propValue);
                        listItem[spName] = value;
                    }
                    continue;
                }

                //// handle multivalue fields
                if (CommonHelper.ImplementsOpenGenericInterface(prop.PropertyType, typeof(IEnumerable <>)))
                {
                    Assert.IsPropertyVirtual(prop);

                    Type argumentType = prop.PropertyType.GetGenericArguments()[0];

                    if (argumentType == typeof(User))
                    {
                        var users = propValue as IEnumerable <User>;
                        Assert.NotNull(users);

                        var values = new SPFieldUserValueCollection();

                        foreach (User user in users)
                        {
                            if (user is Person)
                            {   // domain user or group
                                var    person = (Person)user;
                                SPUser spUser = null;
                                try
                                {
                                    spUser = listItem.ParentList.ParentWeb.SiteUsers[person.Login];
                                }
                                catch (SPException)
                                {
                                    throw new SharepointCommonException(string.Format("User {0} not found.", user.Id));
                                }

                                var val = new SPFieldUserValue();
                                val.LookupId = spUser.ID;
                                values.Add(val);
                            }
                            else
                            {   // sharepoint group
                                SPGroup spGroup = null;
                                try
                                {
                                    spGroup = listItem.ParentList.ParentWeb.SiteGroups[user.Name];
                                }
                                catch (SPException)
                                {
                                    throw new SharepointCommonException(string.Format("Group {0} not found.", user.Name));
                                }

                                var val = new SPFieldUserValue();
                                val.LookupId = spGroup.ID;
                                values.Add(val);
                            }
                        }

                        listItem[spName] = values;
                    }

                    if (typeof(Item).IsAssignableFrom(argumentType))
                    {
                        var lookupvalues = propValue as IEnumerable;

                        if (customFieldProvider == null)
                        {
                            var spLookupValues = new SPFieldLookupValueCollection();

                            foreach (Item lookupvalue in lookupvalues)
                            {
                                var val = new SPFieldLookupValue();
                                val.LookupId = lookupvalue.Id;
                                spLookupValues.Add(val);
                            }

                            listItem[spName] = spLookupValues;
                        }
                        else
                        {
                            var providerType = customFieldProvider.GetType();
                            var method       = providerType.GetMethod("SetLookupItem");

                            if (method.DeclaringType == typeof(CustomFieldProvider))
                            {
                                throw new SharepointCommonException(string.Format("Must override 'SetLookupItem' in {0} to get custom lookups field working.", providerType));
                            }

                            var values = customFieldProvider.SetLookupItem(propValue);
                            listItem[spName] = values;
                        }
                    }
                    continue;
                }

                if (prop.PropertyType.IsEnum)
                {
                    listItem[spName] = EnumMapper.ToItem(prop.PropertyType, propValue);
                    continue;
                }

                var innerType = Nullable.GetUnderlyingType(prop.PropertyType);

                if (innerType != null && innerType.IsEnum)
                {
                    listItem[spName] = EnumMapper.ToItem(innerType, propValue);
                    continue;
                }

                if (prop.PropertyType == typeof(Person))
                {
                    throw new SharepointCommonException("Cannot use [Person] as mapped property. Use [User] instead.");
                }

                listItem[spName] = propValue;
            }
        }
Ejemplo n.º 32
0
 public static string GetDefaultUserLoginName(this SPGroup group)
 {
     return(group.Users[group.Users.Count - 1].LoginName);
 }
Ejemplo n.º 33
0
 public static bool InGroup(this SPUser user, SPGroup group)
 {
     return(user.Groups.Cast <SPGroup>()
            .Any(g => g.ID == group.ID));
 }
Ejemplo n.º 34
0
        public bool IsAuthorised(params IRight[] requiredRights)
        {
            /// We need to filter out only the rights for which kind of query is going to be permitted. In this case only the following rights should be allowed.
            /// 1. All Glyma Security Manager rights as they have unrestricted access to the entire securable context.
            /// 2. Glyma Project Manager create right as they have unrestricted rights to create new domains.
            /// 3. The transaction right as this is a requires transaction to do anything other than reading.
            /// 4. The benign access right as this right doesn't actually have access to do anything and should be given to anyone that has access to the system, even unauthorised people.
            List <IRight> rightsPermittedForThisQuery = new List <IRight>();

            foreach (IRight requiredRight in requiredRights)
            {
                if (requiredRight == SPGlymaRightFactory.Instance.SecurableContextManageRight ||
                    requiredRight == SPGlymaRightFactory.Instance.RootMapCreateRight ||
                    requiredRight == SPGlymaRightFactory.Instance.TransactionRight ||
                    requiredRight == SPGlymaRightFactory.Instance.BenignAccessRight)
                {
                    rightsPermittedForThisQuery.Add(requiredRight);
                }
            }

            IRight[] permittedRights = rightsPermittedForThisQuery.ToArray();

            foreach (SPRoleAssignment roleAssignment in Web.RoleAssignments)
            {
                SPGroup group = roleAssignment.Member as SPGroup;

                /// Check that we're actually looking at a group, that this group contains the current user, and that this group is on the list of accessible groups.
                if (group != null && group.ContainsCurrentUser)
                {
                    /// Do a check that this group actually has the required right.
                    foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                    {
                        IRole role = null;

                        switch (roleDefinition.Name)
                        {
                        case GlymaSecurityManagerRoleName:
                            /// This user is a Glyma Security Manager, they have access to everything.
                            return(true);

                        case GlymaProjectManagerRoleName:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaProjectManagerRole;
                            break;

                        case GlymaMapManagerRoleName:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapManagerRole;
                            break;

                        case GlymaMapAuthorRoleName:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                            break;

                        case GlymaMapReaderRoleName:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                            break;

                        case OldGlymaMapAuthorRoleName:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                            break;

                        case OldGlymaMapReaderRoleName:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                            break;

                        default:
                            role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                            break;
                        }

                        if (role.HasRights(permittedRights))
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Gets the principal.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="memberName">Name of the member.</param>
        /// <param name="loginName">Name of the login.</param>
        /// <returns></returns>
        internal static SPPrincipal GetPrincipal(SPWeb web, string memberName, string loginName)
        {
            foreach (SPPrincipal p in web.SiteUsers)
            {
                if (p.Name.ToLowerInvariant() == memberName.ToLowerInvariant())
                {
                    return(p);
                }
            }
            foreach (SPPrincipal p in web.SiteGroups)
            {
                if (p.Name.ToLowerInvariant() == memberName.ToLowerInvariant())
                {
                    return(p);
                }
            }

            try
            {
                SPPrincipal principal;
                if (!string.IsNullOrEmpty(loginName) && Microsoft.SharePoint.Utilities.SPUtility.IsLoginValid(web.Site, loginName))
                {
                    // We have a user
                    Logger.Write("Progress: Adding user '{0}' to site.", loginName);
                    principal = web.EnsureUser(loginName);
                }
                else
                {
                    // We have a group

                    SPGroup groupToAdd = null;
                    try
                    {
                        groupToAdd = web.SiteGroups[memberName];
                    }
                    catch (SPException)
                    {
                    }
                    if (groupToAdd != null)
                    {
                        // The group exists, so get it
                        principal = groupToAdd;
                    }
                    else
                    {
                        // The group didn't exist so we need to create it:
                        //  Create it:
                        Logger.Write("Progress: Adding group '{0}' to site.", memberName);
                        web.SiteGroups.Add(memberName, web.Site.Owner, web.Site.Owner, string.Empty);
                        //  Get it:
                        principal = web.SiteGroups[memberName];
                    }
                }
                return(principal);
            }
            catch (Exception ex)
            {
                Logger.Write("WARNING: Unable to add member to site: {0}\r\n{1}", memberName, Utilities.FormatException(ex));
            }
            return(null);
        }
Ejemplo n.º 36
0
        public bool IsAuthorised(Guid?domainUid, Guid rootMapUid, params IRight[] requiredRights)
        {
            using (SecurityDBDataContext dataContext = new SecurityDBDataContext(Connection))
            {
                var accessibleGroups = from securableObject in dataContext.GroupAssociations
                                       where securableObject.SecurableContextId == SecurableContextId && securableObject.SecurableParentUid == domainUid && securableObject.SecurableObjectUid == rootMapUid && securableObject.Group.GroupSPID != null
                                       select securableObject.Group;

                Dictionary <int, Group> sortedGroups = accessibleGroups.ToDictionary(x => x.GroupSPID.Value);

                foreach (SPRoleAssignment roleAssignment in Web.RoleAssignments)
                {
                    SPGroup group = roleAssignment.Member as SPGroup;

                    /// Check that we're actually looking at a group, that this group contains the current user, and that this group is on the list of accessible groups.
                    if (group != null && group.ContainsCurrentUser)
                    {
                        /// Do a check that this group actually has the required right.
                        foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                        {
                            IRole role = null;

                            switch (roleDefinition.Name)
                            {
                            case GlymaSecurityManagerRoleName:
                                /// This user is a Glyma Security Manager, they have access to everything.
                                return(true);

                            case GlymaProjectManagerRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaProjectManagerRole;
                                break;

                            case GlymaMapManagerRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapManagerRole;
                                break;

                            case GlymaMapAuthorRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                                break;

                            case GlymaMapReaderRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                                break;

                            case OldGlymaMapAuthorRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                                break;

                            case OldGlymaMapReaderRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                                break;

                            default:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                                break;
                            }

                            if (sortedGroups.ContainsKey(group.ID))
                            {
                                if (role.HasRights(requiredRights))
                                {
                                    return(true);
                                }
                            }
                        }
                    }
                }

                return(false);
            }
        }
Ejemplo n.º 37
0
        public Dictionary <string, SPRoleType> AddBasicSecurityGroups(SPWeb ew, string safeTitle, SPUser owner, SPListItem eI)
        {
            ew.AllowUnsafeUpdates = true;
            Dictionary <string, SPRoleType> pNewGroups = new Dictionary <string, SPRoleType>();

            string[] grps     = new[] { "Owner", "Member", "Visitor" };
            SPGroup  ownerGrp = null;
            //SPListItem eI = ew.Lists[base.ListUid].GetItemById(base.ItemID);
            var spUInfoList = ew.Site.RootWeb.Lists["User Information List"];

            foreach (string grp in grps)
            {
                string finalName = string.Empty;
                try
                {
                    if (eI.HasUniqueRoleAssignments)
                    {
                        var raColl = eI.RoleAssignments;
                        var groupAlreadyCreated = (from SPRoleAssignment roleAssignment in raColl
                                                   where roleAssignment.Member.Name.Contains(grp)
                                                   select roleAssignment.Member.ID).Any();
                        if (groupAlreadyCreated)
                        {
                            continue;
                        }
                    }
                    finalName = CoreFunctions.AddGroup(ew, safeTitle, grp, ew.CurrentUser, ew.CurrentUser, string.Empty);
                    spUInfoList.Items.GetItemById(ew.SiteGroups[finalName].ID).SystemUpdate();
                    ew.Update();
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Unexpected Permission error on AddBasicSecurityGroup: " + ex);
                }

                SPGroup    finalGrp = ew.SiteGroups[finalName];
                SPRoleType rType;
                switch (grp)
                {
                case "Owner":
                    ownerGrp       = finalGrp;
                    rType          = SPRoleType.Administrator;
                    finalGrp.Owner = owner;
                    finalGrp.AddUser(owner);
                    finalGrp.AllowMembersEditMembership = true;
                    finalGrp.Update();
                    ew.Update();
                    break;

                default:
                    rType          = SPRoleType.Reader;
                    finalGrp.Owner = ownerGrp;
                    finalGrp.Update();
                    ew.Update();
                    break;
                }
                Thread.Sleep(500);
                //AddNewItemLvlPerm(eI, ew, rType, finalGrp);
                pNewGroups.Add(finalGrp.Name, rType);
            }
            return(pNewGroups);
        }
Ejemplo n.º 38
0
        private bool setPermissions(SPItemEventProperties properties, bool isAdd)
        {
            if (!properties.List.Fields.ContainsFieldWithInternalName("Permissions"))
            {
                return(false);
            }
            string curProps  = "";
            string newProps  = "";
            bool   sendEmail = false;

            try
            {
                SPFieldUserValue uv     = null;
                SPFieldUserValue uv_new = null;
                if (isAdd)
                {
                    uv = new SPFieldUserValue(properties.Web, properties.AfterProperties["SharePointAccount"].ToString());
                }
                else
                {
                    uv = new SPFieldUserValue(properties.Web, properties.ListItem["SharePointAccount"].ToString());

                    if (properties.AfterProperties["SharePointAccount"] != null)
                    {
                        uv_new = new SPFieldUserValue(properties.Web, properties.AfterProperties["SharePointAccount"].ToString());
                    }
                }

                SPUser u = uv.User;
                if (u == null)
                {
                    u = uv.User;
                    if (u == null)
                    {
                        u = properties.Web.EnsureUser(uv.LookupValue);
                    }
                }
                SPUser u_new = null;
                if (uv_new != null)
                {
                    u_new = uv_new.User;
                    if (u_new == null)
                    {
                        u_new = properties.Web.EnsureUser(uv_new.LookupValue);
                    }
                }

                // semicolon causes issues in list cleanup and potentially in other modules.
                if ((isAdd && u.Name.Contains(";")) || (!isAdd && u_new != null && u_new.Name.Contains(";")))
                {
                    throw new InvalidOperationException("Semicolon is not allowed for AD username.");
                }

                try
                {
                    curProps = properties.ListItem["Permissions"].ToString().Trim();
                }
                catch { }

                try
                {
                    newProps = properties.AfterProperties["Permissions"].ToString();
                }
                catch { return(false); }

                ArrayList arr = new ArrayList(newProps.Split(','));

                var webGroups = APITeam.GetWebGroups(properties.Web);

                foreach (SPGroup group in webGroups)
                {
                    if (arr.Contains(group.ID.ToString()))
                    {
                        try
                        {
                            group.AddUser(u);
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            group.RemoveUser(u);
                        }
                        catch { }
                    }
                }


                if (!String.IsNullOrEmpty(newProps) && String.IsNullOrEmpty(curProps))
                {
                    sendEmail = true;
                }

                try
                {
                    string perms = "";
                    foreach (SPGroup wGroup in webGroups)
                    {
                        try
                        {
                            SPGroup g = u.Groups.GetByID(wGroup.ID);
                            if (g != null && arr.Contains(g.ID.ToString(CultureInfo.InvariantCulture)))
                            {
                                perms += ", " + wGroup.Name;
                            }
                        }
                        catch { }
                    }

                    properties.AfterProperties["Permissions"] = perms.Trim(", ".ToCharArray());
                }
                catch { }
            }
            catch (InvalidOperationException ex)
            {
                throw ex;
            }
            catch { }

            return(sendEmail);
        }
        private void renderPage()
        {
            // OK, so now we're finally in a position to load up the values of the page fields:

            SourceDocIcon.AlternateText = "Icon of document being publishing out.";
            SourceDocIcon.ImageUrl      = WBUtils.DocumentIcon32(sourceDocAsItem.Url);

            TitleField.Text = sourceFile.Title;

            ReadOnlyNameField.Text = sourceDocAsItem.Name;
            NameField.Text         = sourceDocAsItem.Name;
            OriginalFileName.Text  = sourceDocAsItem.WBxGetColumnAsString(WorkBox.COLUMN_NAME__ORIGINAL_FILENAME);

            DocumentFileNamingConvention.Text = documentRecordsType.DocumentNamingConvention.Replace("<", "&lt;").Replace(">", "&gt;");

            RecordsTypeUIControlValue.Value     = documentRecordsType.UIControlValue;
            PickRecordsTypeButton.OnClientClick = "WorkBoxFramework_pickANewRecordsType(WorkBoxFramework_PublishDoc_pickedANewRecordsType, '" + documentRecordsType.UIControlValue + "'); return false;";
            RecordsType.Text = documentRecordsType.FullPath.Replace("/", " / ");


            WBTermCollection <WBTerm> functionalAreas = sourceDocAsItem.WBxGetMultiTermColumn <WBTerm>(functionalAreasTaxonomy, WorkBox.COLUMN_NAME__FUNCTIONAL_AREA);

            functionalAreaFieldIsEditable = documentRecordsType.IsFunctionalAreaEditable;
            if (functionalAreaFieldIsEditable)
            {
                functionalAreasTaxonomy.InitialiseTaxonomyControl(FunctionalAreaField, WorkBox.COLUMN_NAME__FUNCTIONAL_AREA, false, false, this);

                String functionalAreaValue = functionalAreas.UIControlValue;
                if (functionalAreaValue.Contains(";"))
                {
                    string[] allFunctionalValues = functionalAreaValue.Split(';');
                    functionalAreaValue = allFunctionalValues[0];
                }

                FunctionalAreaField.Text = functionalAreaValue;
            }
            else
            {
                ReadOnlyFunctionalAreaField.Text = functionalAreas.Names();
            }

            bool    userCanPublishToPublic = false;
            SPGroup publishersGroup        = WorkBox.OwningTeam.PublishersGroup(SPContext.Current.Site);

            if (publishersGroup != null)
            {
                if (publishersGroup.ContainsCurrentUser)
                {
                    userCanPublishToPublic = true;
                }
            }

            String selectedZone = WBRecordsType.PROTECTIVE_ZONE__PROTECTED;

            if (userCanPublishToPublic)
            {
                if (destinationType.Equals(WorkBox.PUBLISHING_OUT_DESTINATION_TYPE__PUBLIC_WEB_SITE))
                {
                    WBLogging.Generic.Verbose("In PUBLIC: The destination type was: " + destinationType);
                    selectedZone = WBRecordsType.PROTECTIVE_ZONE__PUBLIC;
                }
                else if (destinationType.Equals(WorkBox.PUBLISHING_OUT_DESTINATION_TYPE__PUBLIC_EXTRANET))
                {
                    WBLogging.Generic.Verbose("In PUBLIC EXTRANET: The destination type was: " + destinationType);
                    selectedZone = WBRecordsType.PROTECTIVE_ZONE__PUBLIC_EXTRANET;
                }
                else
                {
                    WBLogging.Generic.Verbose("The destination type was: " + destinationType);
                    selectedZone = WBRecordsType.PROTECTIVE_ZONE__PROTECTED;
                }
            }
            else
            {
                selectedZone = WBRecordsType.PROTECTIVE_ZONE__PROTECTED;
            }

            List <String> protectiveZoneList = new List <String>();

            protectiveZoneList.Add(selectedZone);

            ProtectiveZone.DataSource = protectiveZoneList;
            ProtectiveZone.DataBind();

            ProtectiveZone.SelectedValue = selectedZone;


            if (showSubjectTags)
            {
                if (documentRecordsType.IsDocumentSubjectTagsRequired)
                {
                    SubjectTagsTitle.Text = "Subject Tags" + WBConstant.REQUIRED_ASTERISK;
                }
                else
                {
                    SubjectTagsTitle.Text = "Subject Tags (optional)";
                }
                SubjectTagsDescription.Text = documentRecordsType.DocumentSubjectTagsDescription;

                subjectTagsTaxonomy.InitialiseTaxonomyControl(SubjectTagsField, WorkBox.COLUMN_NAME__SUBJECT_TAGS, true, true, this);
                WBTermCollection <WBTerm> subjectTags = sourceDocAsItem.WBxGetMultiTermColumn <WBTerm>(subjectTagsTaxonomy, WorkBox.COLUMN_NAME__SUBJECT_TAGS);
                SubjectTagsField.Text = subjectTags.WBxToString();
            }


            if (showReferenceID)
            {
                if (documentRecordsType.IsDocumentReferenceIDRequired)
                {
                    ReferenceIDTitle.Text = "Reference ID" + WBConstant.REQUIRED_ASTERISK;
                }
                else
                {
                    ReferenceIDTitle.Text = "Reference ID (optional)";
                }
                ReferenceIDDescription.Text = documentRecordsType.DocumentReferenceIDDescription;
                ReferenceID.Text            = sourceDocAsItem.WBxGetColumnAsString(WorkBox.COLUMN_NAME__REFERENCE_ID);
            }

            if (showReferenceDate)
            {
                if (documentRecordsType.IsDocumentReferenceDateRequired)
                {
                    ReferenceDateTitle.Text = "Reference Date" + WBConstant.REQUIRED_ASTERISK;
                }
                else
                {
                    ReferenceDateTitle.Text = "Reference Date (optional)";
                }
                ReferenceDateDescription.Text = documentRecordsType.DocumentReferenceDateDescription;
                if (sourceDocAsItem.WBxColumnHasValue(WorkBox.COLUMN_NAME__REFERENCE_DATE))
                {
                    ReferenceDate.SelectedDate = (DateTime)sourceDocAsItem[WorkBox.COLUMN_NAME__REFERENCE_DATE];
                }
                else
                {
                    ReferenceDate.SelectedDate = DateTime.Now;
                }
            }

            if (showSeriesTag)
            {
                if (documentRecordsType.IsDocumentSeriesTagRequired)
                {
                    SeriesTagTitle.Text = "Series Tag" + WBConstant.REQUIRED_ASTERISK;
                }
                else
                {
                    SeriesTagTitle.Text = "Series Tag (optional)";
                }
                SeriesTagDescription.Text = documentRecordsType.DocumentSeriesTagDescription;

                SeriesTagDropDownList.DataSource     = GetSeriesTagDataSource(documentRecordsType.DocumentSeriesTagParentTerm(seriesTagsTaxonomy));
                SeriesTagDropDownList.DataTextField  = "SeriesTagTermName";
                SeriesTagDropDownList.DataValueField = "SeriesTagTermUIControlValue";
                SeriesTagDropDownList.DataBind();

                if (sourceDocAsItem.WBxColumnHasValue(WorkBox.COLUMN_NAME__SERIES_TAG))
                {
                    SeriesTagDropDownList.SelectedValue = sourceDocAsItem.WBxGetSingleTermColumn <WBTerm>(seriesTagsTaxonomy, WorkBox.COLUMN_NAME__SERIES_TAG).UIControlValue;
                }
            }

            if (showScanDate)
            {
                if (documentRecordsType.IsDocumentScanDateRequired)
                {
                    ScanDateTitle.Text = "Scan Date" + WBConstant.REQUIRED_ASTERISK;
                }
                else
                {
                    ScanDateTitle.Text = "Scan Date (optional)";
                }
                ScanDateDescription.Text = documentRecordsType.DocumentScanDateDescription;
                if (sourceDocAsItem.WBxColumnHasValue(WorkBox.COLUMN_NAME__SCAN_DATE))
                {
                    ScanDate.SelectedDate = (DateTime)sourceDocAsItem[WorkBox.COLUMN_NAME__SCAN_DATE];
                }
            }

            teamsTaxonomy.InitialiseTaxonomyControl(OwningTeamField, WorkBox.COLUMN_NAME__OWNING_TEAM, false);
            TaxonomyFieldValue owningTeamValue = sourceDocAsItem[WorkBox.COLUMN_NAME__OWNING_TEAM] as TaxonomyFieldValue;

            OwningTeamField.Text = owningTeamValue.WBxUIControlValue();

            teamsTaxonomy.InitialiseTaxonomyControl(InvolvedTeamsField, WorkBox.COLUMN_NAME__INVOLVED_TEAMS, true);
            TaxonomyFieldValueCollection involvedTeamsValues = sourceDocAsItem[WorkBox.COLUMN_NAME__INVOLVED_TEAMS] as TaxonomyFieldValueCollection;

            InvolvedTeamsField.Text = involvedTeamsValues.WBxUIControlValue();


            if (functionalAreaFieldIsEditable)
            {
                FunctionalAreaField.Focus();
            }
            else
            {
                PickRecordsTypeButton.Focus();
            }
        }
 protected void add_user(SPGroup group, string user_account)
 {
     SPUser user = group.ParentWeb.EnsureUser(user_account);
     group.AddUser(user);
 }
Ejemplo n.º 41
0
        private void AssignGroupsToTasks(int projectId, int pubType, ProjectDataSet projectDataSet)
        {
            SPGroup addMemGrp   = null;
            SPGroup addVisitGrp = null;

            try
            {
                mySiteToPublish.AllowUnsafeUpdates = true;
                var projectCenterList = mySiteToPublish.Lists[ProjectCenter];
                var pcItem            = projectCenterList.GetItemById(projectId);

                var projAssignTo = !string.IsNullOrWhiteSpace(Convert.ToString(pcItem[AssignedTo]))
                    ? Convert.ToString(pcItem[AssignedTo])
                    : string.Empty;

                if (pcItem?.HasUniqueRoleAssignments == true)
                {
                    foreach (SPRoleAssignment role in pcItem.RoleAssignments)
                    {
                        try
                        {
                            if (role.Member is SPGroup)
                            {
                                var tempGrp = (SPGroup)role.Member;

                                if (tempGrp.Name.Contains(Member))
                                {
                                    addMemGrp = tempGrp;
                                }

                                if (tempGrp.Name.Contains(Visitor))
                                {
                                    addVisitGrp = tempGrp;
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            Trace.WriteLine(exception);
                        }
                    }

                    var projAssignToBuilder = new StringBuilder(projAssignTo);

                    foreach (ProjectDataSet.ProjectResourceRow projectResourceRow in projectDataSet.ProjectResource)
                    {
                        try
                        {
                            if (!projectResourceRow.IsWRES_ACCOUNTNull())
                            {
                                var email = string.Empty;

                                try
                                {
                                    email = projectResourceRow.WRES_EMAIL;
                                }
                                catch (Exception exception)
                                {
                                    Trace.WriteLine(exception);
                                }

                                var assignRes = from assgRow in projectDataSet.Assignment.AsEnumerable()
                                                where assgRow.Field <Guid>(ResourceUid) == projectResourceRow.RES_UID
                                                select assgRow;

                                if (assignRes.Any())
                                {
                                    addMemGrp.AddUser(projectResourceRow.WRES_ACCOUNT, email, projectResourceRow.RES_NAME, string.Empty);
                                }
                                else
                                {
                                    addVisitGrp.AddUser(projectResourceRow.WRES_ACCOUNT, email, projectResourceRow.RES_NAME, string.Empty);
                                }

                                if (!projAssignToBuilder.ToString().Contains(
                                        $";#{mySiteToPublish.AllUsers[projectResourceRow.WRES_ACCOUNT].ID};#{getResourceName(projectResourceRow.RES_UID, projectDataSet)}"))
                                {
                                    projAssignToBuilder.Append($";#{mySiteToPublish.AllUsers[projectResourceRow.WRES_ACCOUNT].ID};#{getResourceName(projectResourceRow.RES_UID, projectDataSet)}");
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            Trace.WriteLine(exception);
                        }
                    }

                    addVisitGrp.Update();
                    addMemGrp.Update();
                    pcItem[AssignedTo] = projAssignToBuilder.ToString();
                    pcItem.Update();
                }
            }
            catch (Exception exception)
            {
                myLog.WriteEntry($"Error in AssignGroupsToTasks {exception.Message}{exception.StackTrace}", EventLogEntryType.Error, 305);
            }
        }
Ejemplo n.º 42
0
 private List<string> getEmailAddressesFromGroup(SPGroup group)
 {
     List<string> addresses = new List<string>();
     foreach (SPUser user in group.Users)
     {
         addresses.Add(user.Email);
     }
     return addresses;
 }
Ejemplo n.º 43
0
        public IEnumerable <Guid> IsAuthorised(Guid?domainUid, IEnumerable <Guid> rootMapUids, params IRight[] requiredRights)
        {
            using (SecurityDBDataContext dataContext = new SecurityDBDataContext(Connection))
            {
                List <Guid> authorisedObjects = new List <Guid>();

                /// Only get the securable objects for the securable context ID we have access and the domain ID we were provided.
                var accessibleGroupAssociations = from securableObject in dataContext.GroupAssociations
                                                  where securableObject.SecurableContextId == SecurableContextId// && securableObject.SecurableParentUid == domainUid && securableObject.Group.GroupSPID != null
                                                  select securableObject;

                //foreach (Guid rootMapUid in rootMapUids)
                //{
                //    accessibleGroupAssociations = from securableObject in accessibleGroupAssociations
                //                                  where securableObject.SecurableObjectUid == rootMapUid
                //                                  select securableObject;
                //}

                /// Only get the securable objects for the root map IDs we were supplied with.
                //var accessibleAndRelevantGroupAssociations = from securableObject in accessibleGroupAssociations
                //                                             where rootMapUids.Any(x => x == securableObject.SecurableObjectUid)
                //                                             select securableObject;

                Dictionary <int, List <Guid> > organisedGroupAssociations = new Dictionary <int, List <Guid> >();

                foreach (var groupAssociation in accessibleGroupAssociations)
                {
                    if (groupAssociation.Group.GroupSPID == null)
                    {
                        continue;
                    }

                    List <Guid> groupAssociations;

                    if (!organisedGroupAssociations.ContainsKey(groupAssociation.Group.GroupSPID.Value))
                    {
                        groupAssociations = new List <Guid>();
                        organisedGroupAssociations[groupAssociation.Group.GroupSPID.Value] = groupAssociations;
                    }
                    else
                    {
                        groupAssociations = organisedGroupAssociations[groupAssociation.Group.GroupSPID.Value];
                    }

                    if (groupAssociation.SecurableObjectUid != null)
                    {
                        groupAssociations.Add(groupAssociation.SecurableObjectUid.Value);
                    }
                }

                List <Guid> accessibleObjects = new List <Guid>();

                foreach (SPRoleAssignment roleAssignment in Web.RoleAssignments)
                {
                    SPGroup group = roleAssignment.Member as SPGroup;

                    /// Check that we're actually looking at a group, and that this group is on the list of accessible groups, and that this group contains the current user.
                    if (group != null && group.ContainsCurrentUser)
                    {
                        /// Do a check that this group actually has the required right.
                        foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                        {
                            IRole role = null;

                            switch (roleDefinition.Name)
                            {
                            case GlymaSecurityManagerRoleName:
                                /// This user is a Glyma Security Manager, they have access to everything.
                                return(rootMapUids);

                            case GlymaProjectManagerRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaProjectManagerRole;
                                break;

                            case GlymaMapManagerRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapManagerRole;
                                break;

                            case GlymaMapAuthorRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                                break;

                            case GlymaMapReaderRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                                break;

                            case OldGlymaMapAuthorRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                                break;

                            case OldGlymaMapReaderRoleName:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                                break;

                            default:
                                role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                                break;
                            }

                            if (organisedGroupAssociations.ContainsKey(group.ID))
                            {
                                if (role.HasRights(requiredRights))
                                {
                                    accessibleObjects.AddRange(organisedGroupAssociations[group.ID]);
                                }
                            }
                        }
                    }
                }

                return(accessibleObjects.ToArray());

                //Dictionary<Guid, SecurityPair> sortedGroups = accessibleGroups.ToDictionary(x => x.SecurableObjectUid.Value);

                //foreach (SPRoleAssignment roleAssignment in Web.RoleAssignments)
                //{
                //    SPGroup group = roleAssignment.Member as SPGroup;

                //    /// Check that we're actually looking at a group, that this group contains the current user, and that this group is on the list of accessible groups.
                //    if (group != null && group.ContainsCurrentUser && sortedGroups.ContainsKey(group.ID))
                //    {
                //        /// Do a check that this group actually has the required right.
                //        foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                //        {
                //            IRole role = null;

                //            switch (roleDefinition.Name)
                //            {
                //                case GlymaSecurityManagerRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaSecurityManagerRole;
                //                    break;

                //                case GlymaProjectManagerRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaProjectManagerRole;
                //                    break;

                //                case GlymaMapManagerRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapManagerRole;
                //                    break;

                //                case GlymaMapAuthorRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                //                    break;

                //                case GlymaMapReaderRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                //                    break;

                //                case OldGlymaMapAuthorRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapAuthorRole;
                //                    break;

                //                case OldGlymaMapReaderRoleName:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                //                    break;

                //                default:
                //                    role = SPGlymaRoleFactory.GetInstance(SecurableContextId.Value).GlymaMapReaderRole;
                //                    break;
                //            }

                //            if (role.HasRights(requiredRights))
                //            {
                //            }
                //        }
                //    }
                //}

                //return false;
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Метод возвращает необходимые состояния кнопок для карточки ЗТ
        /// </summary>
        /// <param name="Item">Текущий Item</param>
        /// <param name="State">Текущий статус карточки</param>
        /// <returns></returns>
        private static AccessData GetRequestAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies)
        {
            AccessData result = new AccessData();

            bool IsExpert = Group.Name == GlobalConstants.Groups.Expert;

            bool InCompany = Companies.Any(Company => Item[GlobalConstants.Request_Fields.CompanyTitle].ToString().Contains(Company));

            bool Responsible = new SPFieldUserValue(Web, Item[GlobalConstants.Request_Fields.Responsible].ToString()).User.ID == Web.CurrentUser.ID;

            bool InMailingList = new SPFieldUserValueCollection(Web, Item[GlobalConstants.Request_Fields.MailingList].ToString()).Any(User => User.User.ID == Web.CurrentUser.ID);

            bool AuditorOrAdministrator = Group.Name == GlobalConstants.Groups.Administrator || Group.Name == GlobalConstants.Groups.Auditor;

            //
            //Нужно доделать доступность кнопок в зависимости от дополнительных параметров, как-то : указана ли компания, какой текущий статус карточки и тд тп
            //
            //                                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            return result;
        }
Ejemplo n.º 45
0
 /// <summary>
 ///   Adds the specified users to the group.
 /// </summary>
 /// <param name = "group"></param>
 /// <param name = "users"></param>
 public static void AddUsersToGroup(SPGroup group, params SPUser[] users)
 {
     foreach (var user in users)
     {
         group.AddUser(user);
     }
     group.Update();
 }
Ejemplo n.º 46
0
        public static void ProvisionWebStructure(this SPWeb web, WebDefinitionCollection subsites)
        {
            foreach (var site in subsites)
            {
                var existed = web.Webs.Cast <SPWeb>().Where(p => p.Url.Contains(site.Url)).FirstOrDefault();

                if (existed != null && !site.Overwrite)
                {
                    continue;
                }
                if (existed != null && site.Overwrite)
                {
                    DeleteSite(existed);
                }

                var newSite = web.AddSite(site.Url.Trim(), site.Name.Trim(), site.Template.Trim());
                if (newSite == null)
                {
                    continue;
                }
                //Provision Lists
                //Provision Features
                foreach (var feature in site.Features)
                {
                    newSite.Features.Add(feature.Guid);
                    //newSite.Update();
                }

                //BreakRoleInheritance
                if (site.BreakRoleInheritance)
                {
                    try
                    {
                        newSite.AllowUnsafeUpdates = true;

                        if (!newSite.HasUniqueRoleAssignments)
                        {
                            newSite.BreakRoleInheritance(false);
                        }

                        //create group
                        string groupOwners = site.Name.Trim() + " Owners";
                        newSite.CreateNewGroup(groupOwners, "Use this group to grant people full control permissions to the SharePoint site: " + site.Name.Trim(), SPRoleType.Administrator);

                        string groupMembers = site.Name.Trim() + " Members";
                        newSite.CreateNewGroup(groupMembers, "Use this group to grant people contribute permissions to the SharePoint site: " + site.Name.Trim(), SPRoleType.Contributor);

                        string groupVisitors = site.Name.Trim() + " Visitors";
                        newSite.CreateNewGroup(groupVisitors, "Use this group to grant people read permissions to the SharePoint site: " + site.Name.Trim(), SPRoleType.Reader);

                        newSite.Update();

                        Utility.ChangeSPGroupOwnerBySPGroup(newSite, groupOwners, groupOwners);
                        Utility.ChangeSPGroupOwnerBySPGroup(newSite, groupMembers, groupOwners);
                        Utility.ChangeSPGroupOwnerBySPGroup(newSite, groupVisitors, groupOwners);

                        SPUser authenUsers = newSite.EnsureUser("NT AUTHORITY\\authenticated users");
                        if (authenUsers != null)
                        {
                            SPGroup spGrp = newSite.Groups[groupVisitors];
                            if (spGrp != null)
                            {
                                spGrp.AddUser(authenUsers);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        newSite.AllowUnsafeUpdates = false;
                    }
                }


                //provision Top Navigation Bar
                try
                {
                    newSite.AllowUnsafeUpdates = true;

                    SPNavigationNodeCollection topnav = newSite.Navigation.TopNavigationBar;

                    //clear all
                    for (int i = topnav.Count - 1; i >= 0; i--)
                    {
                        topnav.Delete(topnav[i]);
                    }

                    string           linkTitle = newSite.Title;
                    SPNavigationNode node      = new SPNavigationNode(linkTitle, newSite.ServerRelativeUrl);
                    node = topnav.AddAsLast(node);

                    SPWeb            rootWeb       = web.Site.RootWeb;
                    string           linkRootTitle = rootWeb.Title;
                    SPNavigationNode nodeRoot      = new SPNavigationNode(linkRootTitle, rootWeb.ServerRelativeUrl);
                    nodeRoot = topnav.AddAsFirst(nodeRoot);

                    //AddParentNode(newSite, topnav);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    newSite.AllowUnsafeUpdates = false;
                }

                if (site.SubSites.Count > 0)
                {
                    newSite.ProvisionWebStructure(site.SubSites);
                }
            }
        }
Ejemplo n.º 47
0
 private bool IsValidUser(SPUser spUser, SPGroup spGroup)
 {
     return spUser.Groups.Cast<SPGroup>()
       .Any(g => g.ID == spGroup.ID);
 }
Ejemplo n.º 48
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb  web    = SPContext.Current.Web;
            string resUrl = "";

            web.Site.CatchAccessDeniedException = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb aweb = site.OpenWeb(web.ID))
                    {
                        resUrl = CoreFunctions.getConfigSetting(aweb, "EPMLiveResourceURL", true, false);
                    }
                }
            });

            //bool canManageAGroup = false;
            SPListItem oLi      = null;
            SPList     oList    = null;
            bool       bUseTeam = false;

            Guid listid = Guid.Empty;
            int  itemid = 0;

            try
            {
                listid = new Guid(Request["listid"]);
                itemid = int.Parse(Request["id"]);

                oList = web.Lists[listid];
                oLi   = oList.GetItemById(itemid);
                GridGanttSettings gSettings = new GridGanttSettings(oList);
                bUseTeam = gSettings.BuildTeam;
            }
            catch (Exception)
            {
                try
                {
                    APITeam.VerifyProjectTeamWorkspace(web, out itemid, out listid);
                    if (itemid > 0 && listid != Guid.Empty)
                    {
                        try
                        {
                            while (!web.IsRootWeb) //Inherit | Open
                            {
                                if (web.IsRootWeb)
                                {
                                    break;
                                }
                                web = web.ParentWeb;
                            }

                            oList = web.Lists[listid];
                            GridGanttSettings gSettings = ListCommands.GetGridGanttSettings(oList);
                            bUseTeam = gSettings.BuildTeam;
                            oLi      = oList.GetItemById(itemid);
                        }
                        catch { }
                    }
                }
                catch { }
            }

            if (bUseTeam)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite tSite = new SPSite(web.Site.ID))
                    {
                        using (SPWeb tWeb = tSite.OpenWeb(web.ID))
                        {
                            SPListItem spListItem = null;
                            SPList tList          = tWeb.Lists[listid];
                            try
                            {
                                spListItem = tList.GetItemById(itemid);
                            }
                            catch (ArgumentException ex)
                            {
                                throw new SPException("The associated project does not exist or has been deleted.", ex);
                            }
                            web.Site.CatchAccessDeniedException = false;

                            foreach (SPRoleAssignment assn in spListItem.RoleAssignments)
                            {
                                if (assn.Member.GetType() == typeof(Microsoft.SharePoint.SPGroup))
                                {
                                    try
                                    {
                                        SPGroup group = web.SiteGroups.GetByID(assn.Member.ID);

                                        if (group.CanCurrentUserEditMembership)
                                        {
                                            string[] sG = group.Name.Split(' ');
                                            if (sG[sG.Length - 1] == "Member")
                                            {
                                                sDefaultGroup = group.ID.ToString();
                                            }

                                            bCanEditTeam = "true";
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                });
            }
            else
            {
                foreach (SPGroup g in web.Groups)
                {
                    string[] sG = g.Name.Split(' ');
                    if (sG[sG.Length - 1] == "Member")
                    {
                        sDefaultGroup = g.ID.ToString();
                    }

                    if (g.CanCurrentUserEditMembership)
                    {
                        bCanEditTeam = "true";
                    }
                }
            }

            if (itemid > 0 && listid != Guid.Empty && PfeData.ConnectionProvider.AllowDatabaseConnections(web))
            {
                // collect pfe database project id for processing in UI part
                var repository = new PfeData.ProjectRepository();
                projectIdInPfe = repository.FindProjectId(web, listid, itemid);
            }

            if (web.Features[new Guid("84520a2b-8e2b-4ada-8f48-60b138923d01")] == null && !bUseTeam)
            {
                sDisable = "_spBodyOnLoadFunctionNames.push(\"ShowDisable\");";
                SPList teamlist = web.Lists["Team"];
                //if(web.DoesUserHavePermissions(SPBasePermissions.ManagePermissions))
                //{
                //    bCanEditTeam = "true";
                //}
            }
            else
            {
                try
                {
                    using (SPSite rsite = new SPSite(resUrl))
                    {
                        using (SPWeb rweb = rsite.OpenWeb())
                        {
                            SPList list = rweb.Lists["Resources"];
                            //DataTable dtTemp = list.Items.GetDataTable();
                            bCanAccessResourcePool = "true";
                            if (list.DoesUserHavePermissions(SPBasePermissions.AddListItems))
                            {
                                bCanAddResource = "true";
                                sNewResUrl      = list.Forms[PAGETYPE.PAGE_NEWFORM].ServerRelativeUrl;
                            }
                        }
                    }
                }
                catch { }

                XmlDocument doc = new XmlDocument();
                doc.LoadXml("<Grid/>");



                if (bUseTeam)
                {
                    try
                    {
                        if (oLi.DoesUserHavePermissions(SPBasePermissions.EditListItems))
                        {
                            bCanEditTeam = "true";
                        }

                        XmlAttribute attr = doc.CreateAttribute("WebId");
                        attr.Value = Convert.ToString(web.ID);
                        doc.FirstChild.Attributes.Append(attr);

                        attr       = doc.CreateAttribute("ListId");
                        attr.Value = Convert.ToString(listid);
                        doc.FirstChild.Attributes.Append(attr);

                        attr       = doc.CreateAttribute("ItemId");
                        attr.Value = Convert.ToString(itemid);
                        doc.FirstChild.Attributes.Append(attr);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    SPList teamlist = web.Lists.TryGetList("Team");

                    if (teamlist == null)
                    {
                        web.AllowUnsafeUpdates = true;
                        web.Lists.Add("Team", "Use this list to manage your project team", SPListTemplateType.GenericList);
                        teamlist = web.Lists.TryGetList("Team");
                        try
                        {
                            teamlist.Fields.Add("ResID", SPFieldType.Number, false);
                            teamlist.Update();
                        }
                        catch { }
                    }
                }

                sLayoutParam = HttpUtility.HtmlEncode(doc.OuterXml);

                if (bCanEditTeam == "true")
                {
                    sResPool = Properties.Resources.txtBuildTeamResPool.Replace("#LayoutParam#", sLayoutParam).Replace("#DataParam#", sLayoutParam);
                    sResGrid = @"TreeGrid(   { 
                    Layout:{ Url:""../../_vti_bin/WorkEngine.asmx"",Timeout:0, Method:""Soap"",Function:""Execute"",Namespace:""workengine.com"",Param:{Function:""GetResourceGridLayout"",Dataxml:""" + sLayoutParam + @""" } } ,
                    Data:{ Url:""../../_vti_bin/WorkEngine.asmx"",Timeout:0, Method:""Soap"",Function:""Execute"",Namespace:""workengine.com"",Param:{Function:""GetResourceGridData"",Dataxml:""" + sLayoutParam + @""" } }, 
                    Debug:"""",SuppressMessage:""3""
                    }, 
	                ""divResPool"" );"    ;
                }
            }

            sUserInfoList = web.SiteUserInfoList.ID.ToString().ToUpper();

            if (Request["isDlg"] == "1")
            {
                sClose = "SP.SOD.execute('SP.UI.Dialog.js', 'SP.UI.ModalDialog.commonModalDialogClose', SP.UI.DialogResult.OK, '');";
            }
            else
            {
                if (String.IsNullOrEmpty(Request["Source"]))
                {
                    sClose = "location.href='" + ((web.ServerRelativeUrl == "/") ? "" : web.ServerRelativeUrl) + "'";
                }
                else
                {
                    sClose = "location.href='" + Request["Source"] + "'";
                }
            }
        }
Ejemplo n.º 49
0
 /// <summary>
 /// This method send approver email notifications
 /// </summary>
 /// <param name="To">string</param>
 /// <param name="From">string</param>
 private void SendApproverEmail(SPGroup ApproverGroup,string From)
 {
     string _toAddress=string.Empty;
     List<string> addresses=getEmailAddressesFromGroup(ApproverGroup);
     foreach (string address in addresses)
     {
         if (_toAddress != "")
         {
             _toAddress = _toAddress + address;
         }
         else
         {
             _toAddress = address;
         }
     }
     //SendApproverEmail.To = _toAddress;
     //SendApproverEmail.From = From;
     //SendApproverEmail.Subject = "Document approval request - CLIF";
     //SendApproverEmail.Body = "<p><strong>Document approval request</strong></p>" +
     //                 "Please review this document <a href=\"" +
     //                    workflowProperties.SiteUrl + workflowProperties.Item.File.ServerRelativeUrl +
     //                  "\">" + workflowProperties.Item.File.Name + "</a>";
 }
        protected override void InternalProcessRecord()
        {
            bool test = false;
            ShouldProcessReason reason;

            if (!base.ShouldProcess(null, null, null, out reason))
            {
                if (reason == ShouldProcessReason.WhatIf)
                {
                    test = true;
                }
            }
            if (test)
            {
                Logger.Verbose = true;
            }

            SPGroup group = null;

            if (Web != null)
            {
                using (SPWeb web = Web.Read())
                {
                    group = Identity.Read(web);
                }
            }
            else
            {
                group = Identity.Read();
            }

            if (group == null)
            {
                WriteError(new PSArgumentException("The specified group could not be found."), ErrorCategory.InvalidArgument, null);
                SkipProcessCurrentRecord();
                return;
            }

            SPRoleAssignment ra = group.ParentWeb.RoleAssignments.GetAssignmentByPrincipal(group);

            foreach (string permission in Permission)
            {
                SPRoleDefinition rd = null;
                try
                {
                    rd = group.ParentWeb.RoleDefinitions[permission];
                }
                catch (SPException)
                {
                    throw new SPException(string.Format("Permission level \"{0}\" cannot be found.", permission));
                }
                if (!ra.RoleDefinitionBindings.Contains(rd))
                {
                    ra.RoleDefinitionBindings.Add(rd);
                }
            }
            if (!test)
            {
                ra.Update();
                group.Update();
            }
        }