Programmatically adding page permissions

Permalink
I am trying to set page permissions programmatically in a package controller and have based this on the docs here https://documentation.concrete5.org/developers/permissions-access-se... . The docs are giving an example for a file object so I'm not sure if it's different for a page? I almost have it but for some reason this code is overwriting every page in the sitemap with the new permissions rather than just the page I need. Not sure what I'm doing wrong?

This is what I have:

use Concrete\Core\Permission\Key\Key as PermissionKey;
use Concrete\Core\Permission\Access\Entity\GroupEntity as GroupPermissionAccessEntity;
use Concrete\Core\User\Group\Group as UserGroup;
// get my page object 
$page = Page::getByID(684);
// override permissions to Manual
$page->setPermissionsToManualOverride();
// remove Guest access
$pk = PermissionKey::getByHandle('view_page');
$pk->setPermissionObject($page);
$pa = $pk->getPermissionAccessObject();
$pe = GroupPermissionAccessEntity::getOrCreate(UserGroup::getByID(GUEST_GROUP_ID));
$pa->removeListItem($pe);
// enable access by a group
$g = UserGroup::getByName('My Custom Group Name');

Blueprint
 
linuxoid replied on at Permalink Best Answer Reply
linuxoid
Hi.

Here's a working code for removing guest access to an Account sub-page and setting permissions for it:
$page = Page::getByPath('/account/my_forum');
if ($page && !$page->isError()) {
    $page->setPermissionsToManualOverride();
    $page->setPermissionsInheritanceToOverride();
    $key = PermissionKey::getByHandle('view_page');
    $key->setPermissionObject($page);
    $access_obj = Access::getByID($key->getPermissionAccessID(), $key);
    $access = $access_obj->duplicate();
    $entity = GroupEntity::getOrCreate($group);
    $access->addListItem($entity, false, PermissionKey::ACCESS_TYPE_INCLUDE);
    $entity = GroupEntity::getOrCreate(Group::getByID(GUEST_GROUP_ID));
    $access->removeListItem($entity);
    $access->save(array('paID' => $access->getPermissionAccessID()));
    $assignment = $key->getPermissionAssignmentObject();
    $assignment->assignPermissionAccess($access);
Blueprint replied on at Permalink Reply
Blueprint
Thanks, that works. A bit different than the offical docs. In case anyone else needs this. You have to use the following as well:
use Concrete\Core\Permission\Key\Key as PermissionKey;
use Concrete\Core\Permission\Access\Entity\GroupEntity;
use Concrete\Core\Permission\Access\Entity\Entity as PermissionAccessEntity;
use Concrete\Core\Permission\Access\Access as PermissionAccess;
use Concrete\Core\User\Group\Group;

and make sure you get your group object too:
$group = Group::getByName('My Group Name');
$entity = GroupEntity::getOrCreate($group);