Coverage for apis_core/core/mixins.py: 38%
26 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-16 07:42 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-16 07:42 +0000
1from django.conf import settings
2from django.contrib.auth.mixins import AccessMixin
4from apis_core.utils.utils import access_for_all
7class ViewPassesTestMixin(AccessMixin):
8 """
9 Deny a request with a permission error if the test_func() method returns
10 False. This is mostly a copy of Django's UserPassesTestMixin, but it allows
11 to set the APIS_VIEW_PASSES_TEST setting to define a function that receives
12 the view and can perform checks on any of the views attributes.
13 If such a setting does not exist, it falls back to APIS' access_for_all
14 function.
15 """
17 def test_func(self):
18 if hasattr(settings, "APIS_VIEW_PASSES_TEST"):
19 return settings.APIS_VIEW_PASSES_TEST(self)
20 # fall back to more general access check
21 return access_for_all(self, viewtype="detail")
23 def get_test_func(self):
24 """
25 Override this method to use a different test_func method.
26 """
27 return self.test_func
29 def dispatch(self, request, *args, **kwargs):
30 view_test_result = self.get_test_func()()
31 if not view_test_result:
32 return self.handle_no_permission()
33 return super().dispatch(request, *args, **kwargs)
36class ListViewObjectFilterMixin:
37 """
38 Filter a queryset of a listview using the APIS_LIST_VIEW_OBJECT_FILTER
39 setting if it exists. A child class has to call the `filter_queryset`
40 method somewhere, most likely in the `get_queryset` method.
41 """
43 def filter_queryset(self, queryset):
44 if hasattr(super(), "filter_queryset"):
45 queryset = super().filter_queryset(queryset)
46 if hasattr(settings, "APIS_LIST_VIEW_OBJECT_FILTER"):
47 return settings.APIS_LIST_VIEW_OBJECT_FILTER(self, queryset)
48 return queryset
50 def get_permission_required(self):
51 if getattr(settings, "APIS_LIST_VIEWS_ALLOWED", False):
52 return []
53 return super().get_permission_required()