Login

Decorator for authenticating token based API calls

Author:
jpulgarin
Posted:
January 7, 2011
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

Uses the token generator located at django.contrib.auth.tokens as an authentication mechanism aimed mainly at API calls. Any POST request with a valid token and user parameter will work as if the user were logged in normally.

 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
# views.py

from django.http import HttpResponseForbidden
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import authenticate, login


try: 
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps # Python 2.4 fallback

# Decorator for using API with normal auth vs token
def logged_in_or_token(view_func):
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)
        if 'token' in request.REQUEST and \
            'user' in request.REQUEST:
                user = authenticate(pk=request.REQUEST['user'], token=request.REQUEST['token'])
                if user:
                    login(request, user)
                    return view_func(request, *args, **kwargs)
        return HttpResponseForbidden()
    return _wrapped_view


# backends.py

from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.tokens import default_token_generator

class TokenBackend(ModelBackend):
    def authenticate(self, pk, token):
        try:
            user = User.objects.get(pk=pk)
        except User.DoesNotExist:
            return None
        if default_token_generator.check_token(user, 
            token): 
            return user
        return None

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, 8 months ago

Comments

udfalkso (on January 7, 2011):

"users = User.objects.all()"

This seems like a rather bad idea.

#

brokenseal (on January 7, 2011):

request.user = user

This seems like a rather bad idea too, it'd be better to authenticate the user, but nice snippets nevertheless.

#

jpulgarin (on January 8, 2011):

Thanks for the input guys, I now pass in "user" with the request so that I don't have to loop through users, and I wrote an authentication backend to avoid manual request.user setting. I'll update the snippet soon.

#

jpulgarin (on February 17, 2011):

Updated.

#

jpulgarin (on February 25, 2011):

Released this as part of django-tokenapi

#

Please login first before commenting.