如何让用户只能使用Symfony删除或修改自己的帖子



如何让用户只能删除或修改自己的帖子。

我可以用登录的用户id成功添加帖子,我可以删除或修改帖子,但我想确保添加帖子的特定用户可以修改或删除帖子。

这是我在控制器中修改功能的帖子

public function edit(Request $request, Posts $post, EntityManagerInterface $entityManager, $id): Response
{
// $post= $this->getDoctrine()->getRepository(Posts::class)->find($id);
// $resultat=$this->getUser()->getPosts();
// $resultat->contains($post);
// if (!($resultat ==true))
// {
//     return $this->json(['code' => 403, 'error' => 'Vous devez être connecté !'], 403);
// }
$user = $this->getUser();
if ($post->isPostedByUser($user))
{
return $this->json(['code' => 403, 'error' => 'c est votre post  !'], 403);
}

$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('posts_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('blog/edit.html.twig', [
'post' => $post,
'postform' => $form->createView(),
]);
}

这是我用来查看这篇文章是否由当前用户发布在实体Posts.php 中的功能

public function isPostedByUser(User $user): bool
{

if ($this->getUser()->getPosts() === $user) {
return true;
}

return false;
}

还有别的办法吗?

有两种方法可以做到这一点,第一种是直接在method中进行检查,第二种是使用符号工具,即Voter

1.检查方法的方法

public function edit(Request $request, Posts $post, EntityManagerInterface $entityManager, $id): Response
{
if($post->getUser() != $this->getUser()){  // $post->getUser() or another method that returns the user of your post
return $this->json(['code' => 403, 'error' => 'c est votre post  !'], 403);
}
// some you action
}

2.使用symfony Voter的变体

在安全文件夹中创建PostVoter

// src/Security/PostVoter.php
class PostVoter extends Voter
{
const EDIT = 'edit';
protected function supports(string $attribute, $subject): bool
{
if (!$subject instanceof Posts) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var Posts $post */
$post = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($post, $user);
}
throw new LogicException('This code should not be reached!');
}
private function canEdit(Posts $post, User $user): bool
{
return $user === $post->getUser(); // $post->getUser() or another method that returns the user of your post
}
}

在编辑方法的顶部添加一个针对新创建的PostVoter的检查

public function edit(Request $request, Posts $post, EntityManagerInterface $entityManager, $id): Response
{
$this->denyAccessUnlessGranted('edit', $post); // here we connect the check PostVoter 

// some you action
}

如果您选择了选项2,那么以下是来自官方文档的更多信息

最新更新