Skip to content

Commit

Permalink
Merge pull request #200 from IMBlues/development
Browse files Browse the repository at this point in the history
refactor: exposing enabled of setting to frontend
  • Loading branch information
IMBlues authored Dec 9, 2021
2 parents ab58253 + 84252ee commit 852b877
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 17 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/eslint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
- name: Install modules
run: |
cd src/pages
npm i --force
npm i
- name: Run ESLint
run: |
cd src/pages
Expand Down
12 changes: 6 additions & 6 deletions src/api/bkuser_core/categories/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def get_required_metas(self):
def get_unfilled_settings(self):
"""获取未就绪的配置"""
required_metas = self.get_required_metas()
configured_meta_ids = self.settings.filter(enabled=True).values_list("meta", flat=True)
configured_meta_ids = self.settings.all().values_list("meta", flat=True)
return required_metas.exclude(id__in=configured_meta_ids)

def mark_synced(self):
Expand All @@ -144,7 +144,7 @@ def to_audit_info(self):
class SyncTaskManager(models.Manager):
def register_task(
self, category: ProfileCategory, operator: str, type_: SyncTaskType = SyncTaskType.MANUAL
) -> 'SyncTask':
) -> "SyncTask":
qs = self.filter(category=category, status=SyncTaskStatus.RUNNING.value).order_by("-create_time")
running = qs.first()
if not running:
Expand All @@ -164,7 +164,7 @@ def register_task(


class SyncTask(TimestampedModel):
id = models.UUIDField('UUID', default=uuid4, primary_key=True, editable=False, auto_created=True, unique=True)
id = models.UUIDField("UUID", default=uuid4, primary_key=True, editable=False, auto_created=True, unique=True)
category = models.ForeignKey(ProfileCategory, verbose_name="用户目录", on_delete=models.CASCADE, db_index=True)
status = models.CharField(
verbose_name="状态", max_length=16, choices=SyncTaskStatus.get_choices(), default=SyncTaskStatus.RUNNING.value
Expand Down Expand Up @@ -196,8 +196,8 @@ def progresses(self):


class SyncProgressManager(models.Manager):
def init_progresses(self, category: ProfileCategory, task_id: UUID) -> Dict[SyncStep, 'SyncProgress']:
progresses: Dict[SyncStep, 'SyncProgress'] = {}
def init_progresses(self, category: ProfileCategory, task_id: UUID) -> Dict[SyncStep, "SyncProgress"]:
progresses: Dict[SyncStep, "SyncProgress"] = {}
for step in [
SyncStep.DEPARTMENTS,
SyncStep.USERS,
Expand All @@ -211,7 +211,7 @@ def init_progresses(self, category: ProfileCategory, task_id: UUID) -> Dict[Sync


class SyncProgress(TimestampedModel):
task_id = models.UUIDField(db_index=True, verbose_name='任务id')
task_id = models.UUIDField(db_index=True, verbose_name="任务id")
category = models.ForeignKey(ProfileCategory, verbose_name="用户目录", on_delete=models.CASCADE)
step = models.CharField(verbose_name="同步步骤", max_length=32, choices=SyncStep.get_choices())
status = models.CharField(
Expand Down
19 changes: 13 additions & 6 deletions src/api/bkuser_core/profiles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@

from bkuser_global.utils import force_str_2_bool

from ..user_settings.exceptions import SettingHasBeenDisabledError
from . import serializers as local_serializers

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -320,9 +321,12 @@ def _update(self, request, partial):
if validated_data.get("password"):
pending_password = validated_data.get("password")
config_loader = ConfigProvider(category_id=instance.category_id)
max_password_history = config_loader.get("max_password_history", settings.DEFAULT_MAX_PASSWORD_HISTORY)
if check_former_passwords(instance, pending_password, max_password_history):
raise error_codes.PASSWORD_DUPLICATED.f(max_password_history=max_password_history)
try:
max_password_history = config_loader.get("max_password_history", settings.DEFAULT_MAX_PASSWORD_HISTORY)
if check_former_passwords(instance, pending_password, int(max_password_history)):
raise error_codes.PASSWORD_DUPLICATED.f(max_password_history=max_password_history)
except SettingHasBeenDisabledError:
logger.info("category<%s> has disabled checking password", instance.category_id)

PasswordValidator(
min_length=int(config_loader["password_min_length"]),
Expand Down Expand Up @@ -400,9 +404,12 @@ def modify_password(self, request, *args, **kwargs):
new_password = serializer.validated_data["new_password"]

config_loader = ConfigProvider(category_id=instance.category_id)
max_password_history = config_loader.get("max_password_history", settings.DEFAULT_MAX_PASSWORD_HISTORY)
if check_former_passwords(instance, new_password, max_password_history):
raise error_codes.PASSWORD_DUPLICATED.f(max_password_history=max_password_history)
try:
max_password_history = config_loader.get("max_password_history", settings.DEFAULT_MAX_PASSWORD_HISTORY)
if check_former_passwords(instance, new_password, int(max_password_history)):
raise error_codes.PASSWORD_DUPLICATED.f(max_password_history=max_password_history)
except SettingHasBeenDisabledError:
logger.info("category<%s> has disabled checking password", instance.category_id)

if not instance.check_password(old_password):
raise error_codes.PASSWORD_ERROR
Expand Down
21 changes: 21 additions & 0 deletions src/api/bkuser_core/user_settings/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# -*- 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.
"""


class SettingHasBeenDisabledError(Exception):
"""配置已经被禁用"""

def __init__(self, key: str, *args):
self.key = key
super().__init__(*args)

def __str__(self):
return f"setting {self.key} has been disabled."
7 changes: 6 additions & 1 deletion src/api/bkuser_core/user_settings/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"""
from dataclasses import dataclass, field

from bkuser_core.user_settings.exceptions import SettingHasBeenDisabledError

from .models import Setting


Expand All @@ -24,11 +26,14 @@ def __post_init__(self):
self._refresh_config()

def _refresh_config(self):
settings = Setting.objects.prefetch_related("meta").filter(category_id=self.category_id, enabled=True)
settings = Setting.objects.prefetch_related("meta").filter(category_id=self.category_id)
self._raws = {x.meta.key: x for x in settings}
self._config = {x.meta.key: x.value for x in settings}

def get(self, k, d=None):
if k in self._raws and not self._raws.get(k).enabled:
raise SettingHasBeenDisabledError(k)

return self._config.get(k, d)

def __getitem__(self, key):
Expand Down
1 change: 1 addition & 0 deletions src/api/bkuser_core/user_settings/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class SettingCreateSerializer(serializers.Serializer):

class SettingUpdateSerializer(serializers.Serializer):
value = serializers.JSONField()
enabled = serializers.BooleanField(default=True)


class SettingListSerializer(serializers.Serializer):
Expand Down
2 changes: 1 addition & 1 deletion src/api/bkuser_core/user_settings/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
class SettingViewSet(AdvancedModelViewSet):
"""配置项"""

queryset = Setting.objects.filter(enabled=True)
queryset = Setting.objects.all()
serializer_class = serializers.SettingSerializer
lookup_field: str = "id"

Expand Down
1 change: 1 addition & 0 deletions src/saas/bkuser_shell/config_center/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ class ListNamespaceSettingsSerializer(serializers.Serializer):
class UpdateNamespaceSettingSerializer(serializers.Serializer):
key = serializers.CharField()
value = serializers.JSONField()
enabled = serializers.BooleanField(required=False, default=True)


class SettingMetaSerializer(serializers.Serializer):
Expand Down
4 changes: 2 additions & 2 deletions src/saas/bkuser_shell/config_center/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def update(self, request, category_id, namespace_name, validated_data):
# TODO: 后续改为批量接口
result = []
for setting_info in validated_data:
body = {"value": setting_info["value"]}
body = {"value": setting_info["value"], "enabled": setting_info["enabled"]}
try:
setting_id = setting_instances[setting_info["key"]].id
except KeyError:
Expand All @@ -224,7 +224,7 @@ def update(self, request, category_id, namespace_name, validated_data):
try:
api_response = api_instance.v2_settings_partial_update(body=body, lookup_value=setting_id)
except ApiException:
logger.exception("更新 Setting<%s> 失败", setting_info["id"])
logger.exception("在目录<%s>中更新 Setting<%s>-<%s> 失败", category_id, setting_info["key"], setting_id)
continue

result.append(api_response)
Expand Down

0 comments on commit 852b877

Please sign in to comment.