Categories
JavaScript jQuery Php SilverStripe Tutorial

Silverstripe 3 – Per user page access permissions

Most of the times group access in SilverStripe is sufficient for controlling user access, but for this project I had a specific situation where every user needs to have a dedicated page. In order to avoid unnecessary editing and creating groups for each individual user, I decided to extend SiteTree and create a page with per user access control.

So, I’ve created a new page type, since I only needed it for a single page type, but you can extend/decorate SiteTree any way you like.

Let’s get to the code. This goes to mysite/code/FilePage.php

So, let’s break it down a bit:

I’ve created a new variable – CanViewTypeExtended to replace SiteTree’s CanViewType, since I couldn’t find the way to add an option (If you know a way, feel free to drop a line). It replicates SiteTree’s CanViewType with OnlyTheseMembers option added, which is our per user access type.

Then, we have has one ViewerMember, which holds actual user ID for single user (I’ve limited it to one user, since using any more would be a group).

The rest is pretty basic, mostly copied from SiteTree with a bit of additions, getSettingsFields  is a standard function for updating the Settings tab in CMS. There we have first included the JavaScript file, which will be shown later, and is only for decoration – showing and hiding fields based on selection.

Then we have created Member selection field, to pick a member to which the access will be granted, and replicated creating CanViewType field from SiteTree.php with addition of our new OnlyTheseMembers option.

After this is saved, all that is left is to check user permissions in canView() method. Since we don’t use CanViewType any more, but have replaced it with CanViewTypeExtended, the entire function is copied from SiteTree.php, except for the last part which grants the access if current member is our selected member:

if($this->CanViewTypeExtended == ‘OnlyTheseMembers’ && $member && $member->ID == $this->ViewerMemberID)
return true;

So, here’s the remaining js file, which goes to mysite/javascript/CMSMain.EditFormMember.js