web/lib/django/contrib/auth/decorators.py
changeset 38 77b6da96e6f1
equal deleted inserted replaced
37:8d941af65caf 38:77b6da96e6f1
       
     1 try:
       
     2     from functools import update_wrapper, wraps
       
     3 except ImportError:
       
     4     from django.utils.functional import update_wrapper, wraps  # Python 2.4 fallback.
       
     5 
       
     6 from django.contrib.auth import REDIRECT_FIELD_NAME
       
     7 from django.http import HttpResponseRedirect
       
     8 from django.utils.decorators import available_attrs
       
     9 from django.utils.http import urlquote
       
    10 
       
    11 
       
    12 def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
       
    13     """
       
    14     Decorator for views that checks that the user passes the given test,
       
    15     redirecting to the log-in page if necessary. The test should be a callable
       
    16     that takes the user object and returns True if the user passes.
       
    17     """
       
    18     if not login_url:
       
    19         from django.conf import settings
       
    20         login_url = settings.LOGIN_URL
       
    21 
       
    22     def decorator(view_func):
       
    23         def _wrapped_view(request, *args, **kwargs):
       
    24             if test_func(request.user):
       
    25                 return view_func(request, *args, **kwargs)
       
    26             path = urlquote(request.get_full_path())
       
    27             tup = login_url, redirect_field_name, path
       
    28             return HttpResponseRedirect('%s?%s=%s' % tup)
       
    29         return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
       
    30     return decorator
       
    31 
       
    32 
       
    33 def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
       
    34     """
       
    35     Decorator for views that checks that the user is logged in, redirecting
       
    36     to the log-in page if necessary.
       
    37     """
       
    38     actual_decorator = user_passes_test(
       
    39         lambda u: u.is_authenticated(),
       
    40         redirect_field_name=redirect_field_name
       
    41     )
       
    42     if function:
       
    43         return actual_decorator(function)
       
    44     return actual_decorator
       
    45 
       
    46 
       
    47 def permission_required(perm, login_url=None):
       
    48     """
       
    49     Decorator for views that checks whether a user has a particular permission
       
    50     enabled, redirecting to the log-in page if necessary.
       
    51     """
       
    52     return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)