Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create data source user #1167

Merged
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/bk-user/bkuser/apis/web/data_source/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
62 changes: 62 additions & 0 deletions src/bk-user/bkuser/apis/web/data_source/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import logging

from django.conf import settings
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

from bkuser.apps.data_source.models import DataSourceDepartment, DataSourceUser
from bkuser.biz.validators import validate_data_source_user_username
from bkuser.common.validators import validate_phone_with_country_code

logger = logging.getLogger(__name__)


class UserCreateInputSLZ(serializers.Serializer):
username = serializers.CharField(help_text="用户名", validators=[validate_data_source_user_username])
full_name = serializers.CharField(help_text="姓名")
email = serializers.EmailField(help_text="邮箱")
phone_country_code = serializers.CharField(
help_text="手机号国际区号", required=False, default=settings.DEFAULT_PHONE_COUNTRY_CODE
)
phone = serializers.CharField(help_text="手机号")
logo = serializers.CharField(help_text="用户 Logo", required=False)
department_ids = serializers.ListField(help_text="部门ID列表", child=serializers.IntegerField(), default=[])
leader_ids = serializers.ListField(help_text="上级ID列表", child=serializers.IntegerField(), default=[])

def validate(self, data):
validate_phone_with_country_code(phone=data["phone"], country_code=data["phone_country_code"])
return data

def validate_department_ids(self, department_ids):
diff_department_ids = set(department_ids) - set(
DataSourceDepartment.objects.filter(
id__in=department_ids, data_source=self.context["data_source"]
).values_list("id", flat=True)
)
if diff_department_ids:
raise serializers.ValidationError(_("传递了错误的部门信息: {}").format(diff_department_ids))
return department_ids

def validate_leader_ids(self, leader_ids):
diff_leader_ids = set(leader_ids) - set(
DataSourceUser.objects.filter(id__in=leader_ids, data_source=self.context["data_source"]).values_list(
"id", flat=True
)
)
if diff_leader_ids:
raise serializers.ValidationError(_("传递了错误的上级信息: {}").format(diff_leader_ids))
return leader_ids


class UserCreateOutputSLZ(serializers.Serializer):
id = serializers.CharField(help_text="数据源用户ID")
17 changes: 17 additions & 0 deletions src/bk-user/bkuser/apis/web/data_source/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from django.urls import path

from bkuser.apis.web.data_source import views

urlpatterns = [
path("<int:id>/users/", views.DataSourceUserListCreateApi.as_view(), name="data_source_user.list_create"),
]
65 changes: 65 additions & 0 deletions src/bk-user/bkuser/apis/web/data_source/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics, status
from rest_framework.response import Response

from bkuser.apis.web.data_source.serializers import UserCreateInputSLZ, UserCreateOutputSLZ
from bkuser.apps.data_source.models import DataSource, DataSourceUser
from bkuser.biz.data_source_organization import (
DataSourceOrganizationHandler,
DataSourceUserBaseInfo,
DataSourceUserRelationInfo,
)
from bkuser.common.error_codes import error_codes


class DataSourceUserListCreateApi(generics.ListCreateAPIView):
queryset = DataSource.objects.all()
pagination_class = None
lookup_url_kwarg = "id"

@swagger_auto_schema(
operation_description="新建数据源用户",
request_body=UserCreateInputSLZ(),
responses={status.HTTP_201_CREATED: UserCreateOutputSLZ()},
tags=["data_source"],
)
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved
def post(self, request, *args, **kwargs):
data_source = self.get_object()
slz = UserCreateInputSLZ(data=request.data, context={"data_source": data_source})
slz.is_valid(raise_exception=True)
data = slz.validated_data

# 不允许对非本地数据源进行用户新增操作
if not data_source.user_editable:
raise error_codes.CANNOT_CREATE_USER
# 校验是否已存在该用户
if DataSourceUser.objects.filter(username=data["username"], data_source=data_source).exists():
raise error_codes.DATA_SOURCE_USER_ALREADY_EXISTED
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved

# 用户数据整合
base_user_info = DataSourceUserBaseInfo(
username=data["username"],
full_name=data["full_name"],
email=data["email"],
phone=data["phone"],
phone_country_code=data["phone_country_code"],
)

relation_info = DataSourceUserRelationInfo(
department_ids=data["department_ids"], leader_ids=data["leader_ids"]
)

user_id = DataSourceOrganizationHandler.create_user(
data_source=data_source, base_user_info=base_user_info, relation_info=relation_info
)
narasux marked this conversation as resolved.
Show resolved Hide resolved
return Response(UserCreateOutputSLZ(instance={"id": user_id}).data)
1 change: 1 addition & 0 deletions src/bk-user/bkuser/apis/web/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@
path("basic/", include("bkuser.apis.web.basic.urls")),
# 租户
path("tenants/", include("bkuser.apis.web.tenant.urls")),
path("data-sources/", include("bkuser.apis.web.data_source.urls")),
]
12 changes: 12 additions & 0 deletions src/bk-user/bkuser/apps/data_source/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
CHINESE_REGION = "CN"
CHINESE_PHONE_LENGTH = 11
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved
6 changes: 6 additions & 0 deletions src/bk-user/bkuser/apps/data_source/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ class DataSource(TimestampedModel):
class Meta:
ordering = ["id"]

@property
def user_editable(self) -> bool:
if self.plugin.id == "local":
return True
return False
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved


