# 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