Sonata Admin general roles Sonata Admin general roles symfony symfony

Sonata Admin general roles


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

# AppBundle/Security/Handler/MyRoleSecurityHandler.phpnamespace 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.ymlservices:    #...    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.ymlsecurity:    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 classprotected 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.