2016-09-03 11:05:50 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2023-04-07 13:25:26 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
from functools import partial
|
2022-12-07 10:58:57 +00:00
|
|
|
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2016-09-03 11:05:50 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
2023-12-05 03:16:34 +00:00
|
|
|
from common.serializers import CommonBulkSerializerMixin, ResourceLabelsMixin
|
2023-04-10 06:19:28 +00:00
|
|
|
from common.serializers.fields import (
|
|
|
|
EncryptedField, ObjectRelatedField, LabeledChoiceField, PhoneField
|
|
|
|
)
|
2022-07-12 06:09:08 +00:00
|
|
|
from common.utils import pretty_string, get_logger
|
2022-12-07 10:58:57 +00:00
|
|
|
from common.validators import PhoneValidator
|
2022-03-08 03:40:46 +00:00
|
|
|
from rbac.builtin import BuiltinRole
|
2022-03-17 06:08:16 +00:00
|
|
|
from rbac.models import OrgRoleBinding, SystemRoleBinding, Role
|
2022-12-07 10:58:57 +00:00
|
|
|
from rbac.permissions import RBACPermission
|
2022-02-17 12:13:31 +00:00
|
|
|
from ..const import PasswordStrategy
|
2022-12-07 10:58:57 +00:00
|
|
|
from ..models import User
|
2019-07-04 08:44:46 +00:00
|
|
|
|
|
|
|
__all__ = [
|
2022-11-11 07:04:31 +00:00
|
|
|
"UserSerializer",
|
|
|
|
"MiniUserSerializer",
|
|
|
|
"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
|
|
|
|
2023-02-01 03:26:57 +00:00
|
|
|
def default_system_roles():
|
|
|
|
return [BuiltinRole.system_user.get_role()]
|
|
|
|
|
|
|
|
|
|
|
|
def default_org_roles():
|
|
|
|
return [BuiltinRole.org_user.get_role()]
|
|
|
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
class RolesSerializerMixin(serializers.Serializer):
|
2022-12-26 07:01:51 +00:00
|
|
|
system_roles = ObjectRelatedField(
|
|
|
|
queryset=Role.system_roles, attrs=('id', 'display_name'),
|
2023-02-01 03:26:57 +00:00
|
|
|
label=_("System roles"), many=True, default=default_system_roles
|
2022-12-26 07:01:51 +00:00
|
|
|
)
|
|
|
|
org_roles = ObjectRelatedField(
|
2023-02-22 12:30:43 +00:00
|
|
|
queryset=Role.org_roles, attrs=('id', 'display_name', 'name'),
|
2023-02-01 03:26:57 +00:00
|
|
|
label=_("Org roles"), many=True, required=False,
|
|
|
|
default=default_org_roles
|
2022-12-26 07:01:51 +00:00
|
|
|
)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
def pop_roles_if_need(self, fields):
|
2022-11-11 07:04:31 +00:00
|
|
|
request = self.context.get("request")
|
|
|
|
view = self.context.get("view")
|
2022-02-17 12:13:31 +00:00
|
|
|
|
2022-11-11 07:04:31 +00:00
|
|
|
if not all([request, view, hasattr(view, "action")]):
|
2022-02-17 12:13:31 +00:00
|
|
|
return fields
|
|
|
|
if request.user.is_anonymous:
|
|
|
|
return fields
|
|
|
|
|
|
|
|
model_cls_field_mapper = {
|
2022-12-07 10:58:57 +00:00
|
|
|
SystemRoleBinding: ["system_roles"],
|
|
|
|
OrgRoleBinding: ["org_roles"],
|
2022-02-17 12:13:31 +00:00
|
|
|
}
|
|
|
|
|
2023-08-23 07:47:22 +00:00
|
|
|
update_actions = ("partial_bulk_update", "bulk_update", "partial_update", "update")
|
|
|
|
action = view.action or "list"
|
|
|
|
if action in update_actions:
|
|
|
|
action = "create"
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2023-12-05 03:16:34 +00:00
|
|
|
class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, ResourceLabelsMixin, serializers.ModelSerializer):
|
2022-12-07 10:58:57 +00:00
|
|
|
password_strategy = LabeledChoiceField(
|
2022-11-11 07:04:31 +00:00
|
|
|
choices=PasswordStrategy.choices,
|
|
|
|
default=PasswordStrategy.email,
|
2023-03-14 08:07:08 +00:00
|
|
|
allow_null=True,
|
2022-11-11 07:04:31 +00:00
|
|
|
required=False,
|
|
|
|
label=_("Password strategy"),
|
|
|
|
)
|
|
|
|
mfa_enabled = serializers.BooleanField(read_only=True, label=_("MFA enabled"))
|
|
|
|
mfa_force_enabled = serializers.BooleanField(
|
|
|
|
read_only=True, label=_("MFA force enabled")
|
2020-04-09 02:33:20 +00:00
|
|
|
)
|
2022-11-11 07:04:31 +00:00
|
|
|
login_blocked = serializers.BooleanField(read_only=True, label=_("Login blocked"))
|
|
|
|
is_expired = serializers.BooleanField(read_only=True, label=_("Is expired"))
|
2023-02-22 12:30:43 +00:00
|
|
|
is_valid = serializers.BooleanField(read_only=True, label=_("Is valid"))
|
|
|
|
is_otp_secret_key_bound = serializers.BooleanField(read_only=True, label=_("Is OTP bound"))
|
2022-12-26 11:16:11 +00:00
|
|
|
can_public_key_auth = serializers.BooleanField(
|
|
|
|
source="can_use_ssh_key_login", label=_("Can public key authentication"),
|
|
|
|
read_only=True
|
2021-03-02 11:18:25 +00:00
|
|
|
)
|
2023-10-10 09:52:52 +00:00
|
|
|
password = EncryptedField(label=_("Password"), required=False, allow_blank=True, allow_null=True, max_length=1024, )
|
2023-04-10 06:19:28 +00:00
|
|
|
phone = PhoneField(
|
2023-04-10 09:24:17 +00:00
|
|
|
validators=[PhoneValidator()], required=False, allow_blank=True, allow_null=True, label=_("Phone")
|
2023-04-10 06:19:28 +00:00
|
|
|
)
|
2022-03-08 03:40:46 +00:00
|
|
|
custom_m2m_fields = {
|
2022-11-11 07:04:31 +00:00
|
|
|
"system_roles": [BuiltinRole.system_user],
|
|
|
|
"org_roles": [BuiltinRole.org_user],
|
2022-03-08 03:40:46 +00:00
|
|
|
}
|
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 是指能识别对象的最小单元
|
2022-11-11 07:04:31 +00:00
|
|
|
fields_mini = ["id", "name", "username"]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 只能写的字段, 这个虽然无法在框架上生效,但是更多对我们是提醒
|
|
|
|
fields_write_only = [
|
2022-12-07 10:58:57 +00:00
|
|
|
"password", "public_key",
|
2021-04-29 11:10:45 +00:00
|
|
|
]
|
2020-04-23 03:14:02 +00:00
|
|
|
# small 指的是 不需要计算的直接能从一张表中获取到的数据
|
2022-12-07 10:58:57 +00:00
|
|
|
fields_small = fields_mini + fields_write_only + [
|
|
|
|
"email", "wechat", "phone", "mfa_level", "source",
|
2023-11-29 09:45:44 +00:00
|
|
|
"wecom_id", "dingtalk_id", "feishu_id", "slack_id",
|
2023-02-03 04:22:27 +00:00
|
|
|
"created_by", "updated_by", "comment", # 通用字段
|
|
|
|
]
|
|
|
|
fields_date = [
|
2023-10-10 09:52:52 +00:00
|
|
|
"date_expired", "date_joined", "last_login",
|
|
|
|
"date_updated", "date_api_key_last_used",
|
2023-02-03 04:22:27 +00:00
|
|
|
]
|
|
|
|
fields_bool = [
|
2023-06-15 04:15:04 +00:00
|
|
|
"is_superuser", "is_org_admin",
|
2022-12-07 10:58:57 +00:00
|
|
|
"is_service_account", "is_valid",
|
|
|
|
"is_expired", "is_active", # 布尔字段
|
|
|
|
"is_otp_secret_key_bound", "can_public_key_auth",
|
2023-02-03 04:22:27 +00:00
|
|
|
"mfa_enabled", "need_update_password",
|
2022-12-07 10:58:57 +00:00
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 包含不太常用的字段,可以没有
|
2023-02-03 04:22:27 +00:00
|
|
|
fields_verbose = fields_small + fields_date + fields_bool + [
|
2023-02-01 10:45:51 +00:00
|
|
|
"mfa_force_enabled", "is_first_login",
|
|
|
|
"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
|
|
|
# 多对多字段
|
2023-12-05 03:16:34 +00:00
|
|
|
fields_m2m = ["groups", "system_roles", "org_roles", "labels"]
|
2021-04-29 11:10:45 +00:00
|
|
|
# 在serializer 上定义的字段
|
2022-11-11 07:04: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
|
2023-03-10 07:52:07 +00:00
|
|
|
fields_unexport = ["avatar_url", ]
|
2020-04-23 03:14:02 +00:00
|
|
|
|
2020-12-08 12:51:02 +00:00
|
|
|
read_only_fields = [
|
2022-12-07 10:58:57 +00:00
|
|
|
"date_joined", "last_login", "created_by",
|
|
|
|
"is_first_login", "wecom_id", "dingtalk_id",
|
2023-10-10 09:52:52 +00:00
|
|
|
"feishu_id", "date_api_key_last_used",
|
2020-12-08 12:51:02 +00:00
|
|
|
]
|
2023-08-23 07:47:22 +00:00
|
|
|
disallow_self_update_fields = ["is_active", "system_roles", "org_roles"]
|
2019-05-21 08:24:01 +00:00
|
|
|
extra_kwargs = {
|
2022-11-11 07:04:31 +00:00
|
|
|
"password": {
|
|
|
|
"write_only": True,
|
|
|
|
"required": False,
|
|
|
|
"allow_null": True,
|
|
|
|
"allow_blank": True,
|
|
|
|
},
|
|
|
|
"public_key": {"write_only": True},
|
|
|
|
"is_first_login": {"label": _("Is first login"), "read_only": True},
|
|
|
|
"is_active": {"label": _("Is active")},
|
|
|
|
"is_valid": {"label": _("Is valid")},
|
|
|
|
"is_service_account": {"label": _("Is service account")},
|
2023-08-08 02:16:23 +00:00
|
|
|
"is_org_admin": {"label": _("Is org admin")},
|
2022-11-11 07:04:31 +00:00
|
|
|
"is_expired": {"label": _("Is expired")},
|
|
|
|
"avatar_url": {"label": _("Avatar url")},
|
|
|
|
"created_by": {"read_only": True, "allow_blank": True},
|
|
|
|
"role": {"default": "User"},
|
|
|
|
"is_otp_secret_key_bound": {"label": _("Is OTP bound")},
|
2023-03-10 07:52:07 +00:00
|
|
|
'mfa_level': {'label': _("MFA level")},
|
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):
|
2022-11-11 07:04:31 +00:00
|
|
|
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):
|
2022-11-11 07:04:31 +00:00
|
|
|
password = attrs.pop("password", None)
|
2019-06-25 06:32:25 +00:00
|
|
|
if password:
|
2022-11-11 07:04:31 +00:00
|
|
|
attrs["password_raw"] = password
|
2019-09-12 10:56:26 +00:00
|
|
|
return attrs
|
2019-06-25 06:32:25 +00:00
|
|
|
|
2020-01-20 03:27:34 +00:00
|
|
|
@staticmethod
|
|
|
|
def clean_auth_fields(attrs):
|
2022-11-11 07:04:31 +00:00
|
|
|
for field in ("password", "public_key"):
|
2020-01-20 03:27:34 +00:00
|
|
|
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):
|
2022-11-11 07:04:31 +00:00
|
|
|
request = self.context.get("request")
|
2022-03-30 11:30:27 +00:00
|
|
|
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
|
2022-11-11 07:04:31 +00:00
|
|
|
disallow_fields = set(list(attrs.keys())) & set(
|
|
|
|
self.Meta.disallow_self_update_fields
|
|
|
|
)
|
2022-03-30 11:30:27 +00:00
|
|
|
if not disallow_fields:
|
|
|
|
return attrs
|
|
|
|
# 用户自己不能更新自己的一些字段
|
2022-11-11 07:04:31 +00:00
|
|
|
logger.debug("Disallow update self fields: %s", disallow_fields)
|
2022-07-12 06:09:08 +00:00
|
|
|
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)
|
2022-11-11 07:04:31 +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 = [
|
2022-11-11 07:04:31 +00:00
|
|
|
Role.objects.filter(id=role.id).first() for role in default_roles
|
2022-03-08 03:40:46 +00:00
|
|
|
]
|
|
|
|
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-11-11 07:04:31 +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-11-11 07:04:31 +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
|
|
|
|
|
2023-12-05 03:16:34 +00:00
|
|
|
@classmethod
|
|
|
|
def setup_eager_loading(cls, queryset):
|
|
|
|
queryset = queryset.prefetch_related('groups', 'labels', 'labels__label')
|
|
|
|
return queryset
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
class UserRetrieveSerializer(UserSerializer):
|
|
|
|
login_confirm_settings = serializers.PrimaryKeyRelatedField(
|
2022-11-11 07:04:31 +00:00
|
|
|
read_only=True, source="login_confirm_setting.reviewers", many=True
|
2022-02-17 12:13:31 +00:00
|
|
|
)
|
2021-09-13 11:40:25 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
class Meta(UserSerializer.Meta):
|
2022-11-11 07:04:31 +00:00
|
|
|
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(
|
2022-11-11 07:04:31 +00:00
|
|
|
queryset=User.get_nature_users(),
|
|
|
|
many=True,
|
|
|
|
label=_("Select users"),
|
|
|
|
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
|
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-11-11 07:04:31 +00:00
|
|
|
fields = ["id", "name", "access_key", "comment"]
|
|
|
|
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)
|
2023-10-13 07:26:22 +00:00
|
|
|
from authentication.serializers import AccessKeyCreateSerializer
|
|
|
|
self.fields["access_key"] = AccessKeyCreateSerializer(read_only=True)
|
2020-05-28 08:10:28 +00:00
|
|
|
|
2021-01-20 10:33:38 +00:00
|
|
|
def get_username(self):
|
2022-11-11 07:04:31 +00:00
|
|
|
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):
|
2022-11-11 07:04:31 +00:00
|
|
|
name = self.initial_data.get("name")
|
2022-03-30 11:07:49 +00:00
|
|
|
name_max_length = 128 - len(User.service_account_email_suffix)
|
2022-11-11 07:04:31 +00:00
|
|
|
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):
|
2022-11-11 07:04:31 +00:00
|
|
|
raise serializers.ValidationError(_("name not unique"), code="unique")
|
2021-01-20 10:33:38 +00:00
|
|
|
return name
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
2022-11-11 07:04:31 +00:00
|
|
|
name = validated_data["name"]
|
2022-03-30 11:07:49 +00:00
|
|
|
email = self.get_email()
|
2022-11-11 07:04:31 +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
|