Search code examples
securitysymfonysonata-adminsonata-user-bundle

Sonata User - Customize admin query with security


I have extended SonataUserBundle and I'd like to customize the Admin query to restrict the list:

class UserAdmin extends BaseUserAdmin
{
// ...
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query->andWhere( 
            $query->expr()->eq($query->getRootAlias().'.company', ':comp')
        );
        $query->setParameter('comp', $securityContext->user->getCompany());
        return $query;
    }
// ...
}

Here, I'm trying to make the user only see users from his company.
But $securityContext is not set.

Can someone tell how to inject the security context into my admin class ?


Solution

  • You have to inject the security context service in your UserAdmin service.

    In order to do that, you have to update the services.yml of your bundle:

    services:
        # ...
        sonata.admin.user:
            class: My\ProjectBundle\Admin\UserAdmin
            tags:
                - {name: sonata.admin, manager_type: orm, group: users, label: users}
            arguments:
                - null
                - Application\Sonata\UserBundle\Entity\User
                - SonataAdminBundle:CRUD
                - @security.context #forth argument
            calls:
                - [setTranslationDomain, [MyProjectBundle]]
                - [setUserManager, [@fos_user.user_manager]]
    

    In you UserAdmin class, override the constructor:

    namespace My\ProjectBundle\Admin;
    
    class UserAdmin extends Admin
    {
    
        private $securityContext = null;
    
        public function __construct($code, $class, $baseControllerName, $secutiryContext=null)
        {
            parent::__construct($code, $class, $baseControllerName);
            $this->securityContext = $securityContext;
        }
    
        public function createQuery($context = 'list')
        {
            $query = parent::createQuery($context);
            $query->andWhere( 
                $query->expr()->eq($query->getRootAlias().'.company', ':comp')
            );
            $query->setParameter('comp', $this->securityContext->user->getCompany());
            return $query;
        }
    }
    

    I didn't test this code, but i use this method to inject service_container in sonata admin to manage file upload using Gedmo Uploadable.

    Hope this helps.