首页 > 解决方案 > 仅当用户等于经过身份验证的用户时,如何使用规范化组获取用户电子邮件

问题描述

我使用 api-platform 创建了一个经典User类,我希望我的GET /users/{id}端点具有不同的行为,具体取决于经过身份验证的用户是否等于{id}用户。

如果我是同一用户(显示电子邮件)

{
  "@context": "/contexts/User",
  "@id": "/users/1",
  "@type": "User",
  "email": "peter@test.com",
  "username": "peter"
}

如果没有(隐藏电子邮件)

{
  "@context": "/contexts/User",
  "@id": "/users/1",
  "@type": "User",
  "username": "peter"
}

我尝试在电子邮件字段中添加自定义组,就像我可以在这里阅读的那样https://api-platform.com/docs/core/serialization/#sharing-the-serialization-context-dynamically

但我不知道如何检索用户对象的信息SerializerContextBuilderInterface

/**
 * @ORM\Column(type="string", length=180, unique=true)
 * @Groups({"owner:read", "user:write"})
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

标签: apisymfonyapi-platform.com

解决方案


在实现 SerializerContextBuilderInterface 的类中,您可以通过将 TokenStorageInterface $tokenStorage 传递给构造函数来检索当前用户。和对象$user(需要序列化)你可以使用 Request:$this->userRepository->find($request->get('id')); 这里的例子:

public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null) : array
{
    $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);

    $route = $request->get('_route');

    if ($route === 'api_users_get_item') {
        $currentUser = $this->token->getToken()->getUser();
        $userToSerialize = $this->userRepository->find($request->get('id'));
        if ($currentUser->getId() === $userToSerialize->getId()) {
            $context['groups'][] = 'owner:read';
        }
    }

    return $context;
}

推荐阅读