I created a blog with a comment system, and I would like the author or administrator to delete his comment.
So I searched the internet, but I found only posts in reference to Symfony 2/3 and I had a hard time understanding.
So I created my own function
/**
* @Route("/blog/commentDelete/{id}-{articleId}-{articleSlug}", name="comment_delete")
*/
public function commentDelete($id, $articleId, $articleSlug, CommentRepository $commentRepository, AuthorizationCheckerInterface $authChecker){
$em = $this->getDoctrine()->getManager();
$comment = $commentRepository->find($id);
$user = $this->getUser();
if ($user->getId() != $comment->getAuthor()->getId() && $authChecker->isGranted('ROLE_MODERATOR') == false ){
throw exception_for("Cette page n'existe pas");
}
$em->remove($comment);
$em->flush();
$this->addFlash('comment_success', 'Commentaire supprimé avec succès');
return $this->redirectToRoute('blog_show', array('id' => $articleId, 'slug' => $articleSlug));
}
On twig, I've this link:
<a href="{{ path('comment_delete', {'id': comment.id, 'articleId': article.id, 'articleSlug': article.slug}) }}">Supprimer</a>
I need the comment id for the action, and article id et article slug to redirect the user once the comment has been deleted.
I check that the person who delete the comment is the author or a moderator.
However, I heard that is absolutely not secure because I have to use a form, but I really don't know how to use a form in this case... Or maybe with JS to hide the link to the final user?
So I would like to know if my function is secure enough or if exists a better solution and how to implement it?