Coverage for src/mesh/views/views_role.py: 34%
25 statements
« prev ^ index » next coverage.py v7.7.0, created at 2025-04-28 07:45 +0000
« prev ^ index » next coverage.py v7.7.0, created at 2025-04-28 07:45 +0000
1from django.contrib import messages
2from django.http import HttpRequest, HttpResponseRedirect
3from django.urls import reverse_lazy
4from django.views.generic import View
5from ptf.url_utils import add_query_parameters_to_url
7from mesh.model.exceptions import RoleException
8from mesh.views.forms.role_forms import RoleSwitchForm
9from mesh.views.mixins import ROLE_SWITCH_QUERY_PARAM, RoleMixin
12class RoleSwitchView(RoleMixin, View):
13 """
14 View used to switch the user's current role.
16 Appends the query parameter `ROLE_SWITCH_QUERY_PARAM` to the redirect URL to
17 indicate a role switch was requested.
18 The info is not stored in the session because it would require the session
19 to be always correctly cleaned afterwards.
20 On the other hand a query parameter disappears on the next navigation.
21 """
23 def post(self, request: HttpRequest, *args, **kwargs):
24 form = RoleSwitchForm(request.POST)
25 redirect_url = request.headers.get("referer", None)
26 if not redirect_url:
27 redirect_url = reverse_lazy("mesh:home")
28 # If there's an URL to redirect to, add the query parameter _role_switch=true
29 else:
30 redirect_url = add_query_parameters_to_url(
31 redirect_url, {ROLE_SWITCH_QUERY_PARAM: ["true"]}
32 )
34 response = HttpResponseRedirect(redirect_url)
35 if not form.is_valid():
36 messages.error(request, "Error: Something went wrong.")
37 return response
39 try:
40 role = self.role_handler.switch_role(form.cleaned_data["role_code"])
41 messages.success(request, f"Successfully switched to '{role.name()}' view.")
42 except RoleException as e:
43 messages.error(request, str(e))
45 return response