Пример #1
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));
 }
Пример #2
0
        private bool TryAssert(CrmEntityRight right)
        {
            using (var serviceContext = PortalViewContext.CreateServiceContext())
            {
                var attachedEntity = serviceContext.MergeClone(Entity);

                return(PortalViewContext.CreateCrmEntitySecurityProvider().TryAssert(serviceContext, attachedEntity, right));
            }
        }
        private string BuildKey(Entity entity, CrmEntityRight right, string securityContextKey)
        {
            var baseKey = string.Concat(securityContextKey, ":", entity.Id, ":", right);

            IIdentity identity;

            return(TryGetCurrentIdentity(out identity)
                                ? string.Concat(baseKey, ":Identity=", identity.Name)
                : string.Concat(baseKey, ":Anonymous"));
        }
Пример #4
0
        private bool TryAssertSecurity(CrmEntityRight right)
        {
            try
            {
                return(SecurityProvider.TryAssert(ServiceContext, Entity, right));
            }
            catch (InvalidOperationException e)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for entity [{0}:{1}]: {2}", Entity.LogicalName, Entity.Id, e.ToString()));

                return(false);
            }
        }
Пример #5
0
        protected bool TryAssertSecurity(Entity entity, CrmEntityRight right)
        {
            if (!ServiceContext.IsAttached(entity))
            {
                entity = ServiceContext.MergeClone(entity);
            }

            try
            {
                return(SecurityProvider.TryAssert(ServiceContext, entity, right));
            }
            catch (InvalidOperationException e)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for entity [{0}:{1}]: {2}", entity.LogicalName, entity.Id, e.ToString()));

                return(false);
            }
        }
        public CrmEntitySecurityCacheInfo(Entity entity, CrmEntityRight right, string securityContextKey)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.Id == null)
            {
                throw new ArgumentException("Parameter ID must have a value.", "entity");
            }

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

            Key = BuildKey(entity, right, securityContextKey);
        }
Пример #7
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());
        }
Пример #8
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 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);
        /// <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));
        }
Пример #11
0
 private IQueryable <TEntity> FilterBySecurity <TEntity>(OrganizationServiceContext context, IQueryable <TEntity> queryable, CrmEntityRight right) where TEntity : Entity
 {
     return(queryable.ToList().Where(e => HasRight(context, e, right)).AsQueryable());
 }
        /// <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));
        }
Пример #13
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));
            }
        }
Пример #14
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));
        }
