Login

Django authentication for django-piston

Author:
chronos
Posted:
September 16, 2010
Language:
Python
Version:
1.2
Tags:
authentication piston
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. Support alternative authentication mechanisms with Piston by erikwright 5 years, 3 months ago
  2. django-tokenapi authentication for django-piston by yurtaev 3 years, 5 months ago
  3. Digest authentication for Piston by erikwright 5 years, 3 months ago
  4. django piston use origin django auth by lettoo 3 years, 2 months ago
  5. Django BasicAuthMixin by icrni 10 months, 2 weeks ago

Comments

Please login first before commenting.