|
0
|
1 |
try: |
|
29
|
2 |
from functools import update_wrapper, wraps |
|
0
|
3 |
except ImportError: |
|
29
|
4 |
from django.utils.functional import update_wrapper, wraps # Python 2.4 fallback. |
|
0
|
5 |
|
|
|
6 |
from django.contrib.auth import REDIRECT_FIELD_NAME |
|
|
7 |
from django.http import HttpResponseRedirect |
|
29
|
8 |
from django.utils.decorators import available_attrs |
|
0
|
9 |
from django.utils.http import urlquote |
|
|
10 |
|
|
29
|
11 |
|
|
0
|
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 |
""" |
|
29
|
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 |
|
|
0
|
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 |
|
|
29
|
46 |
|
|
0
|
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) |