Ticket #33299: decorators_sol2.py

File decorators_sol2.py, 2.9 KB (added by Iago González, 3 years ago)

Solution 2

Line 
1from functools import wraps
2from urllib.parse import urlparse
3
4from django.conf import settings
5from django.contrib.auth import REDIRECT_FIELD_NAME
6from django.core.exceptions import PermissionDenied
7from django.shortcuts import resolve_url
8
9
10def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME, include_request=False):
11 """
12 Decorator for views that checks that the user passes the given test,
13 redirecting to the log-in page if necessary. The test should be a callable
14 that takes the user object and returns True if the user passes.
15 """
16
17 def decorator(view_func):
18 @wraps(view_func)
19 def _wrapped_view(request, *args, **kwargs):
20 extra = {"request": request} if include_request else {}
21 if test_func(request.user, **extra):
22 return view_func(request, *args, **kwargs)
23 path = request.build_absolute_uri()
24 resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
25 # If the login url is the same scheme and net location then just
26 # use the path as the "next" url.
27 login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
28 current_scheme, current_netloc = urlparse(path)[:2]
29 if ((not login_scheme or login_scheme == current_scheme) and
30 (not login_netloc or login_netloc == current_netloc)):
31 path = request.get_full_path()
32 from django.contrib.auth.views import redirect_to_login
33 return redirect_to_login(
34 path, resolved_login_url, redirect_field_name)
35 return _wrapped_view
36 return decorator
37
38
39def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
40 """
41 Decorator for views that checks that the user is logged in, redirecting
42 to the log-in page if necessary.
43 """
44 actual_decorator = user_passes_test(
45 lambda u: u.is_authenticated,
46 login_url=login_url,
47 redirect_field_name=redirect_field_name
48 )
49 if function:
50 return actual_decorator(function)
51 return actual_decorator
52
53
54def permission_required(perm, login_url=None, raise_exception=False):
55 """
56 Decorator for views that checks whether a user has a particular permission
57 enabled, redirecting to the log-in page if necessary.
58 If the raise_exception parameter is given the PermissionDenied exception
59 is raised.
60 """
61 def check_perms(user):
62 if isinstance(perm, str):
63 perms = (perm,)
64 else:
65 perms = perm
66 # First check if the user has the permission (even anon users)
67 if user.has_perms(perms):
68 return True
69 # In case the 403 handler should be called raise the exception
70 if raise_exception:
71 raise PermissionDenied
72 # As the last resort, show the login form
73 return False
74 return user_passes_test(check_perms, login_url=login_url)
Back to Top