Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py: 27%
38 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from functools import wraps
2from urllib.parse import urlparse
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
10def user_passes_test(
11 test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME
12):
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 """
19 def decorator(view_func):
20 @wraps(view_func)
21 def _wrapped_view(request, *args, **kwargs):
22 if test_func(request.user):
23 return view_func(request, *args, **kwargs)
24 path = request.build_absolute_uri()
25 resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
26 # If the login url is the same scheme and net location then just
27 # use the path as the "next" url.
28 login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
29 current_scheme, current_netloc = urlparse(path)[:2]
30 if (not login_scheme or login_scheme == current_scheme) and (
31 not login_netloc or login_netloc == current_netloc
32 ):
33 path = request.get_full_path()
34 from django.contrib.auth.views import redirect_to_login
36 return redirect_to_login(path, resolved_login_url, redirect_field_name)
38 return _wrapped_view
40 return decorator
43def login_required(
44 function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None
45):
46 """
47 Decorator for views that checks that the user is logged in, redirecting
48 to the log-in page if necessary.
49 """
50 actual_decorator = user_passes_test(
51 lambda u: u.is_authenticated,
52 login_url=login_url,
53 redirect_field_name=redirect_field_name,
54 )
55 if function:
56 return actual_decorator(function)
57 return actual_decorator
60def permission_required(perm, login_url=None, raise_exception=False):
61 """
62 Decorator for views that checks whether a user has a particular permission
63 enabled, redirecting to the log-in page if necessary.
64 If the raise_exception parameter is given the PermissionDenied exception
65 is raised.
66 """
68 def check_perms(user):
69 if isinstance(perm, str):
70 perms = (perm,)
71 else:
72 perms = perm
73 # First check if the user has the permission (even anon users)
74 if user.has_perms(perms):
75 return True
76 # In case the 403 handler should be called raise the exception
77 if raise_exception:
78 raise PermissionDenied
79 # As the last resort, show the login form
80 return False
82 return user_passes_test(check_perms, login_url=login_url)