【问题标题】:Symfony 4: Doctrine-entity returns different data based on ROLE_*Symfony 4:Doctrine-entity 根据 ROLE_* 返回不同的数据
【发布时间】:2018-06-01 20:56:36
【问题描述】:

我得到了一个Account-entity,它应该根据当前登录用户的角色返回不同的数据:

return [                                     // to be returned if user has role:
    'id' => $this->id,                       // ROLE_USER, ROLE_PAYED, ROLE_ADMIN
    'name' => $this->name,                   // ROLE_USER, ROLE_PAYED, ROLE_ADMIN
    'hobbies' => ['some', 'tags'],           // ROLE_PAYED, ROLE_ADMIN
    'roles' => ['ROLE_USER', 'ROLE_PAYED']   // ROLE_ADMIN
];

如果我要在 Controller 中进行此更改,我只需调用 voter。但我想在实体的jsonSerialize-function 中使用它,以便在每个请求中无一例外地实现它。

我猜真正的问题是“如何在实体中获得选民”,但实际上我对 Symfony 的了解还不够(现在只使用了 10 天)。

【问题讨论】:

    标签: php symfony security symfony4


    【解决方案1】:

    选民是服务,服务真的不应该在实体内部。实体不应该对视图或控制器中的任何内容有任何了解。如果您发现自己需要实体内部的服务,这通常表明您需要重新考虑您的架构。

    我将采取的方法是创建一个JsonSerializeAccount 服务,该服务使用AuthorizationChecker 创建 json 数组。

    <?php
    
    namespace App\Service;
    
    use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
    use App\Entity\Account;
    
    class JsonSerializeAccount {
        /**
         * @var AuthorizationCheckerInterface
         */
        private $authorizationChecker;
    
        public function __construct(AuthorizationCheckerInterface $authorizationChecker)
        {
            $this->authorizationChecker = $authorizationChecker;
        }
    
        public function jsonSerialize(Account $account): array
        {
            $json = [
                'id' => $account->getId(),
                'name' => $account->getName(),
            ];
    
            if ($this->authorizationChecker->isGranted('view_hobbies', $account)) {
                $json['hobbies'] = $account->getHobbies();
            }
    
            if ($this->authorizationChecker->isGranted('view_roles', $account)) {
                $json['roles'] = $account->getRoles();
            }
    
            return $json;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      相关资源
      最近更新 更多