ユーザーと製品システムを使用して単純なアプリ(Symfony 4.1.7)をコーディングします
ユーザーは自分の製品を編集できますが、他のユーザーの製品は編集できません
私の問題、私は編集ルートに行きます、それが私の製品であっても、それは拒否されたアクセスを返します
私のProductController:
/**
* @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
、あなたが比較されているよう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)
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加