2022-02-17 12:13:31 +00:00
|
|
|
from django.db.models import F, Value
|
|
|
|
from django.db.models.functions import Concat
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2022-02-17 12:13:31 +00:00
|
|
|
|
2023-07-24 03:52:25 +00:00
|
|
|
from common.exceptions import JMSException
|
2022-02-17 12:13:31 +00:00
|
|
|
from orgs.mixins.api import OrgBulkModelViewSet
|
|
|
|
from orgs.utils import current_org
|
|
|
|
from .. import serializers
|
|
|
|
from ..models import RoleBinding, SystemRoleBinding, OrgRoleBinding
|
|
|
|
|
2022-03-16 08:31:06 +00:00
|
|
|
__all__ = [
|
|
|
|
'RoleBindingViewSet', 'SystemRoleBindingViewSet',
|
|
|
|
'OrgRoleBindingViewSet'
|
|
|
|
]
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RoleBindingViewSet(OrgBulkModelViewSet):
|
|
|
|
model = RoleBinding
|
|
|
|
serializer_class = serializers.RoleBindingSerializer
|
|
|
|
filterset_fields = [
|
|
|
|
'scope', 'user', 'role', 'org',
|
|
|
|
'user__name', 'user__username', 'role__name'
|
|
|
|
]
|
|
|
|
search_fields = [
|
|
|
|
'user__name', 'user__username', 'role__name'
|
|
|
|
]
|
|
|
|
|
2022-03-16 08:31:06 +00:00
|
|
|
def get_queryset(self):
|
2023-07-24 03:52:25 +00:00
|
|
|
queryset = self._get_queryset() \
|
2023-07-31 10:06:23 +00:00
|
|
|
.prefetch_related('user', 'role', 'org')
|
2022-02-17 12:13:31 +00:00
|
|
|
return queryset
|
|
|
|
|
2022-03-16 08:31:06 +00:00
|
|
|
def _get_queryset(self):
|
|
|
|
return super().get_queryset()
|
2022-03-16 07:59:52 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
class SystemRoleBindingViewSet(RoleBindingViewSet):
|
|
|
|
model = SystemRoleBinding
|
|
|
|
serializer_class = serializers.SystemRoleBindingSerializer
|
|
|
|
|
2022-03-02 12:48:43 +00:00
|
|
|
def perform_destroy(self, instance):
|
|
|
|
user = instance.user
|
|
|
|
role_qs = self.model.objects.filter(user=user)
|
|
|
|
if role_qs.count() == 1:
|
|
|
|
msg = _('{} at least one system role').format(user)
|
2022-03-07 07:03:57 +00:00
|
|
|
raise JMSException(code='system_role_delete_error', detail=msg)
|
|
|
|
return super().perform_destroy(instance)
|
2022-03-02 12:48:43 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
class OrgRoleBindingViewSet(RoleBindingViewSet):
|
|
|
|
serializer_class = serializers.OrgRoleBindingSerializer
|
|
|
|
|
2022-03-16 08:31:06 +00:00
|
|
|
def _get_queryset(self):
|
|
|
|
return OrgRoleBinding.objects.root_all()
|
2022-03-16 07:59:52 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
def perform_bulk_create(self, serializer):
|
|
|
|
validated_data = serializer.validated_data
|
|
|
|
bindings = [
|
2022-02-28 11:28:58 +00:00
|
|
|
OrgRoleBinding(
|
|
|
|
role=d['role'], user=d['user'],
|
|
|
|
org_id=current_org.id, scope='org'
|
|
|
|
)
|
2022-02-17 12:13:31 +00:00
|
|
|
for d in validated_data
|
|
|
|
]
|
|
|
|
OrgRoleBinding.objects.bulk_create(bindings, ignore_conflicts=True)
|