Login

django piston use origin django auth

Author:
lettoo
Posted:
January 31, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Django-piston have two build-in authentication handlers, the HttpBasicAuthentication and OAuthAuthentication. This snippet give another choice which use the django auth. It can support ajax and normal request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect, HttpResponse
from django.utils import simplejson
from django.utils.http import urlquote

class DjangoAuthentication(object):
    """
    Django authenticater.
    """
    
    def __init__(self, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
        if not login_url:
            login_url = settings.LOGIN_URL
        self.login_url = login_url
        self.redirect_field_name = redirect_field_name
        self.request = None

    def is_authenticated(self, request):
        """
        This method call the `is_authenticated` method of django
        User in django.contrib.auth.models.
        
        `is_authenticated`: Will be called when checking for
        authentication. It returns True if the user is authenticated
        False otherwise.
        """
        self.request = request
        return request.user.is_authenticated()

    def challenge(self):
        """
        `challenge`: In cases where `is_authenticated` returns
        False, the result of this method will be returned.
        This will usually be a `HttpResponse` object with
        some kind of challenge headers and 401 code on it.
        """
        path = urlquote(self.request.get_full_path())
        tup = self.login_url, self.redirect_field_name, path
        if self.request.is_ajax():
            json = {'redirect': '%s?%s=%s' %tup}
            return HttpResponse(simplejson.dumps(json), mimetype='application/json')
        else:
            return HttpResponseRedirect('%s?%s=%s' %tup)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

dumb906 (on May 12, 2012):

works

#

Please login first before commenting.