This is auth_data_required decorator analogous to login_required where authentication data must come in POST of request.
It's useful for API. I took the idea from Tumblr API.
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 | from functools import wraps
from django.contrib.auth import authenticate
from django.utils.decorators import available_attrs
from django.core import exceptions
def request_has_authentication(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(username=username, password=password)
authenticated = user is not None and user.is_active
if authenticated:
request.user = user
return authenticated
def request_passes_test(request_test_func):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if not request_test_func(request):
raise exceptions.PermissionDenied()
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator
def auth_data_required(function=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
actual_decorator = request_passes_test(request_has_authentication)
if function:
return actual_decorator(function)
return actual_decorator
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.