1๐
I feel like this is pretty "hacky". Are there any security issues involved with what Iโve done here?
A GET request is not supposed to have side-effects. Indeed, as the HTTP specifications say [w3.org]:
In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered โsafeโ.
You should make use of POST, PUT, PATCH or DELETE to make requests with side effects.
Django will automatically try to validate a CSRF token if you make a POST request. This to prevent a vulnerability that could result in a malicious JavaScript file that uses the credentials of the logged in user to make requests. Django (aims to) prevent this by using a CSRF token. You add such token to the POST request as is explained in the AJAX section of the documentation:
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
function add_to_cart(product_pk) {
let url = '/add-to-cart/' + product_pk.toString()
$.ajax({
type: 'POST',
url: url,
processData: false,
contentType: false,
headers: {'X-CSRFToken': csrftoken}
})
}
finally we should product the view to only accept POST requests with the @require_POST
decorator [Django-doc]:
from django.views.decorators.http import require_POST
@require_POST
def add_to_cart(request, product_pk):
# โฆ