From 31d219524bfc059815b906dad750b388cdcae78c Mon Sep 17 00:00:00 2001 From: fit2bot <68588906+fit2bot@users.noreply.github.com> Date: Mon, 7 Mar 2022 11:21:25 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E7=94=A8=E6=88=B7roles=E5=BF=85=E5=A1=AB=E9=97=AE=E9=A2=98=20(?= =?UTF-8?q?#7745)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jiangjie.Bai --- apps/users/serializers/user.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/users/serializers/user.py b/apps/users/serializers/user.py index c89a01d21..d4380a0ff 100644 --- a/apps/users/serializers/user.py +++ b/apps/users/serializers/user.py @@ -6,6 +6,7 @@ from rest_framework import serializers from common.mixins import CommonBulkSerializerMixin from common.validators import PhoneValidator +from orgs.utils import current_org from rbac.permissions import RBACPermission from rbac.models import OrgRoleBinding, SystemRoleBinding from ..models import User @@ -20,10 +21,12 @@ __all__ = [ class RolesSerializerMixin(serializers.Serializer): system_roles = serializers.ManyRelatedField( + allow_empty=False, child_relation=serializers.PrimaryKeyRelatedField(queryset=Role.system_roles), label=_('System roles'), ) org_roles = serializers.ManyRelatedField( + required=False, child_relation=serializers.PrimaryKeyRelatedField(queryset=Role.org_roles), label=_('Org roles'), ) @@ -67,6 +70,16 @@ class RolesSerializerMixin(serializers.Serializer): self.pop_roles_if_need(fields) return fields + @staticmethod + def _validate_org_roles(attrs): + if current_org.is_root(): + attrs.pop('org_roles', None) + return attrs + org_roles = attrs.get('org_roles', None) + if not org_roles: + raise serializers.ValidationError({'org_roles': _('This field is required.')}) + return attrs + class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializers.ModelSerializer): password_strategy = serializers.ChoiceField( @@ -175,6 +188,7 @@ class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializer return attrs def validate(self, attrs): + attrs = self._validate_org_roles(attrs) attrs = self.change_password_to_raw(attrs) attrs = self.clean_auth_fields(attrs) attrs.pop('password_strategy', None) @@ -182,8 +196,7 @@ class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializer def save_and_set_custom_m2m_fields(self, validated_data, save_handler): m2m_values = { - f: validated_data.pop(f, None) - for f in self.custom_m2m_fields + f: validated_data.pop(f, None) for f in self.custom_m2m_fields } instance = save_handler(validated_data) for field_name, value in m2m_values.items():