/// <summary> The try assert. </summary>
        /// <param name="context"> The context. </param>
        /// <param name="entity"> The entity. </param>
        /// <param name="right"> The right. </param>
        /// <param name="dependencies"> The dependencies. </param>
        /// <param name="map"> The map. </param>
        /// <param name="useScope">Pass true if you need to determine web file permissions throught parent web page</param>
        /// <returns> The <see cref="bool"/>. </returns>
        public virtual bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right,
                                      CrmEntityCacheDependencyTrace dependencies, ContentMap map, bool useScope)
        {
            entity.AssertEntityName("adx_webpage");
            this.AddDependencies(
                dependencies,
                entity,
                new[] { "adx_webrole", "adx_webrole_contact", "adx_webrole_account", "adx_webpageaccesscontrolrule" });

            WebPageNode page;

            if (!map.TryGetValue(entity, out page))
            {
                // the website context is missing data
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Failed to lookup the web page '{0}' ({1}).", entity.GetAttributeValue <string>("adx_name"), entity.Id));

                return(false);
            }

            dependencies.IsCacheable = false;

            return(this.TryAssert(page, right, useScope));
        }
Exemplo n.º 2
0
            protected override bool TestWebFile(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
            {
                return(_contentMapProvider.Using(map =>
                {
                    WebFileNode file;

                    if (map.TryGetValue(entity, out file) && file.Parent != null)
                    {
                        return !file.Parent.IsReference &&
                        TestFileWebPage(context, file.Parent.ToEntity(), right, dependencies, map);
                    }

                    return base.TestWebFile(context, entity, right, dependencies);
                }));
            }
Exemplo n.º 3
0
        public override bool TryAssert(OrganizationServiceContext context, Entity currentEvent, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            currentEvent.AssertEntityName("adx_event");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on event ({1}).", right, currentEvent.Id));

            dependencies.AddEntityDependency(currentEvent);
            dependencies.AddEntitySetDependency("adx_webrole");
            dependencies.AddEntitySetDependency("adx_eventaccesspermission");

            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

                // If roles are not enabled on the site, grant Read, deny Change.
                return(right == CrmEntityRight.Read);
            }

            // Windows Live ID Server decided to return null for an unauthenticated user's name
            // A null username, however, breaks the Roles.GetRolesForUser() because it expects an empty string.
            var currentUsername = (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
                                ? HttpContext.Current.User.Identity.Name ?? string.Empty
                                : string.Empty;


            var userRoles = Roles.GetRolesForUser(currentUsername);

            // Get all rules applicable to the event, grouping equivalent rules. (Rules that
            // target the same event and confer the same right are equivalent.)
            var ruleGroupings = from rule in GetRulesApplicableToEvent(context, currentEvent, dependencies)
                                let eventReference = rule.GetAttributeValue <EntityReference>("adx_eventid")
                                                     let rightOption = rule.GetAttributeValue <OptionSetValue>("adx_right")
                                                                       where eventReference != null && rightOption != null
                                                                       group rule by new { EventID = eventReference.Id, Right = rightOption.Value } into ruleGrouping
            select ruleGrouping;

            var websiteReference = currentEvent.GetAttributeValue <EntityReference>("adx_websiteid");

            foreach (var ruleGrouping in ruleGroupings)
            {
                // Collect the names of all the roles that apply to this rule grouping
                var ruleGroupingRoles = ruleGrouping.SelectMany(rule => rule.GetRelatedEntities(context, "adx_eventaccesspermission_webrole").ToList()
                                                                .Where(role => BelongsToWebsite(websiteReference, role))
                                                                .Select(role => role.GetAttributeValue <string>("adx_name")));

                // Determine if the user belongs to any of the roles that apply to this rule grouping
                var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

                // If the user belongs to one of the roles...
                if (userIsInAnyRoleForThisRule)
                {
                    if (ruleGrouping.Key.Right != RestrictRead)
                    {
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.EventID));

                        // ...the user has all rights.
                        return(true);
                    }
                }
                // If the user does not belong to any of the roles, the rule restricts read, and the desired right
                // is read...
                else if (ruleGrouping.Key.Right == RestrictRead && right == CrmEntityRight.Read)
                {
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on event ({0}). Permission denied.", ruleGrouping.Key.EventID));

                    // ...the user has no right.
                    return(false);
                }
            }

            //Get all membership type applicable to the event
            var membershipTypes = currentEvent.GetRelatedEntities(context, "adx_event_membershiptype");

            //If the event has membership types, specific user has right to access it. If there is no membership type, every user has right.
            if (membershipTypes.Any())
            {
                var contact = PortalContext.Current.User;

                //Anonymouse user has no right.
                if (contact == null)
                {
                    return(false);
                }

                foreach (var membershipType in membershipTypes)
                {
                    if (contact.GetRelatedEntities(context, "adx_membership_contact").Any(m => m.GetAttributeValue <EntityReference>("adx_membershiptypeid") == membershipType.ToEntityReference()))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            // If none of the above rules apply, assert on parent webpage.
            var parentWebPage = currentEvent.GetRelatedEntity(context, "adx_webpage_event");

            // If there is no parent web page, grant Read by default, and deny Change.
            if (parentWebPage == null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and event. Allowing Read, but not Change.");

                return(right == CrmEntityRight.Read);
            }

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and event. Asserting right on parent web page.");

            return(_webPageAccessControlProvider.TryAssert(context, parentWebPage, right, dependencies));
        }
 /// <summary> The add dependencies. </summary>
 /// <param name="dependencies"> The dependencies. </param>
 /// <param name="entity"> The entity. </param>
 /// <param name="attributes"> The attributes. </param>
 protected void AddDependencies(CrmEntityCacheDependencyTrace dependencies, Entity entity, string[] attributes)
 {
     attributes.ForEach(dependencies.AddEntitySetDependency);
     dependencies.AddEntityDependency(entity);
 }
 /// <summary> The try assert. </summary>
 /// <param name="context"> The context. </param>
 /// <param name="entity"> The entity. </param>
 /// <param name="right"> The right. </param>
 /// <param name="dependencies"> The dependencies. </param>
 /// <returns> The assertion. </returns>
 public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
 {
     return(this.ContentMapProvider.Using(map => this.TryAssert(context, entity, right, dependencies, map)));
 }
        protected override bool TryAssert(OrganizationServiceContext context, Entity forum, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            forum.AssertEntityName("adx_communityforum");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on forum '{1}' ({2}).", right, forum.GetAttributeValue <string>("adx_name"), forum.Id));

            this.AddDependencies(dependencies, forum, new [] { "adx_webrole", "adx_communityforumaccesspermission" });

            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

                // If roles are not enabled on the site, grant Read, deny Change.
                return(right == CrmEntityRight.Read);
            }

            var userRoles = this.GetUserRoles();

            // Get all rules applicable to the forum, grouping equivalent rules. (Rules that
            // target the same forum and confer the same right are equivalent.)
            var ruleGroupings = from rule in this.GetRulesApplicableToForum(forum, dependencies, map)
                                let forumReference = rule.GetAttributeValue <EntityReference>("adx_forumid")
                                                     let rightOption = rule.GetAttributeValue <OptionSetValue>("adx_right")
                                                                       where forumReference != null && rightOption != null
                                                                       group rule by new { ForumID = forumReference.Id, Right = ParseRightOption(rightOption.Value) } into ruleGrouping
            select ruleGrouping;

            var websiteReference = forum.GetAttributeValue <EntityReference>("adx_websiteid");

            // Order the rule groupings so that all GrantChange rules will be evaluated first.
            ruleGroupings = ruleGroupings.OrderByDescending(grouping => grouping.Key.Right, new RightOptionComparer());

            foreach (var ruleGrouping in ruleGroupings)
            {
                // Collect the names of all the roles that apply to this rule grouping
                var ruleGroupingRoles = ruleGrouping.SelectMany(rule => GetRolesForGrouping(map, rule, websiteReference));

                // Determine if the user belongs to any of the roles that apply to this rule grouping
                var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

                // If the user belongs to one of the roles...
                if (userIsInAnyRoleForThisRule)
                {
                    // ...and the rule is GrantChange...
                    if (ruleGrouping.Key.Right == RightOption.GrantChange)
                    {
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.ForumID));

                        // ...the user has all rights.
                        return(true);
                    }
                }
                // If the user does not belong to any of the roles, the rule restricts read, and the desired right
                // is read...
                else if (ruleGrouping.Key.Right == RightOption.RestrictRead && right == CrmEntityRight.Read)
                {
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on forum ({0}). Permission denied.", ruleGrouping.Key.ForumID));

                    // ...the user has no right.
                    return(false);
                }
            }

            // If none of the above rules apply, assert on parent webpage.
            var         parentWebPage = forum.GetAttributeValue <EntityReference>("adx_parentpageid");
            WebPageNode parentPageNode;

            map.TryGetValue(parentWebPage, out parentPageNode);

            // If there is no parent web page, grant Read by default, and deny Change.
            if (parentWebPage == null || parentPageNode == null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. Allowing Read, but not Change.");

                return(right == CrmEntityRight.Read);
            }

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. Asserting right on parent web page.");

            return(this._webPageAccessControlProvider.TryAssert(context, parentPageNode.ToEntity(), right, dependencies));
        }
