Login

Django authentication for django-piston

Author:
chronos
Posted:
September 16, 2010
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

This authenticate together django.contrib.auth.models.User like django normal login does.

 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# coding: utf-8

from django.contrib.auth import login as auth_login
from django.contrib.auth.forms import AuthenticationForm
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.translation import ugettext as _

class DjangoAuthentication(object):
    """
    Django authentication for piston
    """
    request = None
    errors = None

    def is_authenticated(self, request):
        """
        if user is_authenticated: return True
        else try to autenticate with django and return true/false dependent of
        result
        """
        self.request = request

        # is authenticated
        if self.request.user.is_authenticated():
            return True

        # not authenticated, call authentication form
        f = AuthenticationForm(data={
            'username': self.request.POST.get('username',''),
            'password': self.request.POST.get('password',''),
        })

        # if authenticated log the user in.
        if f.is_valid():

            auth_login(self.request,f.get_user())
            # this ** should ** return true
            return self.request.user.is_authenticated()

        else:
            # fail to auth, save form errors
            self.errors = f.errors
            return False

    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.
        """
        resp = { 'error': _('Authentication needed'), 'msgs': self.errors }
        return HttpResponse(simplejson.dumps(
                resp, cls=DateTimeAwareJSONEncoder,
                ensure_ascii=False, indent=4),
            status=401,mimetype="application/json")

More like this

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

Comments

Please login first before commenting.