2022-03-02 12:48:43 +00:00
|
|
|
from django.utils.translation import ugettext as _
|
2022-02-17 12:13:31 +00:00
|
|
|
from django.db.models import F, Value
|
|
|
|
from django.db.models.functions import Concat
|
|
|
|
|
|
|
|
from orgs.mixins.api import OrgBulkModelViewSet
|
|
|
|
from orgs.utils import current_org
|
2022-03-02 12:48:43 +00:00
|
|
|
from common.exceptions import JMSException
|
2022-02-17 12:13:31 +00:00
|
|
|
from .. import serializers
|
|
|
|
from ..models import RoleBinding, SystemRoleBinding, OrgRoleBinding
|
|
|
|
|
|
|
|
__all__ = ['RoleBindingViewSet', 'SystemRoleBindingViewSet', 'OrgRoleBindingViewSet']
|
|
|
|
|
|
|
|
|
|
|
|
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'
|
|
|
|
]
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2022-03-02 12:48:43 +00:00
|
|
|
queryset = super().get_queryset() \
|
2022-02-17 12:13:31 +00:00
|
|
|
.prefetch_related('user', 'role') \
|
|
|
|
.annotate(
|
|
|
|
user_display=Concat(
|
|
|
|
F('user__name'), Value('('),
|
|
|
|
F('user__username'), Value(')')
|
|
|
|
),
|
|
|
|
role_display=F('role__name')
|
|
|
|
)
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
|
|
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):
|
|
|
|
model = OrgRoleBinding
|
|
|
|
serializer_class = serializers.OrgRoleBindingSerializer
|
|
|
|
|
|
|
|
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)
|