Exemplo n.º 7
0
        public override bool TryAssert(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            entity.ThrowOnNull("entity");

            if (entity.LogicalName == "adx_issueforum")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_issueforum ({1}).", right, entity.Id));

                dependencies.AddEntityDependency(entity);

                dependencies.AddEntitySetDependency("adx_webrole");

                return(right == CrmEntityRight.Change
                                        ? UserInRole("adx_webrole_issueforum_write", false, serviceContext, entity, dependencies)
                                        : UserInRole("adx_webrole_issueforum_read", true, serviceContext, entity, dependencies) ||
                       UserInRole("adx_webrole_issueforum_write", false, serviceContext, entity, dependencies));
            }

            if (entity.LogicalName == "adx_issue")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_issue ({1}).", right, entity.Id));

                dependencies.AddEntityDependency(entity);

                var issueForum = entity.GetRelatedEntity(serviceContext, new Relationship("adx_issueforum_issue"));

                if (issueForum == null)
                {
                    return(false);
                }

                var approved = entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false);

                // If the right being asserted is Read, and the issue is approved, assert whether the issue forum is readable.
                if (right == CrmEntityRight.Read && approved)
                {
                    return(TryAssert(serviceContext, issueForum, right, dependencies));
                }

                return(TryAssert(serviceContext, issueForum, CrmEntityRight.Change, dependencies));
            }

            if (entity.LogicalName == "adx_issuecomment")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_issuecomment ({1}).", right, entity.Id));

                dependencies.AddEntityDependency(entity);

                var issue = entity.GetRelatedEntity(serviceContext, new Relationship("adx_issue_issuecomment"));

                if (issue == null)
                {
                    return(false);
                }

                var approved = entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false);

                // If the right being asserted is Read, and the comment is approved, assert whether the issue is readable.
                if (right == CrmEntityRight.Read && approved)
                {
                    return(TryAssert(serviceContext, issue, right, dependencies));
                }

                return(TryAssert(serviceContext, issue, CrmEntityRight.Change, dependencies));
            }

            if (entity.LogicalName == "adx_issuevote")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_issuevote ({1}).", entity.Id));

                dependencies.AddEntityDependency(entity);

                var issue = entity.GetRelatedEntity(serviceContext, new Relationship("adx_issue_issuevote"));

                return(issue != null && TryAssert(serviceContext, issue, right, dependencies));
            }

            throw new NotSupportedException("Entities of type {0} are not supported by this provider.".FormatWith(entity.LogicalName));
        }
        protected override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            switch (entity.LogicalName)
            {
            case "adx_weblink":
                WebLinkNode link;
                if (map.TryGetValue(entity, out link))
                {
                    return(TryAssert(link) || UserCanPreview(context, entity));
                }
                break;

            case "adx_webpage":
                WebPageNode page;
                if (map.TryGetValue(entity, out page))
                {
                    return(TryAssert(page.PublishingState) || UserCanPreview(context, entity));
                }
                break;

            case "adx_weblinkset":
                WebLinkSetNode linkset;
                if (map.TryGetValue(entity, out linkset))
                {
                    return(TryAssert(linkset.PublishingState) || UserCanPreview(context, entity));
                }
                break;

            case "adx_webfile":
                WebFileNode file;
                if (map.TryGetValue(entity, out file))
                {
                    return(TryAssert(file.PublishingState) || UserCanPreview(context, entity));
                }
                break;

            case "adx_shortcut":
                ShortcutNode shortcut;
                if (map.TryGetValue(entity, out shortcut))
                {
                    return(TryAssert(shortcut) || UserCanPreview(context, entity));
                }
                break;

            case "adx_communityforum":
                ForumNode forum;
                if (map.TryGetValue(entity, out forum))
                {
                    return(TryAssert(forum.PublishingState) || UserCanPreview(context, entity));
                }
                break;
            }

            return(this.TryAssert(context, entity, right, dependencies));
        }
