From 13ef64359724499246c40296267a7b668ea110dc Mon Sep 17 00:00:00 2001 From: Divesh Pahuja Date: Thu, 9 Dec 2021 13:45:15 +0100 Subject: [PATCH] Add CSRF protection for Add to cart action (#273) * Fix CSRF protection for cart - resolves #260 * Fix CSRF protection for cart - resolves #260 --- src/Controller/CartController.php | 6 +++++- templates/product/detail.html.twig | 7 +++++-- templates/product/product_teaser.html.twig | 7 ++++++- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/Controller/CartController.php b/src/Controller/CartController.php index 1c54ba6e..85da2d4b 100644 --- a/src/Controller/CartController.php +++ b/src/Controller/CartController.php @@ -54,7 +54,7 @@ protected function getCart() } /** - * @Route("/cart/add-to-cart", name="shop-add-to-cart") + * @Route("/cart/add-to-cart", name="shop-add-to-cart", methods={"POST"}) * * @param Request $request * @param Factory $ecommerceFactory @@ -65,6 +65,10 @@ protected function getCart() */ public function addToCartAction(Request $request, Factory $ecommerceFactory) { + if (!$this->isCsrfTokenValid('addToCart', $request->get('_csrf_token'))) { + throw new \Exception('Invalid request'); + } + $id = $request->get('id'); $product = AbstractProduct::getById($id); diff --git a/templates/product/detail.html.twig b/templates/product/detail.html.twig index 70660bd8..ad3ff7ef 100644 --- a/templates/product/detail.html.twig +++ b/templates/product/detail.html.twig @@ -156,8 +156,11 @@

{{ 'general.available-in' | trans }} {{ ('attribute.' ~ product.saleInformation.saleInformation.availabilityType) | lower | trans }}

{% endif %} - - {{ 'general.add-to-cart' | trans }} +
+ + {{ 'general.add-to-cart' | trans }} +
diff --git a/templates/product/product_teaser.html.twig b/templates/product/product_teaser.html.twig index 662a9514..550a6ca3 100644 --- a/templates/product/product_teaser.html.twig +++ b/templates/product/product_teaser.html.twig @@ -33,7 +33,12 @@
- {{ 'general.buy' | trans }} +
+ + {{ 'general.buy' | trans }} +