1 from django.contrib.auth.mixins import UserPassesTestMixin

2 from django.shortcuts import get_object_or_404

3

4 from meshadmin.server.networks.models import Network, NetworkMembership

5

6

7 class NetworkPermissionMixin(UserPassesTestMixin):

8 def get_network(self):

9 if hasattr(self, "object") and isinstance(self.object, Network):

10 return self.object

11

12 network_id = self.kwargs.get("network_id") or self.kwargs.get("pk")

13 if network_id:

14 return get_object_or_404(Network, id=network_id)

15

16 if hasattr(self, "object"):

17 return self.object.network

18

19 return None

20

21 def test_func(self):

22 network = self.get_network()

23 if not network:

24 return False

25

26 if self.request.user.is_superuser:

27 return True

28

29 return NetworkMembership.objects.filter(

30 network=network,

31 user=self.request.user,

32 role__in=[NetworkMembership.Role.ADMIN, NetworkMembership.Role.MEMBER],

33 ).exists()