Exemplo n.º 9
0
        private bool TryAssertIdea(OrganizationServiceContext serviceContext, Entity ideaEntity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            var ideaForumReference = ideaEntity.GetAttributeValue <EntityReference>("adx_ideaforumid");

            IdeaForumNode ideaForumNode;

            if (!map.TryGetValue(ideaForumReference, out ideaForumNode))
            {
                return(false);
            }
            var ideaForum = ideaForumNode.AttachTo(serviceContext);

            if (ideaForum == null)
            {
                return(false);
            }

            var approved = ideaEntity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false);

            // If the right being asserted is Read, and the idea is approved, assert whether the idea forum is readable.
            if (right == CrmEntityRight.Read && approved)
            {
                return(this.TryAssert(serviceContext, ideaForum, right, dependencies, map));
            }

            return(this.TryAssert(serviceContext, ideaForum, CrmEntityRight.Change, dependencies, map));
        }
        public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            if (entity == null || right == CrmEntityRight.Change)
            {
                return(false);
            }

            dependencies.AddEntityDependency(entity);
            dependencies.AddEntitySetDependency("adx_webrole");
            dependencies.AddEntitySetDependency("adx_webrole_contact");
            dependencies.AddEntitySetDependency("adx_webrole_account");
            dependencies.AddEntitySetDependency("adx_websiteaccess");

            var entityName = entity.LogicalName;

            if (entityName == "adx_idea")
            {
                return(entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false));
            }

            if (entityName == "adx_ideacomment")
            {
                return(entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false));
            }

            EntityReference publishingStateReference = null;
            Entity          entityPublishingState    = null;

            switch (entityName)
            {
            case "adx_communityforumpost":
                publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                break;

            case "adx_ad":
                publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                break;

            // legacy entities
            case "adx_event":
                entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_event");
                break;

            case "adx_eventschedule":
                entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_eventschedule");
                break;

            case "adx_eventspeaker":
                entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_eventspeaker");
                break;

            case "adx_eventsponsor":
                entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_eventsponsor");
                break;

            case "adx_survey":
                entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_survey");
                break;
            }

            if (publishingStateReference != null)
            {
                entityPublishingState = context.RetrieveSingle(
                    "adx_publishingstate",
                    new[] { "adx_isvisible" },
                    new Condition("adx_publishingstateid", ConditionOperator.Equal, publishingStateReference.Id));
            }

            if (entityPublishingState == null)
            {
                return(true);
            }

            dependencies.AddEntityDependency(entityPublishingState);

            if (entityPublishingState.GetAttributeValue <bool?>("adx_isvisible").GetValueOrDefault())
            {
                return(true);
            }

            return(UserCanPreview(context, entityPublishingState));
        }
            public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
            {
                if (entity == null || right == CrmEntityRight.Change)
                {
                    return(false);
                }

                dependencies.AddEntityDependency(entity);
                dependencies.AddEntitySetDependency("adx_webrole");
                dependencies.AddEntitySetDependency("adx_webrole_contact");
                dependencies.AddEntitySetDependency("adx_webrole_account");
                dependencies.AddEntitySetDependency("adx_websiteaccess");

                var entityName = entity.LogicalName;

                // Weblinks require some special handling.
                if (entityName == "adx_weblink")
                {
                    var weblinkPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_weblink");

                    // If a weblink has a publishing state, and that state is not visible, state access is
                    // denied (unless the user can preview).
                    if (weblinkPublishingState != null && !weblinkPublishingState.GetAttributeValue <bool?>("adx_isvisible").GetValueOrDefault())
                    {
                        dependencies.AddEntityDependency(weblinkPublishingState);

                        return(UserCanPreview(context, entity));
                    }

                    var weblinkPage = context.RetrieveRelatedEntity(entity, "adx_webpage_weblink");

                    // If a weblink has an associated page, and page validation is not disabled, return the
                    // result of assertion on that page.
                    if (weblinkPage != null && !entity.GetAttributeValue <bool?>("adx_disablepagevalidation").GetValueOrDefault(false))
                    {
                        return(TryAssert(context, weblinkPage, right, dependencies));
                    }
                }

                if (entityName == "adx_idea")
                {
                    return(entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false));
                }

                if (entityName == "adx_ideacomment")
                {
                    return(entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false));
                }

                EntityReference publishingStateReference = null;
                Entity          entityPublishingState    = null;

                switch (entityName)
                {
                case "adx_webpage":
                    publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                    break;

                case "adx_weblinkset":
                    publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                    break;

                case "adx_webfile":
                    publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                    break;

                case "adx_communityforum":
                    publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                    break;

                case "adx_communityforumpost":
                    publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                    break;

                case "adx_ad":
                    publishingStateReference = entity.GetAttributeValue <EntityReference>("adx_publishingstateid");
                    break;

                // legacy entities
                case "adx_event":
                    entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_event");
                    break;

                case "adx_eventschedule":
                    entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_eventschedule");
                    break;

                case "adx_eventspeaker":
                    entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_eventspeaker");
                    break;

                case "adx_eventsponsor":
                    entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_eventsponsor");
                    break;

                case "adx_survey":
                    entityPublishingState = context.RetrieveRelatedEntity(entity, "adx_publishingstate_survey");
                    break;
                }

                if (publishingStateReference != null)
                {
                    entityPublishingState = context.RetrieveSingle(
                        "adx_publishingstate",
                        new[] { "adx_isvisible" },
                        new Condition("adx_publishingstateid", ConditionOperator.Equal, publishingStateReference.Id));
                }

                if (entityPublishingState == null)
                {
                    return(true);
                }

                dependencies.AddEntityDependency(entityPublishingState);

                if (entityPublishingState.GetAttributeValue <bool?>("adx_isvisible").GetValueOrDefault())
                {
                    return(true);
                }

                return(UserCanPreview(context, entityPublishingState));
            }
        /// <summary>
        /// Test whether or not an Entity's published dates are visible in the current context.
        /// </summary>
        /// <param name="context">OrganizationServiceContext</param>
        /// <param name="entity">CRM Entity</param>
        /// <param name="right">Entity Right</param>
        /// <param name="dependencies">Cache Dependency Trace</param>
        /// <param name="map">Content Map</param>
        /// <returns></returns>
        protected override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            if (entity == null || right == CrmEntityRight.Change)
            {
                return(false);
            }

            dependencies.AddEntityDependency(entity);
            dependencies.AddEntitySetDependency("adx_webrole");
            dependencies.AddEntitySetDependency("adx_websiteaccess");

            var entityName = entity.LogicalName;

            var releaseDate = DateTime.MinValue;
            var expiryDate  = DateTime.MaxValue;

            if (entityName == "adx_webpage" ||
                entityName == "adx_webfile" ||
                entityName == "adx_event" ||
                entityName == "adx_survey" ||
                entityName == "adx_ad")
            {
                releaseDate = entity.GetAttributeValue <DateTime?>("adx_releasedate").GetValueOrDefault(DateTime.MinValue);
                expiryDate  = entity.GetAttributeValue <DateTime?>("adx_expirationdate").GetValueOrDefault(DateTime.MaxValue);
            }
            else if (entityName == "adx_weblink")
            {
                if (!entity.GetAttributeValue <bool?>("adx_disablepagevalidation").GetValueOrDefault(false))
                {
                    var pageReference = entity.GetAttributeValue <EntityReference>("adx_pageid");

                    if (pageReference != null)
                    {
                        WebPageNode rootPage;
                        if (map.TryGetValue(pageReference, out rootPage))
                        {
                            var weblinkWebPage = HttpContext.Current.GetContextLanguageInfo().FindLanguageSpecificWebPageNode(rootPage, false);

                            if (weblinkWebPage != null)
                            {
                                return(TryAssert(context, weblinkWebPage.ToEntity(), right, dependencies));
                            }
                        }
                    }
                }

                return(true);
            }
            else if (entityName == "adx_shortcut")
            {
                if (!entity.GetAttributeValue <bool?>("adx_disabletargetvalidation").GetValueOrDefault(false))
                {
                    var pageReference    = entity.GetAttributeValue <EntityReference>("adx_webpageid");
                    var webFileReference = entity.GetAttributeValue <EntityReference>("adx_webfileid");

                    if (pageReference != null)
                    {
                        WebPageNode rootPage;
                        if (map.TryGetValue(pageReference, out rootPage))
                        {
                            var shortcutWebPage = HttpContext.Current.GetContextLanguageInfo().FindLanguageSpecificWebPageNode(rootPage, false);

                            if (shortcutWebPage != null)
                            {
                                return(TryAssert(context, shortcutWebPage.ToEntity(), right, dependencies));
                            }
                        }
                    }
                    else if (webFileReference != null)
                    {
                        WebFileNode webFile;
                        if (map.TryGetValue(webFileReference, out webFile))
                        {
                            return(TryAssert(context, webFile.ToEntity(), right, dependencies));
                        }
                    }
                }

                var parentPageReference = entity.GetAttributeValue <EntityReference>("adx_parentpage_webpageid");

                if (parentPageReference != null)
                {
                    WebPageNode rootPage;
                    if (map.TryGetValue(parentPageReference, out rootPage))
                    {
                        var parentPage = HttpContext.Current.GetContextLanguageInfo().FindLanguageSpecificWebPageNode(rootPage, false);

                        return(TryAssert(context, parentPage.ToEntity(), right, dependencies));
                    }
                }

                return(true);
            }

            return(UserCanPreview(context, entity) || InnerTryAssert(releaseDate, expiryDate));
        }
        protected override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            var entityName = entity.LogicalName;

            this.AddDependencies(
                dependencies,
                entity,
                new[] { "adx_webrole", "adx_webrole_contact", "adx_webrole_account", "adx_websiteaccess" });

            if (entityName == "adx_weblink")
            {
                // Change permission only comes through adx_manageweblinksets on the website.
                if (right == CrmEntityRight.Change)
                {
                    return(TryAssertRightProperty(context, "adx_manageweblinksets", dependencies));
                }

                WebLinkNode link;

                if (map.TryGetValue(entity, out link))
                {
                    dependencies.IsCacheable = false;

                    if (link.DisablePageValidation.GetValueOrDefault())
                    {
                        return(true);
                    }

                    return(link.WebPage == null || link.WebPage.IsReference || (_webPageAccessControlSecurityProvider != null && _webPageAccessControlSecurityProvider.TryAssert(link.WebPage, right, false)));
                }
            }

            WebsiteNode site;

            if (!map.TryGetValue(_website, out site))
            {
                return(false);
            }

            if (entityName == "adx_contentsnippet")
            {
                return(right == CrmEntityRight.Read || TryAssertRightProperty(site, rule => rule.ManageContentSnippets));
            }

            if (entityName == "adx_weblinkset")
            {
                return(right == CrmEntityRight.Read || TryAssertRightProperty(site, rule => rule.ManageWebLinkSets));
            }

            if (entityName == "adx_sitemarker")
            {
                return(right == CrmEntityRight.Read || TryAssertRightProperty(site, rule => rule.ManageSiteMarkers));
            }

            return(false);
        }
        public bool TryAssertRightProperty(OrganizationServiceContext context, string rightPropertyName, CrmEntityCacheDependencyTrace dependencies)
        {
            // If Roles are not enabled on the site, deny permission.
            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, "Roles are not enabled for this application. Permission denied.");

                return(false);
            }

            dependencies.AddEntitySetDependency("adx_webrole");
            dependencies.AddEntitySetDependency("adx_webrole_contact");
            dependencies.AddEntitySetDependency("adx_webrole_account");

            dependencies.AddEntityDependency(_website);

            var userRoles = this.GetUserRoles();

            if (!userRoles.Any())
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No roles were found for the current user. Permission denied.");

                return(false);
            }

            var websiteaccessFetch =
                new Fetch
            {
                Entity = new FetchEntity("adx_websiteaccess", new [] { "adx_manageweblinksets", "adx_previewunpublishedentities" })
                {
                    Filters = new[]
                    {
                        new Filter
                        {
                            Conditions = new[]
                            {
                                new Condition(
                                    "adx_websiteid",
                                    ConditionOperator.Equal,
                                    this._website.Id),
                            }
                        }
                    }
                }
            };

            var rules = context.RetrieveMultiple(websiteaccessFetch).Entities;

            // If no access permissions are defined for this site, deny permission.
            if (!rules.Any())
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No website access permission rules were found for the current website. Permission denied.");

                return(false);
            }

            dependencies.AddEntityDependencies(rules);

            foreach (var rule in rules)
            {
                var ruleRoles = context.RetrieveRelatedEntities(rule, "adx_websiteaccess_webrole", new [] { "adx_name" }).Entities;

                if (ruleRoles == null)
                {
                    continue;
                }

                var ruleRoleNames = ruleRoles.Select(role => role.GetAttributeValue <string>("adx_name"));

                var roleIntersection = ruleRoleNames.Intersect(userRoles, StringComparer.InvariantCulture);

                // If the user is in any of the roles associated with the permission rule, and
                // the rightsPredicate evaluates to true for the given rule, grant permission.
                if (roleIntersection.Any() && rule.GetAttributeValue <bool?>(rightPropertyName).GetValueOrDefault(false))
                {
                    return(true);
                }
            }

            // If no permission rules meet the necessary conditions, deny permission.
            return(false);
        }
        private bool TryAssertBlog(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            var pageReference = entity.GetAttributeValue <EntityReference>("adx_parentpageid");

            if (pageReference == null)
            {
                return(false);
            }

            var parentPage = serviceContext.RetrieveSingle(
                "adx_webpage",
                new[] { "adx_name" },
                new Condition("adx_webpageid", ConditionOperator.Equal, pageReference.Id));

            if (right == CrmEntityRight.Read)
            {
                return(parentPage != null && this.WebPageSecurityProvider.TryAssert(serviceContext, parentPage, right, dependencies));
            }

            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, "Roles are not enabled for this application. Denying Change.");

                return(false);
            }

            IEnumerable <Entity> authorRoles = new List <Entity>();
            EntityNode           blogNode;

            if (!map.TryGetValue(entity, out blogNode))
            {
                return(false);
            }

            if (blogNode is BlogNode)
            {
                authorRoles = ((BlogNode)blogNode).WebRoles.Select(wr => wr.ToEntity());
            }

            if (!authorRoles.Any())
            {
                return(false);
            }

            dependencies.AddEntityDependencies(authorRoles);

            var userRoles = this.GetUserRoles();

            return(authorRoles.Select(e => e.GetAttributeValue <string>("adx_name")).Intersect(userRoles, StringComparer.InvariantCulture).Any() ||
                   (parentPage != null && this.WebPageSecurityProvider.TryAssert(serviceContext, parentPage, right, dependencies)));
        }
