Browse Source

fix #682 - add /api/auth/token/ edge for obtaining CSRF token from API

Rafał Pitoń 8 years ago
parent
commit
8e23f39329
3 changed files with 23 additions and 1 deletions
  1. 10 1
      misago/users/api/auth.py
  2. 12 0
      misago/users/tests/test_auth_api.py
  3. 1 0
      misago/users/urls/api.py

+ 10 - 1
misago/users/api/auth.py

@@ -1,7 +1,7 @@
 from django.contrib import auth
 from django.core.exceptions import ValidationError
 from django.utils.translation import ugettext as _
-from django.views.decorators.csrf import csrf_protect
+from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
 
 from rest_framework import status
 from rest_framework.decorators import api_view, permission_classes
@@ -56,6 +56,15 @@ def session_user(request):
 
 
 """
+GET /auth/token/ will return cookie with current auth token
+"""
+@api_view(['GET'])
+@ensure_csrf_cookie
+def get_token(request):
+    return Response({'detail': 'ok'})
+
+
+"""
 POST /auth/send-activation/ with CSRF token and email
 will mail account activation link to requester
 """

+ 12 - 0
misago/users/tests/test_auth_api.py

@@ -1,3 +1,4 @@
+from django.conf import settings
 from django.contrib.auth import get_user_model
 from django.core import mail
 from django.test import TestCase
@@ -7,6 +8,17 @@ from ..models import BAN_USERNAME, Ban
 from ..tokens import make_activation_token, make_password_change_token
 
 
+class GetTokenTests(TestCase):
+    def test_token_api(self):
+        """api returns CSRF token on GET request"""
+        response = self.client.get('/api/auth/token/')
+
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(response.json(), {'detail': 'ok'})
+
+        self.assertIn(settings.CSRF_COOKIE_NAME, response.client.cookies)
+
+
 class GatewayTests(TestCase):
     def test_api_invalid_credentials(self):
         """login api returns 400 on invalid POST"""

+ 1 - 0
misago/users/urls/api.py

@@ -10,6 +10,7 @@ from ..api.users import UserViewSet
 
 urlpatterns = [
     url(r'^auth/$', auth.gateway, name='auth'),
+    url(r'^auth/token/$', auth.get_token, name='get-token'),
     url(r'^auth/send-activation/$', auth.send_activation, name='send-activation'),
     url(r'^auth/send-password-form/$', auth.send_password_form, name='send-password-form'),
     url(r'^auth/change-password/(?P<pk>\d+)/(?P<token>[a-zA-Z0-9]+)/$', auth.change_forgotten_password, name='change-forgotten-password'),