1

I followed this to create my ajax authentication. The ajax does not send the POST data; it sends an empty querydict. If I explicitly write my username and password in my ajax view, it logins in and out perfectly... but that is useless.

I found the answer. This has been updated for Django 1.5.1. The code below works.

#Ajax_Views.py
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpRequest
from django.conf.urls import url
from django.utils import simplejson

from tastypie.http import HttpUnauthorized, HttpForbidden
from tastypie.utils import trailing_slash
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization

class UserResource(ModelResource):
    class Meta:
         queryset = User.objects.all()
         fields = ['first_name', 'last_name', 'email']
         allowed_methods = ['get', 'post']
         resource_name = 'user'
         authorization = Authorization()

    def prepend_urls(self):
        return [
        url(r"^(?P<resource_name>%s)/login%s$" %
            (self._meta.resource_name, trailing_slash()),
            self.wrap_view('login'), name="api_login"),
        url(r'^(?P<resource_name>%s)/logout%s$' %
            (self._meta.resource_name, trailing_slash()),
            self.wrap_view('logout'), name='api_logout'),
        ]

    def login(self, request, **kwargs):
        self.method_check(request, allowed=['post', 'ajax'])

        data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
        username = data.get('username', '')
        password = data.get('password', '')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request, user)
                return self.create_response(request, {
                    'success': True
                })
            else:
                return self.create_response(request, {
                    'success': False,
                    'reason': 'disabled',
                    }, HttpForbidden )
        else:
            return self.create_response(request, {
                'success': False,
                'reason': 'incorrect',
                }, HttpUnauthorized )


    def logout(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        if request.user and request.user.is_authenticated():
            logout(request)
            return self.create_response(request, { 'success': True })
        else:
            return self.create_response(request, { 'success': False }, HttpUnauthorized)



#Jquery/Ajax 

$('#send').click(function(e){
    e.preventDefault();
    data = {
        "username": $('#username').val(),
        "password": $('#password').val()
     };
    $.ajax({
        type: "POST",
        url: "http://127.0.0.1:8000/api/user/login/",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function(data) {console.log(data)},
        error: function (rs, e) {console.debug(rs)}
    });
});

#The HTML

    <input type='text' id='username' />
    <input type='password' id='password'/>
    <input type='submit' id='send' class='btn' href='#'>Send</a>
Community
  • 1
  • 1
jmitchel3
  • 391
  • 3
  • 4
  • 16

1 Answers1

0

I'm trying to build out a front end in Backbone for a Django 1.5 app.

I understand the Tastypie stuff and have been able to get that working, but I'm not sure how the page knows if the user is logged in or not when the page is first visited. I am using Session storage - is this incompatible with a JavaScript front end? Do I need to manually store the CSRF token and delete it after the user logs in, am I forced to use Django's (non-Ajax) for login/logout and then redirect to a protected, django served page with the JavaScript app code?

I am serving the JavaScript from django now, to get the CSRF token.. So I think I'm on the right path.

kevins
  • 472
  • 5
  • 16