# 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
Comments
"users = User.objects.all()"
This seems like a rather bad idea.
#
request.user = user
This seems like a rather bad idea too, it'd be better to authenticate the user, but nice snippets nevertheless.
#
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.
#
Updated.
#
Released this as part of django-tokenapi
#