2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2022-02-17 12:13:31 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
2023-07-31 10:06:23 +00:00
|
|
|
from common.serializers.fields import ObjectRelatedField
|
|
|
|
from users.models import User
|
2022-02-17 12:13:31 +00:00
|
|
|
from orgs.serializers import CurrentOrgDefault
|
|
|
|
from ..models import RoleBinding, SystemRoleBinding, OrgRoleBinding
|
|
|
|
|
|
|
|
__all__ = [
|
2023-07-24 03:52:25 +00:00
|
|
|
'RoleBindingSerializer', 'OrgRoleBindingSerializer', 'SystemRoleBindingSerializer'
|
2022-02-17 12:13:31 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
class RoleBindingSerializer(serializers.ModelSerializer):
|
2023-07-31 10:06:23 +00:00
|
|
|
user = ObjectRelatedField(
|
|
|
|
required=False, queryset=User.objects,
|
|
|
|
label=_('User'), attrs=('id', 'name', 'username')
|
|
|
|
)
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
class Meta:
|
|
|
|
model = RoleBinding
|
|
|
|
fields = [
|
2023-07-31 10:06:23 +00:00
|
|
|
'id', 'user', 'role', 'scope', 'org', 'org_name',
|
2022-02-17 12:13:31 +00:00
|
|
|
]
|
|
|
|
read_only_fields = ['scope']
|
|
|
|
extra_kwargs = {
|
2022-03-16 07:59:52 +00:00
|
|
|
'org_name': {'label': _("Org name")}
|
2022-02-17 12:13:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
class SystemRoleBindingSerializer(RoleBindingSerializer):
|
|
|
|
org = None
|
|
|
|
|
|
|
|
class Meta(RoleBindingSerializer.Meta):
|
|
|
|
model = SystemRoleBinding
|
|
|
|
|
|
|
|
def get_field_names(self, *args):
|
|
|
|
names = super().get_field_names(*args)
|
|
|
|
return list(set(names) - {'org'})
|
|
|
|
|
|
|
|
|
|
|
|
class OrgRoleBindingSerializer(RoleBindingSerializer):
|
|
|
|
org = serializers.PrimaryKeyRelatedField(
|
|
|
|
default=CurrentOrgDefault(), label=_("Organization"), read_only=True
|
|
|
|
)
|
|
|
|
|
|
|
|
class Meta(RoleBindingSerializer.Meta):
|
|
|
|
model = OrgRoleBinding
|
|
|
|
validators = []
|
|
|
|
|
|
|
|
def validate(self, attrs):
|
|
|
|
data = self.initial_data
|
|
|
|
many = isinstance(data, list)
|
|
|
|
if not many:
|
|
|
|
user = attrs.get('user')
|
|
|
|
role = attrs.get('role')
|
|
|
|
role_bindings = OrgRoleBinding.objects.filter(user=user, role=role)
|
|
|
|
|
|
|
|
if not self.instance and role_bindings.exists():
|
|
|
|
raise serializers.ValidationError({'role': _('Has bound this role')})
|
|
|
|
return attrs
|