Exemplo n.º 16
0
        private bool TryAssertIdeaComment(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            var idea = entity.GetRelatedEntity(serviceContext, new Relationship("adx_idea_ideacomment"));

            if (idea == null)
            {
                return(false);
            }

            var approved = entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false);

            // If the right being asserted is Read, and the comment is approved, assert whether the idea is readable.
            if (right == CrmEntityRight.Read && approved)
            {
                return(this.TryAssert(serviceContext, idea, right, dependencies));
            }

            return(this.TryAssert(serviceContext, idea, CrmEntityRight.Change, dependencies, map));
        }
Exemplo n.º 17
0
        private bool UserInRole(string roleRelationship, bool defaultIfNoRoles, OrganizationServiceContext serviceContext, Entity entity, CrmEntityCacheDependencyTrace dependencies)
        {
            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Roles are not enabled for this application. Returning {0}.", defaultIfNoRoles));

                return(defaultIfNoRoles);
            }

            var website = entity.GetAttributeValue <EntityReference>("adx_websiteid");

            if (website == null)
            {
                return(false);
            }

            var roles = entity.GetRelatedEntities(serviceContext, new Relationship(roleRelationship))
                        .Where(e => Equals(e.GetAttributeValue <EntityReference>("adx_websiteid"), website))
                        .ToArray();

            if (!roles.Any())
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Read is not restricted to any particular roles. Returning {0}.", defaultIfNoRoles));

                return(defaultIfNoRoles);
            }

            dependencies.AddEntityDependencies(roles);

            // Windows Live ID Server decided to return null for an unauthenticated user's name
            // A null username, however, breaks the Roles.GetRolesForUser() because it expects an empty string.
            var currentUsername = HttpContext.Current.User != null && HttpContext.Current.User.Identity != null
                                ? HttpContext.Current.User.Identity.Name ?? string.Empty
                                : string.Empty;

            var userRoles = Roles.GetRolesForUser(currentUsername);

            return(roles.Select(e => e.GetAttributeValue <string>("adx_name")).Intersect(userRoles, StringComparer.InvariantCulture).Any());
        }
