From 81a5febfbc04cecbda7839972155efeb27d606df Mon Sep 17 00:00:00 2001 From: "Jiangjie.Bai" Date: Wed, 30 Mar 2022 19:30:27 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=B7=BB=E5=8A=A0=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E4=B8=8D=E8=83=BD=E8=87=AA=E6=9B=B4=E6=96=B0=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E9=80=BB=E8=BE=91=20&=20=E4=BF=AE=E5=A4=8D=E7=94=A8=E6=88=B7is?= =?UTF-8?q?=5Factive=E5=88=9B=E5=BB=BA=E5=A4=B1=E8=B4=A5=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix: 添加用户不能自更新字段逻辑 & 修复用户is_active创建失败的问题 fix: 添加用户不能自更新字段逻辑 & 修复用户is_active创建失败的问题 --- apps/users/serializers/user.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/apps/users/serializers/user.py b/apps/users/serializers/user.py index b998e8f6d..344b28ef0 100644 --- a/apps/users/serializers/user.py +++ b/apps/users/serializers/user.py @@ -132,6 +132,7 @@ class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializer 'date_joined', 'last_login', 'created_by', 'is_first_login', 'wecom_id', 'dingtalk_id', 'feishu_id' ] + disallow_self_update_fields = ['is_active'] extra_kwargs = { 'password': {'write_only': True, 'required': False, 'allow_null': True, 'allow_blank': True}, 'public_key': {'write_only': True}, @@ -180,7 +181,23 @@ class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializer attrs.pop(field, None) return attrs + def check_disallow_self_update_fields(self, attrs): + request = self.context.get('request') + if not request or not request.user.is_authenticated: + return attrs + if not self.instance: + return attrs + if request.user.id != self.instance.id: + return attrs + disallow_fields = set(list(attrs.keys())) & set(self.Meta.disallow_self_update_fields) + if not disallow_fields: + return attrs + # 用户自己不能更新自己的一些字段 + error = 'User Cannot self-update fields: {}'.format(disallow_fields) + raise serializers.ValidationError(error) + def validate(self, attrs): + attrs = self.check_disallow_self_update_fields(attrs) attrs = self.change_password_to_raw(attrs) attrs = self.clean_auth_fields(attrs) attrs.pop('password_strategy', None) @@ -205,17 +222,6 @@ class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializer field.set(value) return instance - def validate_is_active(self, is_active): - request = self.context.get('request') - if not request or not request.user.is_authenticated: - return is_active - - user = request.user - if user.id == self.instance.id and not is_active: - # 用户自己不能禁用启用自己 - raise serializers.ValidationError("Cannot inactive self") - return is_active - def update(self, instance, validated_data): save_handler = partial(super().update, instance) instance = self.save_and_set_custom_m2m_fields(validated_data, save_handler, created=False)