Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added docs & more tests for ``SessionAuthentication``.

  • Loading branch information...
commit df4a68c2eba0af5a59395caf2bbec1c14a63f03f 1 parent 6b8b884
@toastdriven toastdriven authored
View
56 docs/cookbook.rst
@@ -378,3 +378,59 @@ their own.::
admin.site.unregister(User)
admin.site.register(User,UserModelAdmin)
+
+
+Using ``SessionAuthentication``
+-------------------------------
+
+If your users are logged into the site & you want Javascript to be able to
+access the API (assuming jQuery), the first thing to do is setup
+``SessionAuthentication``::
+
+ from django.contrib.auth.models import User
+ from tastypie.authentication import SessionAuthentication
+ from tastypie.resources import ModelResource
+
+
+ class UserResource(ModelResource):
+ class Meta:
+ resource_name = 'users'
+ queryset = User.objects.all()
+ authentication = SessionAuthentication()
+
+Then you'd build a template like::
+
+ <html>
+ <head>
+ <title></title>
+ <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
+ <script type="text/javascript">
+ $(document).ready(function() {
+ // We use ``.ajax`` here due to the overrides.
+ $.ajax({
+ // Substitute in your API endpoint here.
+ url: '/api/v1/users/',
+ contentType: 'application/json',
+ // The ``X-CSRFToken`` evidently can't be set in the
+ // ``headers`` option, so force it here.
+ // This method requires jQuery 1.5+.
+ beforeSend: function(jqXHR, settings) {
+ // Pull the token out of the DOM.
+ jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
+ },
+ success: function(data, textStatus, jqXHR) {
+ // Your processing of the data here.
+ console.log(data);
+ }
+ });
+ });
+ </script>
+ </head>
+ <body>
+ <!-- Include the CSRF token in the body of the HTML -->
+ {% csrf_token %}
+ </body>
+ </html>
+
+There are other ways to make this function, with other libraries or other
+techniques for supplying the token. This is simply a starting point for
View
9 tests/basic/api/resources.py
@@ -3,6 +3,7 @@
from tastypie.bundle import Bundle
from tastypie import fields
from tastypie.resources import ModelResource
+from tastypie.authentication import SessionAuthentication
from tastypie.authorization import Authorization
from basic.models import Note, AnnotatedNote, SlugBasedNote
@@ -49,3 +50,11 @@ class Meta:
queryset = SlugBasedNote.objects.all()
resource_name = 'slugbased'
detail_uri_name = 'slug'
+
+
+class SessionUserResource(ModelResource):
+ class Meta:
+ resource_name = 'sessionusers'
+ queryset = User.objects.all()
+ authentication = SessionAuthentication()
+ authorization = Authorization()
View
3  tests/basic/api/urls.py
@@ -1,6 +1,6 @@
from django.conf.urls.defaults import *
from tastypie.api import Api
-from basic.api.resources import NoteResource, UserResource, BustedResource, CachedUserResource, SlugBasedNoteResource
+from basic.api.resources import NoteResource, UserResource, BustedResource, CachedUserResource, SlugBasedNoteResource, SessionUserResource
api = Api(api_name='v1')
api.register(NoteResource(), canonical=True)
@@ -10,5 +10,6 @@
v2_api = Api(api_name='v2')
v2_api.register(BustedResource(), canonical=True)
v2_api.register(SlugBasedNoteResource())
+v2_api.register(SessionUserResource())
urlpatterns = v2_api.urls + api.urls
View
21 tests/basic/tests/views.py
@@ -1,5 +1,6 @@
+from django.contrib.auth.models import User
from django.http import HttpRequest
-from django.test import TestCase
+from django.test import TestCase, Client
from django.utils import simplejson as json
@@ -126,3 +127,21 @@ def test_slugbased(self):
self.assertEqual(len(deserialized), 1)
self.assertEqual(len(deserialized['objects']), 2)
self.assertEqual([obj['title'] for obj in deserialized['objects']], [u'Another First Post', u'First Post'])
+
+ def test_session_auth(self):
+ csrf_client = Client(enforce_csrf_checks=True)
+ super_duper = User.objects.create_superuser('daniel', 'daniel@example.com', 'pass')
+
+ # Unauthenticated.
+ resp = csrf_client.get('/api/v2/sessionusers/', data={'format': 'json'})
+ self.assertEqual(resp.status_code, 401)
+
+ # Now log in.
+ self.assertTrue(csrf_client.login(username='daniel', password='pass'))
+ # Fake the cookie the login didn't create. :(
+ csrf_client.cookies['csrftoken'] = 'o9nXqnrypI9ydKoiWGCjDDcxXI7qRymH'
+
+ resp = csrf_client.get('/api/v2/sessionusers/', data={'format': 'json'}, HTTP_X_CSRFTOKEN='o9nXqnrypI9ydKoiWGCjDDcxXI7qRymH')
+ self.assertEqual(resp.status_code, 200)
+ deserialized = json.loads(resp.content)
+ self.assertEqual(len(deserialized), 2)
View
1  tests/settings_basic.py
@@ -1,4 +1,5 @@
from settings import *
+INSTALLED_APPS.append('django.contrib.sessions')
INSTALLED_APPS.append('basic')
ROOT_URLCONF = 'basic.urls'
Please sign in to comment.
Something went wrong with that request. Please try again.