Пример #15
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));
        }
        /// <summary> The try assert. </summary>
        /// <param name="page"> The page. </param>
        /// <param name="right"> The right. </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(WebPageNode page, CrmEntityRight right, bool useScope)
        {
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on web page '{1}' ({2}).", right, page.Name, page.Id));

            if (!Roles.Enabled)
            {
                ADXTrace.Instance.TraceError(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);
            }

            // Ignore access control rules for service pages like not found or access denied
            if (right == CrmEntityRight.Read && IsServicePage(page))
            {
                return(true);
            }

            // If the chain of pages from the current page up to the root page contains an inactive page, deny the assertion
            if (IsInactivePath(page))
            {
                return(false);
            }

            var userRoles = this.GetUserRoles();

            // when we use rule scope we're checking permissions for parent page of web file
            //	and we need to check permissions only for one level
            var useInheritance = !useScope;

            // Get all rules applicable to the page and its parent path, grouping equivalent rules. (Rules that
            // target the same web page and confer the same right are equivalent.)
            var ruleGroupings =
                from rule in this.GetRulesApplicableToWebPage(page, useInheritance)
                where rule.WebPage != null && rule.Right != null
                group rule by new { WebPageId = rule.WebPage.Id, Right = ParseRightOption(rule.Right.Value) } into ruleGrouping
            select ruleGrouping;

            // 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 => rule.WebRoles.Where(role => BelongsToWebsite(page.Website, role))
                    .Select(role => role.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)
                {
                    // ...and the rule is GrantChange...
                    if (ruleGrouping.Key.Right == RightOption.GrantChange)
                    {
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on web page ({0}). Permission granted.", ruleGrouping.Key.WebPageId));

                        // ...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)
                {
                    if (useScope && ruleGrouping.Any(rule => rule.Scope.HasValue && (ScopeOption)rule.Scope.Value == ScopeOption.ExcludeDirectChildWebFiles))
                    {
                        // Ignore read restriction for web files where scope is ExcludeDirectChildWebFiles
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Ignoring web page ({0}) read restriction due to ExcludeDirectChildWebFiles", ruleGrouping.Key.WebPageId));
                    }
                    else
                    {
                        if (page.Parent == null && page.PartialUrl == "/")
                        {
                            ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("\"Restrict Read\" right on web page({0}) ({1}).", ruleGrouping.Key.WebPageId, page.Name));
                        }
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on web page ({0}). Permission denied.", ruleGrouping.Key.WebPageId));

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

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and page. Allowing Read, but not Change.");

            // If none of the above rules apply, grant Read by default, and deny Change by default.
            return(right == CrmEntityRight.Read);
        }
 /// <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));
 }
Пример #18
0
        public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            var info = CacheInfoFactory.GetCacheInfo(context, entity, right);

            if (!info.IsCacheable)
            {
                return(UnderlyingProvider.TryAssert(context, entity, right, dependencies));
            }

            // No locking is required here because the Items collection is already per-thread/per-request.
            var cachedValue = HttpContext.Current.Items[info.Key];

            if (cachedValue is bool)
            {
                return((bool)cachedValue);
            }

            var value = UnderlyingProvider.TryAssert(context, entity, right, dependencies);

            // We ignore whether the value is cacheable or not and always cache it at this level, as the result
            // will always be the same per-request.
            HttpContext.Current.Items[info.Key] = value;

            return(value);
        }
Пример #19
0
 private bool HasRight <TEntity>(OrganizationServiceContext context, TEntity entity, CrmEntityRight right) where TEntity : Entity
 {
     return(_securityProvider.TryAssert(context, entity, right));
 }
        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));
        }
        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));
        }
        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));
        }
 /// <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)));
 }
        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)));
        }
Пример #25
0
        public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
        {
            var info = CacheInfoFactory.GetCacheInfo(context, entity, right);

            if (!info.IsCacheable)
            {
                return(UnderlyingProvider.TryAssert(context, entity, right, dependencies));
            }

            Stopwatch stopwatch = null;

            return(ObjectCacheManager.Get(info.Key,
                                          cache =>
            {
                stopwatch = Stopwatch.StartNew();

                var value = UnderlyingProvider.TryAssert(context, entity, right, dependencies);

                stopwatch.Stop();

                return value;
            },
                                          (cache, value) =>
            {
                if (dependencies.IsCacheable)
                {
                    cache.Insert(info.Key, value, dependencies);

                    if (stopwatch != null)
                    {
                        cache.AddCacheItemTelemetry(info.Key, new CacheItemTelemetry {
                            Duration = stopwatch.Elapsed
                        });
                    }
                }
            }));
        }
Пример #26
0
        public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right)
        {
            if (entity == null || entity.Id == Guid.Empty)
            {
                return(false);
            }

            entity.AssertEntityName(_handledEntityNames);

            CrmEntityInactiveInfo inactiveInfo;

            if (CrmEntityInactiveInfo.TryGetInfo(entity.LogicalName, out inactiveInfo) && inactiveInfo.IsInactive(entity))
            {
                return(false);
            }

            var website = context.GetWebsite(entity);

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

            if (right == CrmEntityRight.Read)
            {
                return(true);
            }

            if (HttpContext.Current.User == null ||
                HttpContext.Current.User.Identity == null ||
                HttpContext.Current.User.Identity.Name == null ||
                !HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return(false);
            }

            var roleName = context.GetSiteSettingValueByName(website, SiteSettingName);

            var result = !string.IsNullOrEmpty(roleName) && Roles.IsUserInRole(roleName);

            return(result);
        }
Пример #27
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));
            }
Пример #28
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 virtual bool TryAssertCrmEntityRight(OrganizationServiceContext context, Entity entity, CrmEntityRight right)
        {
            var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName);

            return(securityProvider.TryAssert(context, entity, right));
        }
 private bool TryAssertSecurity(EntityNode node, CrmEntityRight right)
 {
     return(TryAssertSecurity(node.ToEntity(), right));
 }