Custom Permissions Pt II – Using custom permissions with Conditional Renderings In Sitecore

Following on from my previous post on Creating Custom Permissions in Sitecore. I thought I would expand this to show a typical use case a little more. More than once I have had the requirement to show ‘non-logged-in’ users an alternative version of a page (think experts exchange where you have to sign in to see the answer to a question). This by default in Sitecore is not so tricky, but you cannot simply do it by preventing read permissions to an item.

I have chosen to base this functionality on Conditional Renderings as, in Sitecore’s out of the box functionality, it already allows us to hide / change the datasource of pieces of presentation.

The Rule
As Conditional Renderings are based on the Rules engine, we will start here and create ourselves a new rule condition.

We will add our rule to the following path in Sitecore and call it ‘Restricted User’:
/sitecore/system/Settings/Rules/Definitions/Elements/Security

Now set an appropriate message for the user to allow them to understand what the condition does – something like ‘where the current user is restricted’ will do nicely.

The Condition Code

Next, we need to create a condition class. In final implementation, I would use abstraction to allow unit testing and mocking, however, the premise is shown below:

    using Sitecore.Diagnostics;
    using Sitecore.Rules;
    using Sitecore.Rules.Conditions;

    public class RestrictedCondition : WhenCondition  where T : RuleContext
    {
        protected override bool Execute(T ruleContext)
        {
            Assert.ArgumentNotNull(ruleContext, "ruleContext");
            ISitecoreItem sitecoreItem = this.ContentManager.RetrieveCurrent();
            return AuthorizationManager.IsAllowed(Context.Item, AccessRight.FromName("item:restricted"), Context.User); // this should be abstracted and maybe use the datasource too 😀
        }
    }

We then need to set the ‘Type’ field value of our ‘Restricted User’ condition item.

Now use it 😀
You should now see the rule appear whenever you try to use conditional renderings in the ‘Security’ section. It’s that easy 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s