Common Sonata Administrator Roles
I want to use role handler protection in Sonata admin dashboard. I am working with Symfony 2.3.
In the doc I have:
Each permission belongs to the administrator: if you try to get the list in FooAdmin (declared as service sonata.admin.demo.foo), Sonata will check if the user has a role
ROLE_SONATA_ADMIN_DEMO_FOO_EDIT
.
As I understand it, 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 these three elements:
ROLE_SONATA_ADMIN_ARTICLE_EDIT
and ROLE_SONATA_ADMIN_USER_EDIT
andROLE_SONATA_ADMIN_TAG_EDIT
But I would like to create access to more generals, for example in my case, just do: ROLE_SONATA_ADMIN_EDIT
and a list of three.
Is there an easy way to do this with this package?
You can easily do this by overriding the method Sonata\AdminBundle\Security\Handler\RoleSecurityHandler
and getBaseRole
:
# 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 belonging 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 to 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.
after assigning these roles to the user, finally you can check:
# inside of any admin class
protected function configureListFields(ListMapper $listMapper)
{
if ($this->isGranted('EDIT')) {
# ...
}
}
Attention! Previous sonata roles (ROLE_SONATA_ADMIN_ARTICLE_EDIT, ROLE_SONATA_ADMIN_USER_EDIT, etc.) will not work. Thus, you can also override the class and the corresponding service
sonata-project/user-bundle/Security/EditableRolesBuilder.php
to return only the role hierarchy.