Login

ad-hoc request authentication

Author:
mwicat
Posted:
May 4, 2011
Language:
Python
Version:
1.3
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.