Exemplo n.º 18
0
        private bool TryAssertIdeaVote(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            var idea = entity.GetRelatedEntity(serviceContext, new Relationship("adx_idea_ideavote"));

            return(idea != null && this.TryAssert(serviceContext, idea, right, dependencies, map));
        }
 /// <summary> The try assert. </summary>
 /// <param name="context"> The context. </param>
 /// <param name="entity"> The entity. </param>
 /// <param name="right"> The right. </param>
 /// <param name="dependencies"> The dependencies. </param>
 /// <param name="map"> The map. </param>
 /// <returns> The <see cref="bool"/>. </returns>
 protected override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
 {
     return(this.TryAssert(context, entity, right, dependencies, map, false));
 }
Exemplo n.º 20
0
        protected override bool TryAssert(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            entity.ThrowOnNull("entity");
            dependencies.AddEntityDependency(entity);
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on {1} ""{2}"" ({3}).", right, entity.LogicalName, entity.GetAttributeValue <string>("adx_name"), entity.Id));

            switch (entity.LogicalName)
            {
            case "adx_ideaforum":
                dependencies.AddEntitySetDependency("adx_webrole");
                return(this.TryAssertIdeaForum(entity, right, dependencies, map));

            case "adx_idea":
                return(this.TryAssertIdea(serviceContext, entity, right, dependencies, map));

            case "adx_ideacomment":
                return(this.TryAssertIdeaComment(serviceContext, entity, right, dependencies, map));

            case "adx_ideavote":
                return(this.TryAssertIdeaVote(serviceContext, entity, right, dependencies, map));

            default:
                throw new NotSupportedException("Entities of type {0} are not supported by this provider.".FormatWith(entity.LogicalName));
            }
        }
        protected virtual IEnumerable <Entity> GetRulesApplicableToForum(Entity forum, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            forum.AssertEntityName("adx_communityforum");

            var rules = new List <Entity>();

            ForumNode currentForumNode;

            if (map.TryGetValue(forum, out currentForumNode))
            {
                var rulesForCurrentForum = currentForumNode.ForumAccessPermissions.Where(fr => fr.StateCode == 0);
                rules.AddRange(rulesForCurrentForum.Select(r => r.ToEntity()));
            }

            dependencies.AddEntityDependencies(rules);

            return(rules);
        }
