gpt4 book ai didi

Symfony 总是返回拒绝访问、@Security、 Controller 、isAuthor

转载 作者:行者123 更新时间:2023-12-04 11:35:56 25 4
gpt4 key购买 nike

我使用用户和产品系统编写了一个简单的应用程序(Symfony 4.1.7)

用户可以编辑他的产品,但不能编辑其他用户的

我的问题,我继续编辑路线,它返回访问被拒绝,即使它是我的产品

我的产品 Controller :

   /**
* @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()
]);
}

产品.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 函数中

== 拒绝访问

!== 我可以访问不是我的产品版本

用户名
 /**
* @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当您比较 ArrayCollection 时到 User
您可以在用户类定义中添加一个函数,用于检查给定用户是否拥有给定产品。

所以在 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)
}

关于Symfony 总是返回拒绝访问、@Security、 Controller 、isAuthor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53485714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com