3
votes

I wanna use the Role Handler security on my Sonata admin dashboard. I work with Symfony 2.3.

In the doc, I have:

Each permission is relative to an admin: if you try to get a list in FooAdmin (declared as sonata.admin.demo.foo service), Sonata will check if the user has the ROLE_SONATA_ADMIN_DEMO_FOO_EDIT role.

As I understand, if I have services such as:

  • sonata.admin.article
  • sonata.admin.user
  • sonata.admin.tag

Then I need to create an edit role, being a list of those 3 elements:

ROLE_SONATA_ADMIN_ARTICLE_EDIT and ROLE_SONATA_ADMIN_USER_EDIT and ROLE_SONATA_ADMIN_TAG_EDIT

But I would rather like to create access more generals, for example, in my case, simply do: ROLE_SONATA_ADMIN_EDIT instead and of a list of three.

Is there a simple way to do this with this bundle?

1

1 Answers

2
votes

You can easily do this by overriding the Sonata\AdminBundle\Security\Handler\RoleSecurityHandler class and getBaseRole method:

# AppBundle/Security/Handler/MyRoleSecurityHandler.php

namespace AppBundle\Security\Handler;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Security\Handler\RoleSecurityHandler;

class MyRoleSecurityHandler extends RoleSecurityHandler
{

   /**
    * {@inheritDoc}
    */
   public function getBaseRole(AdminInterface $admin)
   {
        return 'ROLE_SONATA_ADMIN_%s';
   }
}

overwrites the sonata service related to this class:

# AppBundle/Resources/config/services.yml
services:
    #...

    sonata.admin.security.handler.role:
        class: AppBundle\Security\Handler\MyRoleSecurityHandler
        public: false
        arguments: [@security.context, [ROLE_SUPER_ADMIN]]

remember declare these roles in your hierarchy:

# app/config/security.yml

security:
    role_hierarchy:
        # ...
        ROLE_SONATA_ADMIN_LIST: ~
        ROLE_SONATA_ADMIN_SHOW: ~
        ROLE_SONATA_ADMIN_EDIT: ~
        ROLE_SONATA_ADMIN_DELETE: ~
        # etc.

once you assign these roles to the user, finally you can to check:

# inside of any admin class

protected function configureListFields(ListMapper $listMapper)
{
    if ($this->isGranted('EDIT')) {
       # ...
    }
}

Warning! The previous sonata roles (ROLE_SONATA_ADMIN_ARTICLE_EDIT, ROLE_SONATA_ADMIN_USER_EDIT, etc.) it will no work. So you could also override the class and the corresponding service of sonata-project/user-bundle/Security/EditableRolesBuilder.php to return only the hierarchy of roles.