Exemplo n.º 22
0
        private bool UserInRole(CrmEntityRight right, bool defaultIfNoRoles, Entity ideaForumEntity, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Roles are not enabled for this application. Returning {0}.", defaultIfNoRoles));
                return(defaultIfNoRoles);
            }

            IEnumerable <Entity> roles = new List <Entity>();
            IdeaForumNode        ideaForumNode;

            if (!map.TryGetValue(ideaForumEntity, out ideaForumNode))
            {
                return(false);
            }

            if (right == CrmEntityRight.Read)
            {
                roles = ideaForumNode.WebRolesRead.Select(wr => wr.ToEntity());
            }
            else if (right == CrmEntityRight.Change)
            {
                roles = ideaForumNode.WebRolesWrite.Select(wr => wr.ToEntity());
            }

            if (!roles.Any())
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Read is not restricted to any particular roles. Returning {0}.", defaultIfNoRoles));
                return(defaultIfNoRoles);
            }

            dependencies.AddEntityDependencies(roles);

            var userRoles = this.GetUserRoles();

            return(roles.Select(e => e.GetAttributeValue <string>("adx_name")).Intersect(userRoles, StringComparer.InvariantCulture).Any());
        }
        /// <summary> The try assert. </summary>
        /// <param name="context"> The context. </param>
        /// <param name="entityReference"> The entity reference. </param>
        /// <param name="right"> The right. </param>
        /// <param name="dependencies"> The dependencies. </param>
        /// <returns> The assertion. </returns>
        public bool TryAssert(OrganizationServiceContext context, EntityReference entityReference, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            EntityNode entity = null;

            this.ContentMapProvider.Using(map => map.TryGetValue(entityReference, out entity));

            return(entity != null && this.TryAssert(context, entity.ToEntity(), right, dependencies));
        }
