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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
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
#
Please login first before commenting.