Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Release history of [django-admin-sortable2](https://github.com/jrief/django-admin-sortable2/)

### 2.3.2
- fix #434: Respect Django's `CSRF_HEADER_NAME` for sortable update requests in the admin changelist.

### 2.3.1
- fix #370: `django-compress` and `django-sass-processor` raises errors during run of compress or compilescss
management command.
Expand Down
10 changes: 10 additions & 0 deletions adminsortable2/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,7 @@ def _bulk_move(self, request, queryset, method):
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
extra_context['sortable_update_url'] = self.get_update_url(request)
extra_context['sortable_csrf_header_name'] = self.get_csrf_header_name(request)
extra_context['base_change_list_template'] = super().change_list_template or 'admin/change_list.html'
return super().changelist_view(request, extra_context)

Expand All @@ -459,6 +460,15 @@ def get_update_url(self, request):
"""
return reverse(f'{self.admin_site.name}:{self._get_update_url_name()}')

def get_csrf_header_name(self, request):
"""
Returns the HTTP header expected by Django's CSRF middleware.
"""
csrf_header_name = getattr(settings, 'CSRF_HEADER_NAME', 'HTTP_X_CSRFTOKEN')
if csrf_header_name.startswith('HTTP_'):
csrf_header_name = csrf_header_name[5:]
return csrf_header_name.replace('_', '-')


class PolymorphicSortableAdminMixin(SortableAdminMixin):
"""
Expand Down
1 change: 1 addition & 0 deletions adminsortable2/templates/adminsortable2/change_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<script type="application/json" id="admin_sortable2_config">
{
"update_url": "{{ sortable_update_url }}",
"csrf_header": "{{ sortable_csrf_header_name }}",
"current_page": {{ cl.page_num }},
"total_pages": {{ cl.paginator.num_pages }}
}
Expand Down
2 changes: 1 addition & 1 deletion client/admin-sortable2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class ListSortable {

const inputElement = this.tableBody.closest('form')?.querySelector('input[name="csrfmiddlewaretoken"]') as HTMLInputElement;
if (inputElement) {
headers.append('X-CSRFToken', inputElement.value);
headers.append(this.config.csrf_header || 'X-CSRFToken', inputElement.value);
}
return headers;
}
Expand Down
52 changes: 51 additions & 1 deletion testapp/test_add_sortable.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import json
import re

import pytest

from django.test import Client
from django.test import Client, override_settings
from django.urls import reverse

from testapp.models import Book1
Expand Down Expand Up @@ -58,3 +61,50 @@ def test_add_chapter():
assert python_in_a_nutshell.chapter_set.count() == 2
assert python_in_a_nutshell.chapter_set.first().my_order == 1
assert python_in_a_nutshell.chapter_set.last().my_order == 2


@pytest.mark.django_db
@override_settings(CSRF_USE_SESSIONS=True, CSRF_HEADER_NAME='HTTP_X_AUTH_CSRFTOKEN')
def test_sortable_respects_custom_csrf_header_name():
client = Client(enforce_csrf_checks=True)
changelist_response = client.get(reverse('admin:testapp_book1_changelist'))
assert changelist_response.status_code == 200

content = changelist_response.content.decode('utf-8')
config_match = re.search(
r'<script type="application/json" id="admin_sortable2_config">\s*(\{.*?\})\s*</script>',
content,
re.S,
)
assert config_match is not None

config = json.loads(config_match.group(1))
assert config['csrf_header'] == 'X-AUTH-CSRFTOKEN'

token_match = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', content)
assert token_match is not None
csrf_token = token_match.group(1)

book = Book1.objects.order_by('my_order').first()
assert book is not None

update_payload = json.dumps({'updatedItems': [[book.pk, book.my_order]]})
update_url = config['update_url']

# Default header must fail when CSRF_HEADER_NAME is customized.
default_header_response = client.post(
update_url,
data=update_payload,
content_type='application/json',
HTTP_X_CSRFTOKEN=csrf_token,
)
assert default_header_response.status_code == 403

# Custom header succeeds and keeps the endpoint compatible with Django settings.
custom_header_response = client.post(
update_url,
data=update_payload,
content_type='application/json',
HTTP_X_AUTH_CSRFTOKEN=csrf_token,
)
assert custom_header_response.status_code == 200
Loading