- Author:
- mwicat
- Posted:
- May 4, 2011
- Language:
- Python
- Version:
- 1.3
- Tags:
- authentication
- Score:
- 0 (after 0 ratings)
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
- Serialize a model instance by chriswedgwood 1 week ago
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 1 week ago
- Crispy Form by sourabhsinha396 10 months ago
- ReadOnlySelect by mkoistinen 10 months, 2 weeks ago
- Verify events sent to your webhook endpoints by santos22 11 months, 1 week ago
Comments
Please login first before commenting.