1

I have a very vague question that I'm not sure where to start from.

I need to make an ajax login using python (django REST calls)

jQuery is available from my end.

I was given this:

    import sys, base64
    import httplib, urllib, urlparse, json
    auth = 'Basic %s' % base64.encodestring('%s:%s' % (username, password)).strip()
    headers = {'Content-Type':'application/x-www-form-urlencoded', 'Authorization':auth}
    endpoint = "urlendpoint.com"
    url = "/login/"
    conn = httplib.HTTPSConnection(endpoint)
    conn.request("POST", url, "", headers)
    response = conn.getresponse()
    if response.status != httplib.OK: raise Exception("%s %s" % (response.status, response.reason))
    result = json.load(response)
    if "token" not in result: raise Exception("Unable to acquire token.")
    if "sessionid" not in result: raise Exception("Unable to acquire session ID.")
    print result["token"], result["sessionid"]
    conn.close()

I need to send the login via POST and then set a cookie.

I have absolutely no clue where to begin with this task. Using the command line, I'm able to set up a /login.py file, access said file with a username and password hard-coded in the above variable field and VIOLA - it works fine. However, I have no clue where to begin using ajax for this task.

The main thing here is that I need to establish a session ID between the logged in user and the server once the person has logged in, in order to get access to the REST (json) endpoints so that I can start adding data (via Ajax).

Any assistance would be much appreciated.

I'm hoping that someone

jake
  • 317
  • 5
  • 18
  • Do you need to write the front end, or the back end? If you just want some user auth system written in Python; then use `Flask` which will be easier to get started with. You need to come up with a specific question. – Burhan Khalid Aug 09 '12 at 20:25
  • I can write html until I'm blue in the face - I just have no idea what I should do with the above code to establish a sessionID or what to with the "token" being printed above. When I use the above code from the command line, I can successfully login. However, this does me no good as I need this to happen from a web browser. The back-end exists. I'll look into Flask, and see what that has to offer. **Edit - the user authorization system is in Django. And that part works well. I need to establish the connection VIA https:// from a web browser . – jake Aug 09 '12 at 20:36
  • I think [this question](http://stackoverflow.com/questions/312925/django-authentication-and-ajax-urls-that-require-login) is what you want. – Burhan Khalid Aug 09 '12 at 20:40
  • I'll take a gander at that. I think that my first step is to make a connection using plain jane html first.. Then move it over to ajax. I'll post my answers if I find them :-/ – jake Aug 09 '12 at 21:27

1 Answers1

6

There's functionally no difference between how it's done for a regular view and how you'd do it for an AJAX view; the only difference is what response you send:

from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseBadRequest
from django.utils import simplejson

def ajax_login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        if username and password:
            # Test username/password combination
            user = authenticate(username=username, password=password)
            # Found a match
            if user is not None:
                # User is active
                if user.is_active:
                    # Officially log the user in
                    login(self.request, user)
                    data = {'success': True}
                else:
                    data = {'success': False, 'error': 'User is not active'}
            else:
                data = {'success': False, 'error': 'Wrong username and/or password'}

            return HttpResponse(simplejson.dumps(data), mimetype='application/json')

    # Request method is not POST or one of username or password is missing
    return HttpResponseBadRequest()        
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444