Login

ad-hoc request authentication

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

  1. Decorator for authenticating token based API calls by jpulgarin 4 years, 4 months ago
  2. Custom requests auth class for Tastypie API key authentication by jezdez 3 years, 2 months ago
  3. Support alternative authentication mechanisms with Piston by erikwright 5 years, 4 months ago
  4. Digest authentication for Piston by erikwright 5 years, 4 months ago
  5. logging tastypie middleware by lalutium 6 months, 3 weeks ago

Comments

Please login first before commenting.