0

我有 3 个服务,只有在用户具有特定角色时才应该覆盖默认服务。

甚至更好。在新服务中注入当前用户/安全。然后服务执行用户角色检查并调用原始服务。

我试图注入security.context它。但随后$security->getToken()返回null

在控制器中它工作正常。如何在我的服务中获取当前用户?这就是我想要做的:

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);
    }
}
4

1 回答 1

1

在创建服务的那一刻,securityContext 不知道当前用户。安全性在应用程序运行时填充,而不是依赖解析。

以下代码有效。

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);
    }
}

感谢马特奥!

于 2016-05-03T08:13:19.377 回答