Symfony始终返回访问被拒绝,@Security,controller,isAuthor
我用用户和产品系统编写了一个简单的应用程序(Symfony 4.1.7) 用户可以编辑其产品,但不能编辑其他用户的产品 我的问题是,我走编辑路线,它返回访问被拒绝,即使它是我的产品 我的产品控制器:Symfony始终返回访问被拒绝,@Security,controller,isAuthor,symfony,Symfony,我用用户和产品系统编写了一个简单的应用程序(Symfony 4.1.7) 用户可以编辑其产品,但不能编辑其他用户的产品 我的问题是,我走编辑路线,它返回访问被拒绝,即使它是我的产品 我的产品控制器: /** * @Route("seller/myproduct/{id}/edit", name="seller_edit_product") * @param Product $product * @return Response * @Security("product.isAuth
/**
* @Route("seller/myproduct/{id}/edit", name="seller_edit_product")
* @param Product $product
* @return Response
* @Security("product.isAuthor(user)")
*/
public function edit(Product $product, Request $request): Response
{
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->flush();
$this->addFlash('success', 'Modify Successfully');
return $this->redirectToRoute('seller_index_product');
}
return $this->render('seller/product/edit.html.twig', [
'product' => $product,
'form' => $form->createView()
]);
}
Product.php
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="product_id")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
public function getUser(): User
{
return $this->user;
}
public function setUser(User $user): self
{
$this->user = $user;
return $this;
}
/**
* @return bool
*/
public function isAuthor(User $user = null)
{
return $user && $user->getProductId() === $this->getUser();
}
在我的isAuhor函数中
=访问被拒绝
==我可以访问非我的产品版本
User.php
/**
* @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="user",orphanRemoval=true)
*/
private $product_id;
public function __construct()
{
$this->product_id = new ArrayCollection();
}
/**
* @return Collection|Product[]
*/
public function getProductId(): Collection
{
return $this->product_id;
}
public function addProductId(Product $productId): self
{
if (!$this->product_id->contains($productId)) {
$this->product_id[] = $productId;
$productId->setUser($this);
}
return $this;
}
}
谢谢当您将
数组集合
与用户
进行比较时,您的isAuthor
函数将始终返回false
您可以在用户类定义中添加一个函数,用于检查给定用户是否具有给定的产品
因此,在Product.php中:
/**
* @return bool
*/
public function isAuthor(User $user = null)
{
return $user && $user->hasProduct($this);
}
而hasProduction
函数可以是这样的:
// this goes into User.php
/**
* @return bool
*/
public function hasProduct(Product $product)
{
return $this->product_id->contains($product)
}
如果你仍然有这个问题,考虑使用安全选民。它将产生一个更干净的解决方案,以换取更多的代码。谢谢你(: