Skip to content

Commit

Permalink
Merge pull request #243 from IMBlues/development
Browse files Browse the repository at this point in the history
fix: correct mypy lint
  • Loading branch information
IMBlues authored Jan 13, 2022
2 parents 02e92fe + 8fa69d3 commit 2d44c51
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 40 deletions.
28 changes: 16 additions & 12 deletions src/api/bkuser_core/categories/plugins/ldap/adaptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
from dataclasses import dataclass, field
from typing import Any, Dict, List, NamedTuple, Optional

from bkuser_core.categories.plugins.ldap.models import LdapDepartment, LdapUserProfile
from bkuser_core.categories.plugins.constants import DYNAMIC_FIELDS_SETTING_KEY
from bkuser_core.categories.plugins.ldap.models import LdapDepartment, LdapUserProfile
from bkuser_core.user_settings.loader import ConfigProvider
from django.utils.encoding import force_str
from ldap3.utils import dn as dn_utils
Expand All @@ -24,6 +24,7 @@
@dataclass
class ProfileFieldMapper:
"""从 ldap 对象属性中获取用户字段"""

config_loader: ConfigProvider
embed_fields = [
"username",
Expand All @@ -36,11 +37,11 @@ class ProfileFieldMapper:
def __post_init__(self):
self.dynamic_fields_mapping = self.config_loader.get(DYNAMIC_FIELDS_SETTING_KEY)

self.dynamic_fields = list(
self.dynamic_fields_mapping.keys()) if self.dynamic_fields_mapping else []
self.dynamic_fields = list(self.dynamic_fields_mapping.keys()) if self.dynamic_fields_mapping else []

def get_value(self, field_name: str, user_meta: Dict[str, List[bytes]], remain_raw: bool = False,
dynamic_field: bool = False) -> Any:
def get_value(
self, field_name: str, user_meta: Dict[str, List[bytes]], remain_raw: bool = False, dynamic_field: bool = False
) -> Any:
"""通过 field_name 从 ldap 数据中获取具体值"""

# 获取自定义字段对应的属性值
Expand Down Expand Up @@ -83,25 +84,28 @@ def get_dynamic_values(self, user_meta: Dict[str, List[bytes]]) -> Dict[str, Any

if self.dynamic_fields:
values.update(
{field_name: self.get_value(
field_name=self.dynamic_fields_mapping[field_name],
user_meta=user_meta,
dynamic_field=True) for field_name in self.dynamic_fields}
{
field_name: self.get_value(
field_name=self.dynamic_fields_mapping[field_name], user_meta=user_meta, dynamic_field=True
)
for field_name in self.dynamic_fields
}
)

return values

def get_user_attributes(self) -> list:
"""获取远端属性名列表"""
user_attributes = [self.config_loader[x] for x in self.embed_fields if self.config_loader.get(x)]
user_attributes.extend([self.dynamic_fields_mapping[x] for x in self.dynamic_fields if
self.dynamic_fields_mapping.get(x)])
user_attributes.extend(
[self.dynamic_fields_mapping[x] for x in self.dynamic_fields if self.dynamic_fields_mapping.get(x)]
)

return user_attributes


def user_adapter(
code: str, user_meta: Dict[str, Any], field_mapper: ProfileFieldMapper, restrict_types: List[str]
code: str, user_meta: Dict[str, Any], field_mapper: ProfileFieldMapper, restrict_types: List[str]
) -> LdapUserProfile:
groups = field_mapper.get_value("user_member_of", user_meta["raw_attributes"], True) or []

Expand Down
4 changes: 2 additions & 2 deletions src/api/bkuser_core/categories/plugins/ldap/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@
from bkuser_core.categories.constants import CategoryType
from bkuser_core.categories.loader import get_plugin_by_category
from bkuser_core.categories.plugins.utils import (
delete_dynamic_filed,
delete_periodic_sync_task,
make_periodic_sync_task,
update_periodic_sync_task,
delete_dynamic_filed,
)
from bkuser_core.categories.signals import post_category_create, post_category_delete, post_dynamic_field_delete
from bkuser_core.user_settings.signals import post_setting_create, post_setting_update
from django.dispatch import receiver

if TYPE_CHECKING:
from bkuser_core.categories.models import ProfileCategory
from bkuser_core.user_settings.models import Setting
from bkuser_core.profiles.models import DynamicFieldInfo
from bkuser_core.user_settings.models import Setting

logger = logging.getLogger(__name__)

Expand Down
2 changes: 1 addition & 1 deletion src/api/bkuser_core/categories/plugins/ldap/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def _load_base_info(self):
"code": info.code,
"telephone": info.telephone,
"status": ProfileStatus.NORMAL.value,
"extras": info.extras
"extras": info.extras,
}

# 2. 更新或创建 Profile 对象
Expand Down
2 changes: 1 addition & 1 deletion src/api/bkuser_core/categories/plugins/ldap/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
specific language governing permissions and limitations under the License.
"""
from dataclasses import dataclass
from typing import List, Optional, Dict
from typing import Dict, List, Optional

from django.utils.functional import cached_property

Expand Down
4 changes: 2 additions & 2 deletions src/api/bkuser_core/categories/plugins/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
import logging

from bkuser_core.categories.plugins.base import TypeList, TypeProtocol
from bkuser_core.categories.plugins.constants import DYNAMIC_FIELDS_SETTING_KEY
from bkuser_core.common.progress import progress
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from bkuser_core.user_settings.models import Setting
from bkuser_core.categories.plugins.constants import DYNAMIC_FIELDS_SETTING_KEY
from django_celery_beat.models import IntervalSchedule, PeriodicTask

logger = logging.getLogger(__name__)

Expand Down
43 changes: 22 additions & 21 deletions src/api/bkuser_core/profiles/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@
import datetime
import logging
import re
from typing import Any, ClassVar, Dict, Tuple, Type

from bkuser_core.profiles.constants import DynamicFieldTypeEnum
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import ValidationError
from typing import Any, ClassVar, Type, Tuple, Dict
from typing_extensions import Protocol


USERNAME_REGEX = r"^(\d|[a-zA-Z])([a-zA-Z0-9._-]){0,31}"
DOMAIN_REGEX = r"^(\d|[a-zA-Z])([a-zA-Z0-9-.]){0,15}"
# for part domain which is not start with
Expand Down Expand Up @@ -74,17 +73,18 @@ def validate_extras_value_unique(value: dict, category_id: int, profile_id: int

class ExtrasValidator(Protocol):
"""自定义字段格式校验"""
target_types: ClassVar[Tuple[Type]]
transform_types: ClassVar[Tuple[Type]]

target_types: ClassVar[Tuple]
transform_types: ClassVar[Tuple]

@classmethod
def validate(cls, value: Any, field_info):
raise NotImplementedError


class ExtrasNumberValidator(ExtrasValidator):
target_types: ClassVar[Tuple[Type]] = (int, float)
transform_types: ClassVar[Tuple[Type]] = (str,)
class ExtrasNumberValidator:
target_types: ClassVar[Tuple] = (int, float)
transform_types: ClassVar[Tuple] = (str,)

@classmethod
def validate(cls, value: Any, field_info):
Expand All @@ -104,8 +104,9 @@ def transform(cls, value):
return float(value)


class ExtrasStringValidator(ExtrasValidator):
target_types: ClassVar[Tuple[Type]] = (str,) # noqa
class ExtrasStringValidator:
target_types: ClassVar[Tuple] = (str,)
transform_types: ClassVar[Tuple] = ()

@classmethod
def validate(cls, value: Any, field_info):
Expand All @@ -124,9 +125,9 @@ def transform(cls, value):
return str(value)


class ExtrasOneEnumValidator(ExtrasValidator):
target_types = (int,)
transform_types = (str,)
class ExtrasOneEnumValidator:
target_types: ClassVar[Tuple] = (int,)
transform_types: ClassVar[Tuple] = (str,)

@classmethod
def validate(cls, value: Any, field_info):
Expand All @@ -150,9 +151,9 @@ def transform(cls, value):
return int(value)


class ExtrasMultlEnumValidator(ExtrasValidator):
target_types = (list,)
transform_types = (str, set, tuple)
class ExtrasMultiEnumValidator:
target_types: ClassVar[Tuple] = (list,)
transform_types: ClassVar[Tuple] = (str, set, tuple)

@classmethod
def validate(cls, value: Any, field_info):
Expand All @@ -174,14 +175,15 @@ def transform(cls, value):
return list(value)


class ExtrasTimerValidator(ExtrasValidator):
target_types: ClassVar[Tuple[Type]] = (str,)
class ExtrasTimerValidator:
target_types: ClassVar[Tuple] = (str,)
transform_types: ClassVar[Tuple] = ()

@classmethod
def validate(cls, value: Any, field_info):
if isinstance(value, cls.target_types):
try:
datetime.datetime.strptime(value, '%Y-%m-%d')
datetime.datetime.strptime(value, "%Y-%m-%d")
return
except Exception:
raise ValidationError(_("{} 不符合格式要求".format(value)))
Expand All @@ -192,9 +194,8 @@ def validate(cls, value: Any, field_info):
DynamicFieldTypeEnum.NUMBER.value: ExtrasNumberValidator,
DynamicFieldTypeEnum.STRING.value: ExtrasStringValidator,
DynamicFieldTypeEnum.ONE_ENUM.value: ExtrasOneEnumValidator,
DynamicFieldTypeEnum.MULTI_ENUM.value: ExtrasMultlEnumValidator,
DynamicFieldTypeEnum.TIMER.value: ExtrasTimerValidator

DynamicFieldTypeEnum.MULTI_ENUM.value: ExtrasMultiEnumValidator,
DynamicFieldTypeEnum.TIMER.value: ExtrasTimerValidator,
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def test_parse_dn_tree(dn, restrict_types, expected):
["com", "center", "Users", "Schema Admins"],
["com", "center", "Builtin", "Administrators"],
],
extras={}
extras={},
),
),
(
Expand Down

0 comments on commit 2d44c51

Please sign in to comment.