Exemplo n.º 24
0
 private bool TryAssertIdeaForum(Entity ideaForumEntity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
 {
     return(right == CrmEntityRight.Change
                         ? this.UserInRole(CrmEntityRight.Change, false, ideaForumEntity, dependencies, map)
                         : this.UserInRole(CrmEntityRight.Read, true, ideaForumEntity, dependencies, map) ||
            this.UserInRole(CrmEntityRight.Change, false, ideaForumEntity, dependencies, map));
 }
 /// <summary> The try assert. </summary>
 /// <param name="context"> The context. </param>
 /// <param name="entity"> The entity. </param>
 /// <param name="right"> The right. </param>
 /// <param name="dependencies"> The dependencies. </param>
 /// <param name="map"> The map. </param>
 /// <returns> The assertion. </returns>
 protected abstract bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map);
        private bool TryAssertBlogPostComment(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            var blogPostReference = entity.GetAttributeValue <EntityReference>("adx_blogpostid");

            if (blogPostReference == null)
            {
                return(false);
            }

            var blogPost = serviceContext.RetrieveSingle(
                "adx_blogpost",
                new[] { "adx_blogid" },
                new Condition("adx_blogpostid", ConditionOperator.Equal, blogPostReference.Id));

            if (blogPost == null)
            {
                return(false);
            }

            var approved = entity.GetAttributeValue <bool?>("adx_approved").GetValueOrDefault(false);

            return(this.TryAssert(
                       serviceContext,
                       blogPost,
                       (right == CrmEntityRight.Read && approved ? CrmEntityRight.Read : CrmEntityRight.Change),
                       dependencies));
        }
