2016-09-03 11:05:50 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2020-05-09 06:51:19 +00:00
|
|
|
from django.core.cache import cache
|
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
|
|
|
|
|
2020-05-18 06:55:16 +00:00
|
|
|
from common.mixins import CommonBulkSerializerMixin
|
2019-09-12 10:56:26 +00:00
|
|
|
from common.permissions import CanUpdateDeleteUser
|
2020-08-07 05:53:17 +00:00
|
|
|
from orgs.models import ROLE as ORG_ROLE
|
2020-10-14 07:17:06 +00:00
|
|
|
from ..models import User
|
2021-08-17 10:50:15 +00:00
|
|
|
from ..const import SystemOrOrgRole, PasswordStrategy
|
2019-07-04 08:44:46 +00:00
|
|
|
|
|
|
|
__all__ = [
|
2021-01-20 10:33:38 +00:00
|
|
|
'UserSerializer', 'UserRetrieveSerializer', 'MiniUserSerializer',
|
|
|
|
'InviteSerializer', 'ServiceAccountSerializer',
|
2019-07-04 08:44:46 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
|
2020-05-18 06:55:16 +00:00
|
|
|
class UserSerializer(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'))
|
2021-07-15 10:09:29 +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'))
|
2020-11-11 02:27:18 +00:00
|
|
|
can_update = serializers.SerializerMethodField(label=_('Can update'))
|
|
|
|
can_delete = serializers.SerializerMethodField(label=_('Can delete'))
|
2021-04-25 10:13:41 +00:00
|
|
|
can_public_key_auth = serializers.ReadOnlyField(source='can_use_ssh_key_login')
|
2021-03-02 11:18:25 +00:00
|
|
|
org_roles = serializers.ListField(
|
|
|
|
label=_('Organization role name'), allow_null=True, required=False,
|
|
|
|
child=serializers.ChoiceField(choices=ORG_ROLE.choices), default=["User"]
|
|
|
|
)
|
2021-08-17 10:50:15 +00:00
|
|
|
system_or_org_role = serializers.ChoiceField(read_only=True, choices=SystemOrOrgRole.choices, label=_('Role'))
|
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 + [
|
|
|
|
'email', 'wechat', 'phone', 'mfa_level',
|
2021-04-30 03:32:33 +00:00
|
|
|
'source', 'source_display', 'can_public_key_auth', 'need_update_password',
|
2021-04-29 11:10:45 +00:00
|
|
|
'mfa_enabled', 'is_valid', 'is_expired', 'is_active', # 布尔字段
|
|
|
|
'date_expired', 'date_joined', 'last_login', # 日期字段
|
|
|
|
'created_by', 'comment', # 通用字段
|
2021-08-12 08:44:06 +00:00
|
|
|
'is_wecom_bound', 'is_dingtalk_bound', 'is_feishu_bound',
|
2020-04-23 03:14:02 +00:00
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 包含不太常用的字段,可以没有
|
|
|
|
fields_verbose = fields_small + [
|
|
|
|
'total_role_display', 'org_role_display',
|
|
|
|
'mfa_level_display', 'mfa_force_enabled', 'is_first_login',
|
2021-08-17 10:50:15 +00:00
|
|
|
'date_password_last_updated', 'avatar_url', 'system_or_org_role'
|
2018-04-18 04:48:07 +00:00
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 外键的字段
|
|
|
|
fields_fk = ['role', 'role_display']
|
|
|
|
# 多对多字段
|
|
|
|
fields_m2m = ['groups', 'groups_display', 'org_roles']
|
|
|
|
# 在serializer 上定义的字段
|
|
|
|
fields_custom = ['can_update', 'can_delete', 'login_blocked', 'password_strategy']
|
|
|
|
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',
|
2020-12-08 12:51:02 +00:00
|
|
|
]
|
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},
|
|
|
|
'is_valid': {'label': _('Is valid')},
|
|
|
|
'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')},
|
2019-05-21 08:24:01 +00:00
|
|
|
}
|
2016-11-09 11:29:15 +00:00
|
|
|
|
2020-04-09 02:33:20 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.set_role_choices()
|
|
|
|
|
|
|
|
def set_role_choices(self):
|
2020-04-23 03:14:02 +00:00
|
|
|
role = self.fields.get('role')
|
|
|
|
if not role:
|
|
|
|
return
|
2020-04-09 10:58:22 +00:00
|
|
|
choices = role._choices
|
2020-07-20 02:42:22 +00:00
|
|
|
choices.pop(User.ROLE.APP, None)
|
2020-07-15 12:10:47 +00:00
|
|
|
request = self.context.get('request')
|
|
|
|
if request and hasattr(request, 'user') and not request.user.is_superuser:
|
2020-07-20 02:42:22 +00:00
|
|
|
choices.pop(User.ROLE.ADMIN, None)
|
|
|
|
choices.pop(User.ROLE.AUDITOR, None)
|
2020-04-09 10:58:22 +00:00
|
|
|
role._choices = choices
|
2020-04-09 02:33:20 +00:00
|
|
|
|
2019-07-02 06:17:56 +00:00
|
|
|
def validate_role(self, value):
|
|
|
|
request = self.context.get('request')
|
2020-07-20 02:42:22 +00:00
|
|
|
if not request.user.is_superuser and value != User.ROLE.USER:
|
|
|
|
role_display = User.ROLE.USER.label
|
2019-07-02 06:17:56 +00:00
|
|
|
msg = _("Role limit to {}".format(role_display))
|
|
|
|
raise serializers.ValidationError(msg)
|
|
|
|
return value
|
|
|
|
|
2021-08-17 08:01:27 +00:00
|
|
|
@property
|
|
|
|
def is_org_admin(self):
|
|
|
|
roles = []
|
|
|
|
role = self.initial_data.get('role')
|
|
|
|
if role:
|
|
|
|
roles.append(role)
|
|
|
|
org_roles = self.initial_data.get('org_roles')
|
|
|
|
if org_roles:
|
|
|
|
roles.extend(org_roles)
|
|
|
|
is_org_admin = User.ROLE.ADMIN.value in roles
|
|
|
|
return is_org_admin
|
|
|
|
|
2019-07-11 10:54:30 +00:00
|
|
|
def validate_password(self, password):
|
2019-06-25 06:32:25 +00:00
|
|
|
from ..utils import check_password_rules
|
2019-07-11 10:54:30 +00:00
|
|
|
password_strategy = self.initial_data.get('password_strategy')
|
2021-05-22 09:00:01 +00:00
|
|
|
if self.instance is None and password_strategy != self.PasswordStrategy.custom:
|
|
|
|
# 创建用户,使用邮件设置密码
|
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
|
2021-08-17 08:01:27 +00:00
|
|
|
if not check_password_rules(password, is_org_admin=self.is_org_admin):
|
2019-06-25 06:32:25 +00:00
|
|
|
msg = _('Password does not match security rules')
|
|
|
|
raise serializers.ValidationError(msg)
|
2019-07-11 10:54:30 +00:00
|
|
|
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
|
|
|
|
|
2019-09-12 10:56:26 +00:00
|
|
|
def validate(self, attrs):
|
|
|
|
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
|
2019-06-25 06:32:25 +00:00
|
|
|
|
2019-11-19 07:23:19 +00:00
|
|
|
def get_can_update(self, obj):
|
|
|
|
return CanUpdateDeleteUser.has_update_object_permission(
|
|
|
|
self.context['request'], self.context['view'], obj
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_can_delete(self, obj):
|
|
|
|
return CanUpdateDeleteUser.has_delete_object_permission(
|
|
|
|
self.context['request'], self.context['view'], obj
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-06-11 10:24:56 +00:00
|
|
|
class UserRetrieveSerializer(UserSerializer):
|
|
|
|
login_confirm_settings = serializers.PrimaryKeyRelatedField(read_only=True,
|
|
|
|
source='login_confirm_setting.reviewers', many=True)
|
|
|
|
|
|
|
|
class Meta(UserSerializer.Meta):
|
|
|
|
fields = UserSerializer.Meta.fields + ['login_confirm_settings']
|
|
|
|
|
|
|
|
|
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-01-20 10:33:38 +00:00
|
|
|
fields = ['id', 'name', 'username']
|
2020-05-13 03:05:58 +00:00
|
|
|
|
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
class InviteSerializer(serializers.Serializer):
|
|
|
|
user = serializers.PrimaryKeyRelatedField(
|
|
|
|
queryset=User.objects.exclude(role=User.ROLE.APP)
|
2020-06-03 10:20:33 +00:00
|
|
|
)
|
2021-01-20 10:33:38 +00:00
|
|
|
role = serializers.ChoiceField(choices=ORG_ROLE.choices)
|
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
|
2021-01-20 10:33:38 +00:00
|
|
|
fields = ['id', 'name', 'access_key']
|
|
|
|
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')
|
|
|
|
return '{}@serviceaccount.local'.format(name)
|
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()
|
|
|
|
if users.filter(email=email) or \
|
|
|
|
users.filter(username=username):
|
|
|
|
raise serializers.ValidationError(_('name not unique'), code='unique')
|
|
|
|
return name
|
|
|
|
|
|
|
|
def save(self, **kwargs):
|
|
|
|
self.validated_data['email'] = self.get_email()
|
|
|
|
self.validated_data['username'] = self.get_username()
|
|
|
|
self.validated_data['role'] = User.ROLE.APP
|
|
|
|
return super().save(**kwargs)
|
2020-05-28 09:47:18 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
def create(self, validated_data):
|
|
|
|
instance = super().create(validated_data)
|
|
|
|
instance.create_access_key()
|
2020-05-28 09:47:18 +00:00
|
|
|
return instance
|