api - 仅当用户等于经过身份验证的用户时,如何使用规范化组获取用户电子邮件
问题描述
我使用 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;
解决方案
在实现 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;
}
推荐阅读
- jquery - 带有表单提交的 AJAX 验证
- html - XML 字符实体不解析
- c++ - 谷歌测试:如何测试所有可能的 N 类型对?
- c - stm32CubeMX 的 cmsis_os.c 有修复吗?
- git - Git:使用多个单引用合并模拟章鱼合并
- bash - 如何在“if”条件下使用圆括号
- tensorflow - Tensorflow 2 在自定义编写层中出错,在 Tensorflow 1 中运行良好(断言 t.graph == cond_graph; AssertionError)
- ruby-on-rails - RoR 控制器 ensure_user_profile 实现
- html - 为什么我的横幅视频无法在 chrome 中自动播放?
- javascript - 将 HTML 表单存储到变量