2016-09-03 11:05:50 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2022-02-17 12:13:31 +00:00
|
|
|
from functools import partial
|
2016-09-13 13:45:10 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2016-09-03 11:05:50 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
2022-09-26 02:43:18 +00:00
|
|
|
from common.drf.serializers import CommonBulkSerializerMixin
|
2021-09-15 13:00:54 +00:00
|
|
|
from common.validators import PhoneValidator
|
2022-07-12 06:09:08 +00:00
|
|
|
from common.utils import pretty_string, get_logger
|
2022-05-11 07:57:48 +00:00
|
|
|
from common.drf.fields import EncryptedField
|
2022-03-08 03:40:46 +00:00
|
|
|
from rbac.builtin import BuiltinRole
|
2022-02-17 12:13:31 +00:00
|
|
|
from rbac.permissions import RBACPermission
|
2022-03-17 06:08:16 +00:00
|
|
|
from rbac.models import OrgRoleBinding, SystemRoleBinding, Role
|
2020-10-14 07:17:06 +00:00
|
|
|
from ..models import User
|
2022-02-17 12:13:31 +00:00
|
|
|
from ..const import PasswordStrategy
|
2019-07-04 08:44:46 +00:00
|
|
|
|
|
|
|
__all__ = [
|
2021-10-20 09:56:59 +00:00
|
|
|
'UserSerializer', 'MiniUserSerializer',
|
2021-01-20 10:33:38 +00:00
|
|
|
'InviteSerializer', 'ServiceAccountSerializer',
|
2019-07-04 08:44:46 +00:00
|
|
|
]
|
|
|
|
|
2022-07-12 06:09:08 +00:00
|
|
|
logger = get_logger(__file__)
|
|
|
|
|
2019-07-04 08:44:46 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
class RolesSerializerMixin(serializers.Serializer):
|
|
|
|
system_roles = serializers.ManyRelatedField(
|
|
|
|
child_relation=serializers.PrimaryKeyRelatedField(queryset=Role.system_roles),
|
|
|
|
label=_('System roles'),
|
|
|
|
)
|
|
|
|
org_roles = serializers.ManyRelatedField(
|
2022-03-07 03:21:25 +00:00
|
|
|
required=False,
|
2022-02-17 12:13:31 +00:00
|
|
|
child_relation=serializers.PrimaryKeyRelatedField(queryset=Role.org_roles),
|
|
|
|
label=_('Org roles'),
|
|
|
|
)
|
2022-06-30 10:21:12 +00:00
|
|
|
system_roles_display = serializers.SerializerMethodField(label=_('System roles display'))
|
|
|
|
org_roles_display = serializers.SerializerMethodField(label=_('Org roles display'))
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_system_roles_display(user):
|
|
|
|
return user.system_roles.display
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_org_roles_display(user):
|
|
|
|
return user.org_roles.display
|
|
|
|
|
|
|
|
def pop_roles_if_need(self, fields):
|
|
|
|
request = self.context.get('request')
|
|
|
|
view = self.context.get('view')
|
|
|
|
|
|
|
|
if not all([request, view, hasattr(view, 'action')]):
|
|
|
|
return fields
|
|
|
|
if request.user.is_anonymous:
|
|
|
|
return fields
|
|
|
|
|
|
|
|
action = view.action or 'list'
|
2022-03-22 08:14:25 +00:00
|
|
|
if action in ('partial_bulk_update', 'bulk_update', 'partial_update', 'update'):
|
|
|
|
action = 'create'
|
2022-02-17 12:13:31 +00:00
|
|
|
model_cls_field_mapper = {
|
|
|
|
SystemRoleBinding: ['system_roles', 'system_roles_display'],
|
|
|
|
OrgRoleBinding: ['org_roles', 'system_roles_display']
|
|
|
|
}
|
|
|
|
|
|
|
|
for model_cls, fields_names in model_cls_field_mapper.items():
|
|
|
|
perms = RBACPermission.parse_action_model_perms(action, model_cls)
|
|
|
|
if request.user.has_perms(perms):
|
|
|
|
continue
|
|
|
|
# 没有权限就去掉
|
|
|
|
for field_name in fields_names:
|
|
|
|
fields.pop(field_name, None)
|
|
|
|
return fields
|
|
|
|
|
|
|
|
def get_fields(self):
|
|
|
|
fields = super().get_fields()
|
|
|
|
self.pop_roles_if_need(fields)
|
|
|
|
return fields
|
|
|
|
|
|
|
|
|
|
|
|
class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializers.ModelSerializer):
|
2020-04-09 02:33:20 +00:00
|
|
|
password_strategy = serializers.ChoiceField(
|
2021-05-22 09:00:01 +00:00
|
|
|
choices=PasswordStrategy.choices, default=PasswordStrategy.email, required=False,
|
|
|
|
write_only=True, label=_('Password strategy')
|
2020-04-09 02:33:20 +00:00
|
|
|
)
|
2021-03-11 13:15:45 +00:00
|
|
|
mfa_enabled = serializers.BooleanField(read_only=True, label=_('MFA enabled'))
|
|
|
|
mfa_force_enabled = serializers.BooleanField(read_only=True, label=_('MFA force enabled'))
|
2022-02-17 12:13:31 +00:00
|
|
|
mfa_level_display = serializers.ReadOnlyField(
|
|
|
|
source='get_mfa_level_display', label=_('MFA level display')
|
|
|
|
)
|
2021-03-11 13:15:45 +00:00
|
|
|
login_blocked = serializers.BooleanField(read_only=True, label=_('Login blocked'))
|
|
|
|
is_expired = serializers.BooleanField(read_only=True, label=_('Is expired'))
|
2021-10-20 09:56:59 +00:00
|
|
|
can_public_key_auth = serializers.ReadOnlyField(
|
2022-02-17 12:13:31 +00:00
|
|
|
source='can_use_ssh_key_login', label=_('Can public key authentication')
|
2021-03-02 11:18:25 +00:00
|
|
|
)
|
2022-05-16 09:28:02 +00:00
|
|
|
password = EncryptedField(
|
|
|
|
label=_('Password'), required=False, allow_blank=True, allow_null=True, max_length=1024
|
|
|
|
)
|
2022-02-17 12:13:31 +00:00
|
|
|
# Todo: 这里看看该怎么搞
|
|
|
|
# can_update = serializers.SerializerMethodField(label=_('Can update'))
|
|
|
|
# can_delete = serializers.SerializerMethodField(label=_('Can delete'))
|
2022-03-08 03:40:46 +00:00
|
|
|
custom_m2m_fields = {
|
|
|
|
'system_roles': [BuiltinRole.system_user],
|
|
|
|
'org_roles': [BuiltinRole.org_user]
|
|
|
|
}
|
2020-05-09 06:51:19 +00:00
|
|
|
|
2016-09-06 08:40:44 +00:00
|
|
|
class Meta:
|
|
|
|
model = User
|
2020-04-23 03:14:02 +00:00
|
|
|
# mini 是指能识别对象的最小单元
|
|
|
|
fields_mini = ['id', 'name', 'username']
|
2021-04-29 11:10:45 +00:00
|
|
|
# 只能写的字段, 这个虽然无法在框架上生效,但是更多对我们是提醒
|
|
|
|
fields_write_only = [
|
|
|
|
'password', 'public_key',
|
|
|
|
]
|
2020-04-23 03:14:02 +00:00
|
|
|
# small 指的是 不需要计算的直接能从一张表中获取到的数据
|
2021-04-29 11:10:45 +00:00
|
|
|
fields_small = fields_mini + fields_write_only + [
|
2022-02-17 12:13:31 +00:00
|
|
|
'email', 'wechat', 'phone', 'mfa_level', 'source', 'source_display',
|
|
|
|
'can_public_key_auth', 'need_update_password',
|
2022-02-18 08:25:54 +00:00
|
|
|
'mfa_enabled', 'is_service_account', 'is_valid', 'is_expired', 'is_active', # 布尔字段
|
2021-04-29 11:10:45 +00:00
|
|
|
'date_expired', 'date_joined', 'last_login', # 日期字段
|
|
|
|
'created_by', 'comment', # 通用字段
|
2021-09-16 10:59:15 +00:00
|
|
|
'is_wecom_bound', 'is_dingtalk_bound', 'is_feishu_bound', 'is_otp_secret_key_bound',
|
2021-09-15 10:20:38 +00:00
|
|
|
'wecom_id', 'dingtalk_id', 'feishu_id'
|
2020-04-23 03:14:02 +00:00
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 包含不太常用的字段,可以没有
|
|
|
|
fields_verbose = fields_small + [
|
|
|
|
'mfa_level_display', 'mfa_force_enabled', 'is_first_login',
|
2022-02-17 12:13:31 +00:00
|
|
|
'date_password_last_updated', 'avatar_url',
|
2018-04-18 04:48:07 +00:00
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 外键的字段
|
2022-02-17 12:13:31 +00:00
|
|
|
fields_fk = []
|
2021-04-29 11:10:45 +00:00
|
|
|
# 多对多字段
|
2022-02-17 12:13:31 +00:00
|
|
|
fields_m2m = [
|
|
|
|
'groups', 'groups_display', 'system_roles', 'org_roles',
|
|
|
|
'system_roles_display', 'org_roles_display'
|
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 在serializer 上定义的字段
|
2022-02-17 12:13:31 +00:00
|
|
|
fields_custom = ['login_blocked', 'password_strategy']
|
2021-04-29 11:10:45 +00:00
|
|
|
fields = fields_verbose + fields_fk + fields_m2m + fields_custom
|
2020-04-23 03:14:02 +00:00
|
|
|
|
2020-12-08 12:51:02 +00:00
|
|
|
read_only_fields = [
|
2021-02-02 08:28:27 +00:00
|
|
|
'date_joined', 'last_login', 'created_by', 'is_first_login',
|
2021-10-28 06:56:56 +00:00
|
|
|
'wecom_id', 'dingtalk_id', 'feishu_id'
|
2020-12-08 12:51:02 +00:00
|
|
|
]
|
2022-03-30 11:30:27 +00:00
|
|
|
disallow_self_update_fields = ['is_active']
|
2019-05-21 08:24:01 +00:00
|
|
|
extra_kwargs = {
|
2019-07-11 10:54:30 +00:00
|
|
|
'password': {'write_only': True, 'required': False, 'allow_null': True, 'allow_blank': True},
|
2019-06-25 06:32:25 +00:00
|
|
|
'public_key': {'write_only': True},
|
2019-05-21 08:24:01 +00:00
|
|
|
'is_first_login': {'label': _('Is first login'), 'read_only': True},
|
2022-06-30 10:21:12 +00:00
|
|
|
'is_active': {'label': _('Is active')},
|
2019-05-21 08:24:01 +00:00
|
|
|
'is_valid': {'label': _('Is valid')},
|
2022-03-02 12:48:43 +00:00
|
|
|
'is_service_account': {'label': _('Is service account')},
|
2019-05-21 08:24:01 +00:00
|
|
|
'is_expired': {'label': _('Is expired')},
|
|
|
|
'avatar_url': {'label': _('Avatar url')},
|
2019-09-12 10:56:26 +00:00
|
|
|
'created_by': {'read_only': True, 'allow_blank': True},
|
2020-04-23 03:14:02 +00:00
|
|
|
'groups_display': {'label': _('Groups name')},
|
|
|
|
'source_display': {'label': _('Source name')},
|
2020-08-07 05:53:17 +00:00
|
|
|
'org_role_display': {'label': _('Organization role name')},
|
|
|
|
'role_display': {'label': _('Super role name')},
|
2020-11-11 02:27:18 +00:00
|
|
|
'total_role_display': {'label': _('Total role name')},
|
2021-03-02 11:18:25 +00:00
|
|
|
'role': {'default': "User"},
|
2021-08-16 09:28:47 +00:00
|
|
|
'is_wecom_bound': {'label': _('Is wecom bound')},
|
|
|
|
'is_dingtalk_bound': {'label': _('Is dingtalk bound')},
|
|
|
|
'is_feishu_bound': {'label': _('Is feishu bound')},
|
2021-09-16 10:59:15 +00:00
|
|
|
'is_otp_secret_key_bound': {'label': _('Is OTP bound')},
|
2021-09-15 13:00:54 +00:00
|
|
|
'phone': {'validators': [PhoneValidator()]},
|
2022-02-17 12:13:31 +00:00
|
|
|
'system_role_display': {'label': _('System role name')},
|
2019-05-21 08:24:01 +00:00
|
|
|
}
|
2016-11-09 11:29:15 +00:00
|
|
|
|
2019-07-11 10:54:30 +00:00
|
|
|
def validate_password(self, password):
|
|
|
|
password_strategy = self.initial_data.get('password_strategy')
|
2021-08-20 01:52:36 +00:00
|
|
|
if self.instance is None and password_strategy != PasswordStrategy.custom:
|
2021-05-22 09:00:01 +00:00
|
|
|
# 创建用户,使用邮件设置密码
|
2019-07-11 10:54:30 +00:00
|
|
|
return
|
2021-05-22 09:00:01 +00:00
|
|
|
if self.instance and not password:
|
|
|
|
# 更新用户, 未设置密码
|
2019-07-11 10:54:30 +00:00
|
|
|
return
|
|
|
|
return password
|
2019-06-25 06:32:25 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2019-09-12 10:56:26 +00:00
|
|
|
def change_password_to_raw(attrs):
|
|
|
|
password = attrs.pop('password', None)
|
2019-06-25 06:32:25 +00:00
|
|
|
if password:
|
2019-09-12 10:56:26 +00:00
|
|
|
attrs['password_raw'] = password
|
|
|
|
return attrs
|
2019-06-25 06:32:25 +00:00
|
|
|
|
2020-01-20 03:27:34 +00:00
|
|
|
@staticmethod
|
|
|
|
def clean_auth_fields(attrs):
|
|
|
|
for field in ('password', 'public_key'):
|
|
|
|
value = attrs.get(field)
|
|
|
|
if not value:
|
|
|
|
attrs.pop(field, None)
|
|
|
|
return attrs
|
|
|
|
|
2022-03-30 11:30:27 +00:00
|
|
|
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
|
|
|
|
# 用户自己不能更新自己的一些字段
|
2022-07-12 06:09:08 +00:00
|
|
|
logger.debug('Disallow update self fields: %s', disallow_fields)
|
|
|
|
for field in disallow_fields:
|
|
|
|
attrs.pop(field, None)
|
|
|
|
return attrs
|
2022-03-30 11:30:27 +00:00
|
|
|
|
2019-09-12 10:56:26 +00:00
|
|
|
def validate(self, attrs):
|
2022-03-30 11:30:27 +00:00
|
|
|
attrs = self.check_disallow_self_update_fields(attrs)
|
2019-09-12 10:56:26 +00:00
|
|
|
attrs = self.change_password_to_raw(attrs)
|
2020-01-20 03:27:34 +00:00
|
|
|
attrs = self.clean_auth_fields(attrs)
|
2020-04-09 02:33:20 +00:00
|
|
|
attrs.pop('password_strategy', None)
|
2019-09-12 10:56:26 +00:00
|
|
|
return attrs
|
2022-02-17 12:13:31 +00:00
|
|
|
|
2022-03-08 03:40:46 +00:00
|
|
|
def save_and_set_custom_m2m_fields(self, validated_data, save_handler, created):
|
|
|
|
m2m_values = {}
|
|
|
|
for f, default_roles in self.custom_m2m_fields.items():
|
|
|
|
roles = validated_data.pop(f, None)
|
|
|
|
if created and not roles:
|
|
|
|
roles = [
|
|
|
|
Role.objects.filter(id=role.id).first()
|
|
|
|
for role in default_roles
|
|
|
|
]
|
|
|
|
m2m_values[f] = roles
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
instance = save_handler(validated_data)
|
|
|
|
for field_name, value in m2m_values.items():
|
|
|
|
if value is None:
|
|
|
|
continue
|
|
|
|
field = getattr(instance, field_name)
|
|
|
|
field.set(value)
|
|
|
|
return instance
|
2019-06-25 06:32:25 +00:00
|
|
|
|
2021-09-13 11:40:25 +00:00
|
|
|
def update(self, instance, validated_data):
|
2022-02-17 12:13:31 +00:00
|
|
|
save_handler = partial(super().update, instance)
|
2022-03-08 03:40:46 +00:00
|
|
|
instance = self.save_and_set_custom_m2m_fields(validated_data, save_handler, created=False)
|
2022-02-17 12:13:31 +00:00
|
|
|
return instance
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
save_handler = super().create
|
2022-03-08 03:40:46 +00:00
|
|
|
instance = self.save_and_set_custom_m2m_fields(validated_data, save_handler, created=True)
|
2022-02-17 12:13:31 +00:00
|
|
|
return instance
|
|
|
|
|
|
|
|
|
|
|
|
class UserRetrieveSerializer(UserSerializer):
|
|
|
|
login_confirm_settings = serializers.PrimaryKeyRelatedField(
|
|
|
|
read_only=True, source='login_confirm_setting.reviewers', many=True
|
|
|
|
)
|
2021-09-13 11:40:25 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
class Meta(UserSerializer.Meta):
|
|
|
|
fields = UserSerializer.Meta.fields + ['login_confirm_settings']
|
2021-09-13 11:40:25 +00:00
|
|
|
|
2019-11-19 07:23:19 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
class MiniUserSerializer(serializers.ModelSerializer):
|
2018-01-23 02:36:20 +00:00
|
|
|
class Meta:
|
|
|
|
model = User
|
2021-08-27 08:38:23 +00:00
|
|
|
fields = UserSerializer.Meta.fields_mini
|
2020-05-13 03:05:58 +00:00
|
|
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
class InviteSerializer(RolesSerializerMixin, serializers.Serializer):
|
|
|
|
users = serializers.PrimaryKeyRelatedField(
|
|
|
|
queryset=User.get_nature_users(), many=True, label=_('Select users'),
|
2022-02-22 11:48:53 +00:00
|
|
|
help_text=_('For security, only list several users')
|
2020-06-03 10:20:33 +00:00
|
|
|
)
|
2022-02-17 12:13:31 +00:00
|
|
|
system_roles = None
|
|
|
|
system_roles_display = None
|
|
|
|
org_roles_display = None
|
2020-06-04 09:24:31 +00:00
|
|
|
|
2020-05-28 08:10:28 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
class ServiceAccountSerializer(serializers.ModelSerializer):
|
2020-05-28 08:10:28 +00:00
|
|
|
class Meta:
|
|
|
|
model = User
|
2022-03-02 12:48:43 +00:00
|
|
|
fields = ['id', 'name', 'access_key', 'comment']
|
2021-01-20 10:33:38 +00:00
|
|
|
read_only_fields = ['access_key']
|
2020-05-28 08:10:28 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
from authentication.serializers import AccessKeySerializer
|
|
|
|
self.fields['access_key'] = AccessKeySerializer(read_only=True)
|
2020-05-28 08:10:28 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
def get_username(self):
|
|
|
|
return self.initial_data.get('name')
|
2020-05-28 08:10:28 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
def get_email(self):
|
|
|
|
name = self.initial_data.get('name')
|
2022-03-30 11:07:49 +00:00
|
|
|
name_max_length = 128 - len(User.service_account_email_suffix)
|
|
|
|
name = pretty_string(name, max_length=name_max_length, ellipsis_str='-')
|
|
|
|
return '{}{}'.format(name, User.service_account_email_suffix)
|
2020-05-28 09:47:18 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
def validate_name(self, name):
|
|
|
|
email = self.get_email()
|
|
|
|
username = self.get_username()
|
|
|
|
if self.instance:
|
|
|
|
users = User.objects.exclude(id=self.instance.id)
|
|
|
|
else:
|
|
|
|
users = User.objects.all()
|
2022-02-17 12:13:31 +00:00
|
|
|
if users.filter(email=email) or users.filter(username=username):
|
2021-01-20 10:33:38 +00:00
|
|
|
raise serializers.ValidationError(_('name not unique'), code='unique')
|
|
|
|
return name
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
2022-03-07 03:40:32 +00:00
|
|
|
name = validated_data['name']
|
2022-03-30 11:07:49 +00:00
|
|
|
email = self.get_email()
|
2022-03-07 03:40:32 +00:00
|
|
|
comment = validated_data.get('comment', '')
|
2022-03-30 11:07:49 +00:00
|
|
|
user, ak = User.create_service_account(name, email, comment)
|
2022-02-18 06:28:28 +00:00
|
|
|
return user
|