Search code examples
symfonysulu

Override service for specific user role


I have 3 services which should override the default services only if the user has a specific role.

Or even better. Inject the current user/security in the new services. The service then performs the check for the user role and calls the original service.

I tried to inject security.context into it. But then $security->getToken() returns null.

In the controllers it works fine. How can i get the current user in my service? This is what i want to do:

class AlwaysVisibleNavigationQueryBuilder extends      NavigationQueryBuilder
{
    public function __construct(\Sulu\Component\Content\Compat\StructureManagerInterface $structureManager, $languageNamespace, SecurityContext $security)
    {
        if (in_array('ROLE_SULU_ADMINISTRATOR', $security->getToken()->getRoles())) {
            // Show unpublished content, too
            $this->published = false;
        }

        parent::__construct($structureManager, $languageNamespace);
    }
}

Solution

  • At the moment of creation of the service, the securityContext was not aware of the current user. The Security is filles when the application runs and not on dependency-resolution.

    The following Code works.

    class AlwaysVisibleNavigationQueryBuilder extends NavigationQueryBuilder
    {
        protected $security;
    
        public function __construct(\Sulu\Component\Content\Compat\StructureManagerInterface $structureManager, $languageNamespace, SecurityContext $security)
        {
            $this->security = $security;
    
            parent::__construct($structureManager, $languageNamespace);
        }
    
        public function build($webspaceKey, $locales)
        {
            $roles = $this->security->getToken()->getRoles();
    
            if (in_array('ROLE_SULU_ADMINISTRATOR', $roles)) {
                // Show unpublished content, too
                $this->published = false;
            }
    
            return parent::build($webspaceKey, $locales);
        }
    }
    

    Thanks to Matteo!