class DataSourceUser(TimestampedModel):
data_source = models.ForeignKey(DataSource, on_delete=models.PROTECT, db_constraint=False)
Expand Down
85 changes: 85 additions & 0 deletions src/bk-user/bkuser/biz/data_source_organization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from typing import List

from django.db import transaction
from pydantic import BaseModel

from bkuser.apps.data_source.models import (
DataSource,
DataSourceDepartmentUserRelation,
DataSourceUser,
DataSourceUserLeaderRelation,
)
from bkuser.apps.tenant.models import Tenant, TenantUser
from bkuser.utils.uuid import generate_uuid


class DataSourceUserBaseInfo(BaseModel):
"""数据源用户基础信息"""

username: str
full_name: str
email: str
phone: str
phone_country_code: str


class DataSourceUserRelationInfo(BaseModel):
"""数据源用户关系信息"""

department_ids: List[int]
leader_ids: List[int]


class DataSourceOrganizationHandler:
@staticmethod
def create_user(
data_source: DataSource, base_user_info: DataSourceUserBaseInfo, relation_info: DataSourceUserRelationInfo
) -> str:
"""
创建数据源用户
"""
# TODO:补充日志
with transaction.atomic():
# 创建数据源用户
create_user_info_map = {"data_source": data_source, **base_user_info.model_dump()}
user = DataSourceUser.objects.create(**create_user_info_map)
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved

# 批量创建数据源用户-部门关系
department_user_relation_objs = [
DataSourceDepartmentUserRelation(department_id=dept_id, user_id=user.id)
for dept_id in relation_info.department_ids
]

if department_user_relation_objs:
DataSourceDepartmentUserRelation.objects.bulk_create(department_user_relation_objs)

# 批量创建数据源用户-上级关系
user_leader_relation_objs = [
DataSourceUserLeaderRelation(leader_id=leader_id, user_id=user.id)
for leader_id in relation_info.leader_ids
]

if user_leader_relation_objs:
DataSourceUserLeaderRelation.objects.bulk_create(user_leader_relation_objs)

# 查询关联的租户
tenant = Tenant.objects.get(id=data_source.owner_tenant_id)
# 创建租户用户
TenantUser.objects.create(
data_source_user=user,
tenant=tenant,
data_source=data_source,
id=generate_uuid(),
)

return user.id
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved
9 changes: 9 additions & 0 deletions src/bk-user/bkuser/biz/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,23 @@
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import logging
import re

from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import ValidationError

TENANT_ID_REGEX = r"^[a-zA-Z][a-zA-Z0-9-]{2,31}"
DATA_SOURCE_USERNAME_REGEX = r"^[a-zA-Z][a-zA-Z0-9-]{2,31}"
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved

logger = logging.getLogger(__name__)


def validate_tenant_id(value):
if not re.fullmatch(re.compile(TENANT_ID_REGEX), value):
raise ValidationError(_("{} 不符合 租户ID 的命名规范: 由3-32位字母、数字、连接符(-)字符组成,以字母开头").format(value)) # noqa: E501


def validate_data_source_user_username(value):
if not re.fullmatch(re.compile(DATA_SOURCE_USERNAME_REGEX), value):
raise ValidationError(_("{} 不符合 用户名 的命名规范: 由3-32位字母、数字、连接符(-)字符组成,以字母开头").format(value)) # noqa: E501
3 changes: 3 additions & 0 deletions src/bk-user/bkuser/common/error_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ class ErrorCodes:
REMOTE_REQUEST_ERROR = ErrorCode(_("调用外部系统API异常"))
# 数据源
DATA_SOURCE_TYPE_NOT_SUPPORTED = ErrorCode(_("数据源类型不支持"))
CANNOT_CREATE_USER = ErrorCode(_("该数据源不支持新增用户"))
DATA_SOURCE_USER_ALREADY_EXISTED = ErrorCode(_("数据源用户已存在"))

# 租户
CREATE_TENANT_FAILED = ErrorCode(_("租户创建失败"))
UPDATE_TENANT_FAILED = ErrorCode(_("租户更新失败"))
Expand Down
42 changes: 42 additions & 0 deletions src/bk-user/bkuser/common/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import logging

import phonenumbers
from django.utils.translation import gettext_lazy as _
from phonenumbers import NumberParseException, region_code_for_country_code
from rest_framework import serializers

from bkuser.apps.data_source.constants import CHINESE_PHONE_LENGTH, CHINESE_REGION

logger = logging.getLogger(__name__)


def validate_phone_with_country_code(phone: str, country_code: str):
try:
region = region_code_for_country_code(int(country_code))

except ValueError:
logger.debug("failed to parse phone_country_code: %s, ", country_code)
raise serializers.ValidationError(_("手机地区码 {} 不符合解析规则").format(country_code))

# phonenumbers库在验证号码的时:过短会解析为有效号码,超过250的字节才算超长
# =》所以这里需要显式做中国号码的长度校验
if region == CHINESE_REGION and len(phone) != CHINESE_PHONE_LENGTH:
raise serializers.ValidationError(_("手机号 {} 不符合长度要求").format(phone))

try:
# 按照指定地区码解析手机号
phonenumbers.parse(phone, region)

except NumberParseException: # pylint: disable=broad-except
logger.debug("failed to parse phone number: %s", phone)
raise serializers.ValidationError(_("手机号 {} 不符合规则").format(phone))
Canway-shiisa marked this conversation as resolved.
Show resolved Hide resolved
Loading