Skip to content

Commit

Permalink
minor: Init default tenant in migrations (#1388)
Browse files Browse the repository at this point in the history
  • Loading branch information
narasux authored Nov 14, 2023
1 parent 049be01 commit b0d2f13
Show file tree
Hide file tree
Showing 19 changed files with 373 additions and 266 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/bk-user.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,7 @@ jobs:
export BK_COMPONENT_API_URL=""
export MYSQL_PASSWORD=root_pwd
export MYSQL_HOST="127.0.0.1"
export INITIAL_ADMIN_USERNAME=admin
export INITIAL_ADMIN_PASSWORD=admin_pwd
export DJANGO_SETTINGS_MODULE=bkuser.settings
poetry run pytest ./tests
7 changes: 2 additions & 5 deletions src/bk-user/bkuser/apis/web/data_source/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@
from bkuser.apps.sync.constants import DataSourceSyncPeriod, SyncTaskStatus, SyncTaskTrigger
from bkuser.apps.sync.models import DataSourceSyncTask
from bkuser.apps.tenant.models import TenantUserCustomField, UserBuiltinField
from bkuser.biz.data_source_plugin import DefaultPluginConfigProvider
from bkuser.common.constants import SENSITIVE_MASK
from bkuser.plugins.base import get_plugin_cfg_cls, is_plugin_exists
from bkuser.plugins.base import get_default_plugin_cfg, get_plugin_cfg_cls, is_plugin_exists
from bkuser.plugins.constants import DataSourcePluginEnum
from bkuser.plugins.local.models import PasswordRuleConfig
from bkuser.plugins.models import BasePluginConfig
Expand Down Expand Up @@ -306,9 +305,7 @@ def validate(self, attrs):
except PDValidationError as e:
raise ValidationError(_("密码规则配置不合法: {}").format(stringify_pydantic_error(e)))
else:
attrs["password_rule"] = (
DefaultPluginConfigProvider().get(DataSourcePluginEnum.LOCAL).password_rule.to_rule() # type: ignore
)
attrs["password_rule"] = get_default_plugin_cfg(DataSourcePluginEnum.LOCAL).password_rule.to_rule()

return attrs

Expand Down
8 changes: 4 additions & 4 deletions src/bk-user/bkuser/apis/web/data_source/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,12 @@
from bkuser.apps.sync.data_models import DataSourceSyncOptions
from bkuser.apps.sync.managers import DataSourceSyncManager
from bkuser.apps.sync.models import DataSourceSyncTask
from bkuser.biz.data_source_plugin import DefaultPluginConfigProvider
from bkuser.biz.exporters import DataSourceUserExporter
from bkuser.common.error_codes import error_codes
from bkuser.common.passwd import PasswordGenerator
from bkuser.common.response import convert_workbook_to_response
from bkuser.common.views import ExcludePatchAPIViewMixin, ExcludePutAPIViewMixin
from bkuser.plugins.base import get_plugin_cfg_schema_map, get_plugin_cls
from bkuser.plugins.base import get_default_plugin_cfg, get_plugin_cfg_schema_map, get_plugin_cls
from bkuser.plugins.constants import DataSourcePluginEnum

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -85,8 +84,9 @@ class DataSourcePluginDefaultConfigApi(generics.RetrieveAPIView):
},
)
def get(self, request, *args, **kwargs):
config = DefaultPluginConfigProvider().get(kwargs["id"])
if not config:
try:
config = get_default_plugin_cfg(kwargs["id"])
except NotImplementedError:
raise error_codes.DATA_SOURCE_PLUGIN_NOT_DEFAULT_CONFIG

return Response(DataSourcePluginDefaultConfigOutputSLZ(instance={"config": config.model_dump()}).data)
Expand Down
6 changes: 2 additions & 4 deletions src/bk-user/bkuser/apis/web/tenant/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
from bkuser.apps.tenant.constants import TENANT_ID_REGEX
from bkuser.apps.tenant.models import Tenant, TenantUser
from bkuser.biz.data_source import DataSourceSimpleInfo
from bkuser.biz.data_source_plugin import DefaultPluginConfigProvider
from bkuser.biz.tenant import TenantUserWithInheritedInfo
from bkuser.biz.validators import validate_data_source_user_username
from bkuser.common.passwd import PasswordValidator
from bkuser.plugins.base import get_default_plugin_cfg
from bkuser.plugins.constants import DataSourcePluginEnum
from bkuser.plugins.local.constants import PasswordGenerateMethod
from bkuser.plugins.local.models import LocalDataSourcePluginConfig, NotificationConfig
Expand Down Expand Up @@ -64,9 +64,7 @@ def validate_fixed_password(self, fixed_password: str) -> str:
if not fixed_password:
return fixed_password

cfg: LocalDataSourcePluginConfig = DefaultPluginConfigProvider().get( # type: ignore
DataSourcePluginEnum.LOCAL,
)
cfg: LocalDataSourcePluginConfig = get_default_plugin_cfg(DataSourcePluginEnum.LOCAL) # type: ignore
ret = PasswordValidator(cfg.password_rule.to_rule()).validate(fixed_password) # type: ignore
if not ret.ok:
raise ValidationError(_("固定密码的值不符合密码规则:{}").format(ret.exception_message))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# -*- 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 os

from django.db import migrations
from django.utils import timezone

from bkuser.common.constants import PERMANENT_TIME
from bkuser.common.hashers import make_password
from bkuser.plugins.base import get_default_plugin_cfg
from bkuser.plugins.constants import DataSourcePluginEnum

logger = logging.getLogger(__name__)


def forwards_func(apps, schema_editor):
"""初始化本地数据源插件"""
admin_username = os.environ.get("INITIAL_ADMIN_USERNAME")
admin_password = os.environ.get("INITIAL_ADMIN_PASSWORD")
if not (admin_username and admin_password):
raise RuntimeError("INITIAL_ADMIN_USERNAME and INITIAL_ADMIN_PASSWORD must be set in environment variables")

logger.info("start initialize default tenant & data source with admin user [%s]...", admin_username)

Tenant = apps.get_model("tenant", "Tenant")
TenantUser = apps.get_model("tenant", "TenantUser")
TenantManager = apps.get_model("tenant", "TenantManager")
DataSource = apps.get_model("data_source", "DataSource")
DataSourceUser = apps.get_model("data_source", "DataSourceUser")
LocalDataSourceIdentityInfo = apps.get_model("data_source", "LocalDataSourceIdentityInfo")

default_tenant = Tenant.objects.create(id="default", name="默认租户", is_default=True)
data_source = DataSource.objects.create(
name="default",
plugin_id=DataSourcePluginEnum.LOCAL,
owner_tenant_id=default_tenant.id,
plugin_config=get_default_plugin_cfg(DataSourcePluginEnum.LOCAL).model_dump(),
)

data_source_user = DataSourceUser.objects.create(
data_source=data_source, code=admin_username, username=admin_username, full_name=admin_username
)
LocalDataSourceIdentityInfo.objects.create(
user=data_source_user,
password=make_password(admin_password),
password_updated_at=timezone.now(),
password_expired_at=PERMANENT_TIME,
data_source=data_source,
username=admin_username,
)
tenant_user = TenantUser.objects.create(
tenant=default_tenant,
data_source_user=data_source_user,
data_source=data_source,
id=admin_username,
)
TenantManager.objects.create(tenant=default_tenant, tenant_user=tenant_user)

logger.info("initialize default tenant & data source with admin user [%s] success", admin_username)


class Migration(migrations.Migration):
dependencies = [
("tenant", "0003_auto_20231113_2017"),
("data_source", "0002_init_builtin_data_source_plugin"),
("idp", "0002_init_builtin_idp_plugin"),
]

operations = [migrations.RunPython(forwards_func)]
4 changes: 2 additions & 2 deletions src/bk-user/bkuser/biz/data_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
DataSourcePlugin,
DataSourceUserLeaderRelation,
)
from bkuser.biz.data_source_plugin import DefaultPluginConfigProvider
from bkuser.plugins.base import get_default_plugin_cfg
from bkuser.plugins.constants import DataSourcePluginEnum
from bkuser.plugins.local.models import LocalDataSourcePluginConfig, PasswordInitialConfig

Expand Down Expand Up @@ -63,7 +63,7 @@ def create_local_data_source_with_merge_config(
) -> DataSource:
"""使用与默认配置合并后的插件配置,创建本地数据源"""
plugin_id = DataSourcePluginEnum.LOCAL
plugin_config: LocalDataSourcePluginConfig = DefaultPluginConfigProvider().get(plugin_id) # type: ignore
plugin_config: LocalDataSourcePluginConfig = get_default_plugin_cfg(plugin_id) # type: ignore
plugin_config.password_initial = password_initial_config

return DataSource.objects.create(
Expand Down
Loading

0 comments on commit b0d2f13

Please sign in to comment.