Reputation:
I code a simple app (Symfony 4.1.7) with a user and product system
A user can edit his product, but not another user's
My problem, I go on the edit route, it return access denied, even when it's my product
My 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();
}
In my isAuhor function
== Access Denied
!== I can access the edition of product that Is not mine
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;
}
}
Thank you
Upvotes: 4
Views: 124
Reputation: 7800
Your isAuthor
function will always return false
as you are comparing an ArrayCollection
to a User
You could add a function in User Class definition that checks if a given user have a given product or no.
So in Product.php :
/**
* @return bool
*/
public function isAuthor(User $user = null)
{
return $user && $user->hasProduct($this);
}
And the hasProduction
function could be something like this:
// this goes into User.php
/**
* @return bool
*/
public function hasProduct(Product $product)
{
return $this->product_id->contains($product)
}
Upvotes: 2