Programmatically testing permissions on pages for a given user/group (Solution)
Permalink
I needed a way to discover whether a given user or group was able to view certain pages. I could not find a solution online. It appears that a lot of the code within the core appears to be hard coded to view permissions only for the current logged in user. This was no use as I was always going to be logged in as Administrator. Anyway, I eventually found this solution and I thought I should share it for others who need to do the same:
I defined this method on a subclass of Page however it can work standalone:
Hope this is helpful to someone
I defined this method on a subclass of Page however it can work standalone:
public function canGuestView() { // We the view page permission... $pk = PagePermissionKey::getByHandle("view_page"); // Regarding the current page (this)... $pk->setPermissionObject($this); // Attempt to get the PermissionAccessObject $pa = $pk->getPermissionAccessObject(); // If it doesn't exist, assume restrictions haven't been defined and grant access (black list approach rather than white list) if ($pa == NULL) return true; // Get the access levels defined for a particular user (including it's groups)... //$accessEntities = $u->getUserAccessEntityObjects(); // Commented as wanted group rather than user // Get the access levels defined only for the "Guest" group, basically anonymous $accessEntities = [GroupPermissionAccessEntity::getOrCreate(Group::getByID(GUEST_GROUP_ID))]; // Test against these permissions return $pa->validateAccessEntities($accessEntities);
Viewing 15 lines of 16 lines. View entire code block.
Hope this is helpful to someone
Perhaps you could cut and paste this into a howto. As you say, documentation about using permissions from code is sparse. Howtos are less likely to get lost with time than forum posts.
Thanks for the tip JohnTheFish. I've submitted my How-To and it is awaiting approval. :-)
I've read the how to. It's basically exactly what i'd need. But if i try to determine if a user has access to a certain page it does not work.
I created a custom group and permitted access to a page via this group. If i get it right the method getUserAccessEntityObjects() does not contain the custom groups and therefore the validation returns false altough the user can access the page. Can anybody confirm this and more important does anybody know a solution?
Best regards
Markus
I created a custom group and permitted access to a page via this group. If i get it right the method getUserAccessEntityObjects() does not contain the custom groups and therefore the validation returns false altough the user can access the page. Can anybody confirm this and more important does anybody know a solution?
Best regards
Markus