Skip to content

Commit

Permalink
Add CSRF protection for Add to cart action (#273)
Browse files Browse the repository at this point in the history
* Fix CSRF protection for cart - resolves #260

* Fix CSRF protection for cart - resolves #260
  • Loading branch information
dvesh3 committed Dec 9, 2021
1 parent 0d7a14f commit 13ef643
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/Controller/CartController.php
Expand Up @@ -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
Expand All @@ -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);

Expand Down
7 changes: 5 additions & 2 deletions templates/product/detail.html.twig
Expand Up @@ -156,8 +156,11 @@
<p class="small text-muted mt-1">{{ 'general.available-in' | trans }} {{ ('attribute.' ~ product.saleInformation.saleInformation.availabilityType) | lower | trans }}</p>
{% endif %}
</div>

<a href="{{ path('shop-add-to-cart', { id: product.id }) }}" class="btn btn-success btn-block">{{ 'general.add-to-cart' | trans }}</a>
<form id="shop_add_to_cart_form" method="post" action="{{ path('shop-add-to-cart', { id: product.id }) }}">
<input type="hidden" name="_csrf_token" value="{{ csrf_token('addToCart') }}">
<a href="#" onclick="document.getElementById('shop_add_to_cart_form').submit();"
class="btn btn-success btn-block">{{ 'general.add-to-cart' | trans }}</a>
</form>

</div>

Expand Down
7 changes: 6 additions & 1 deletion templates/product/product_teaser.html.twig
Expand Up @@ -33,7 +33,12 @@
</a>
</div>
<div class="col p-1">
<a href="{{ path('shop-add-to-cart', { id: product.id }) }}" class="btn btn-block btn-primary">{{ 'general.buy' | trans }} <i class=" ml-2"><img src="/static/images/icons/cart.svg" height="20" width="auto"></i></a>
<form id="shop_add_to_cart_form" method="post" action="{{ path('shop-add-to-cart', { id: product.id }) }}">
<input type="hidden" name="_csrf_token" value="{{ csrf_token('addToCart') }}">
<a href="#" onclick="document.getElementById('shop_add_to_cart_form').submit();"
class="btn btn-block btn-primary">{{ 'general.buy' | trans }} <i class=" ml-2"><img
src="/static/images/icons/cart.svg" height="20" width="auto"></i></a>
</form>
</div>
</div>
</div>
Expand Down

0 comments on commit 13ef643

Please sign in to comment.