Exemplo n.º 27
0
        protected virtual IEnumerable <Entity> GetRulesApplicableToEvent(OrganizationServiceContext context, Entity crmEvent, CrmEntityCacheDependencyTrace dependencies)
        {
            crmEvent.AssertEntityName("adx_event");

            var rules = new List <Entity>();

            var currentEvent = crmEvent;

            if (currentEvent != null)
            {
                var rulesForCurrentEvent = currentEvent.GetRelatedEntities(context, "adx_event_eventaccesspermission");

                if (rulesForCurrentEvent != null)
                {
                    rules.AddRange(rulesForCurrentEvent);
                }
            }

            dependencies.AddEntityDependencies(rules);

            return(rules);
        }
        protected override bool TryAssert(OrganizationServiceContext serviceContext, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.LogicalName == "adx_blog")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_blog ({1}).", right, entity.Id));

                return(this.TryAssertBlog(serviceContext, entity, right, dependencies, map));
            }

            if (entity.LogicalName == "adx_blogpost")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_blogpost ({1}).", right, entity.Id));
                dependencies.AddEntityDependency(entity);

                return(this.TryAssertBlogPost(serviceContext, entity, right, dependencies));
            }

            if (entity.LogicalName == "adx_blogpostcomment")
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on adx_blogpostcomment ({1}).", right, entity.Id));
                dependencies.AddEntityDependency(entity);

                return(this.TryAssertBlogPostComment(serviceContext, entity, right, dependencies));
            }

            throw new NotSupportedException("Entities of type {0} are not supported by this provider.".FormatWith(entity.LogicalName));
        }
Exemplo n.º 29
0
            public override bool TryAssert(OrganizationServiceContext context, Entity website, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
            {
                if (website == null)
                {
                    return(false);
                }

                var securityProvider = new WebsiteAccessPermissionProvider(website, HttpContext.Current);

                return(securityProvider.TryAssertRightProperty(context, "adx_previewunpublishedentities", dependencies));
            }
Exemplo n.º 30
0
            protected override bool TestShortcutParent(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
            {
                return(_contentMapProvider.Using(map =>
                {
                    ShortcutNode shortcut;

                    if (map.TryGetValue(entity, out shortcut))
                    {
                        return shortcut.Parent != null &&
                        !shortcut.Parent.IsReference &&
                        TestWebPage(context, shortcut.Parent.ToEntity(), right, dependencies);
                    }

                    return base.TestShortcutParent(context, entity, right, dependencies);
                }));
            }