Coverage for backend/django/core/viewset.py: 92%
30 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-06-23 21:51 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2026-06-23 21:51 +0000
1from rest_framework import viewsets
4class ContextMixin:
5 """
6 A mixin that provides the flowsheet context to all views to enforce access control.
7 """
8 def initial(self, request, *args, **kwargs):
9 if hasattr(self, 'action'): 9 ↛ 14line 9 didn't jump to line 14 because the condition on line 9 was always true
10 view_method = getattr(self, self.action, None)
11 if hasattr(view_method, 'ignore_access_control') and view_method.ignore_access_control:
12 return super().initial(request, *args, **kwargs)
14 if hasattr(request, "query_params"): 14 ↛ 17line 14 didn't jump to line 17 because the condition on line 14 was always true
15 flowsheet_id = request.query_params.get("flowsheet")
16 else:
17 flowsheet_id = request.GET.get("flowsheet")
19 from core.validation import sanitize_flowsheet_id, flowsheet_context
21 flowsheet_id = sanitize_flowsheet_id(flowsheet_id)
22 action = getattr(self, "action", None)
23 write_actions = {"create", "update", "partial_update", "destroy"} | set(
24 getattr(self, "write_actions", set())
25 )
26 write_intent = action in write_actions
27 self.flowsheet_context = flowsheet_context(flowsheet_id, request.user, write_intent=write_intent)
28 # start the context
29 self.flowsheet_token = self.flowsheet_context.__enter__()
31 return super().initial(request, *args, **kwargs)
33 def finalize_response(self, request, response, *args, **kwargs):
34 # Clean up context when the response is finalized
35 if hasattr(self, 'flowsheet_context'):
36 self.flowsheet_context.__exit__(None, None, None)
38 return super().finalize_response(request, response, *args, **kwargs)
40 def handle_exception(self, exc):
41 # Clean up context in case of exception
42 if hasattr(self, 'flowsheet_context'):
43 self.flowsheet_context.__exit__(type(exc), exc, exc.__traceback__)
45 return super().handle_exception(exc)
47class ReadOnlyModelViewSet(ContextMixin, viewsets.ReadOnlyModelViewSet):
48 """
49 Use this model viewset for read-only operations instead of the default one to enforce access control.
50 """
51 pass
53class ModelViewSet(ContextMixin, viewsets.ModelViewSet):
54 """
55 Use this model viewset instead of the default one to enforce access control.
56 """
57 pass