internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: TencentBlueKing/bk-user

Issue:
修复 SaaS 目录配置页面出现白屏，无法拉取到正确配置的问题
填写完基本信息后，会出现配置白屏

![image](https://user-images.githubusercontent.com/4225292/130004154-aca12be1-0187-4938-87f4-581b2fba3a8d.png)

实际上的原因是我们的 `views` 装饰器存在一个 bug，当用户传入 `serializer` 对象时，会使得上一次请求的数据残留


Discussion:

Resolving patch:
diff --git a/src/bkuser_global/drf_crown/crown.py b/src/bkuser_global/drf_crown/crown.py
--- a/src/bkuser_global/drf_crown/crown.py
+++ b/src/bkuser_global/drf_crown/crown.py
@@ -97,6 +97,11 @@ def get_in_serializer_instance(self, request: Optional["Request"] = None) -> "Ba
                 _data = getattr(request, "query_params")
 
         if isinstance(_in, BaseSerializer):
+            # 由于传入的是全局对象，会残留上一次请求的结果
+            # 这里需要手动清理一下
+            if hasattr(_in, "_validated_data"):
+                delattr(_in, "_validated_data")
+
             _in.initial_data = _data
             slz_obj = _in
         elif issubclass(_in, BaseSerializer):
diff --git a/src/saas/bkuser_shell/config_center/views.py b/src/saas/bkuser_shell/config_center/views.py
--- a/src/saas/bkuser_shell/config_center/views.py
+++ b/src/saas/bkuser_shell/config_center/views.py
@@ -201,7 +201,7 @@ def list_defaults(self, request, validated_data):
         return setting_metas
 
     @inject_serializer(
-        query_in=serializers.UpdateNamespaceSettingSerializer(many=True),
+        body_in=serializers.UpdateNamespaceSettingSerializer(many=True),
         out=serializers.SettingSerializer(many=True),
         tags=["config_center"],
     )


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
部门查询接口 ?lookup_field=name，当部门名称中含有 "." 时返回 404
**用文字描述你遇到的问题**

请用简练的文字描述你遇到的问题，问题描述的清晰程度决定了问题被解决的效率。

**重现方法**
1. 创建一个目录，名字包含点，如【广东省.深圳市】
2. 使用api查询， http:://{host:port}/api/v2/departments/广东省.深圳市/?lookup_field=name

查询结果是404

请描述问题重现的方法，如果不方便描述，可以通过截图或者视频辅助。

**预期行为**

预期的正常行为

**版本**
- 提供用户管理的具体版本号
- 是否是企业版问题？

**如果是 SaaS 页面问题，请提供使用的操作系统和浏览器信息**
 - OS: [e.g. iOS]
 - Browser [e.g. chrome, safari]
 - Version [e.g. 22]

**额外信息**

任何你觉得有助于问题解决的内容



Discussion:

Resolving patch:
diff --git a/src/api/bkuser_core/departments/urls.py b/src/api/bkuser_core/departments/urls.py
--- a/src/api/bkuser_core/departments/urls.py
+++ b/src/api/bkuser_core/departments/urls.py
@@ -13,7 +13,7 @@
 
 from . import views
 
-PVAR_DEPARTMENT_ID = r"(?P<%s>[\w\-]+)" % LOOKUP_FIELD_NAME
+PVAR_DEPARTMENT_ID = r"(?P<%s>[\w\-\.]+)" % LOOKUP_FIELD_NAME
 
 urlpatterns = [
     url(


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[日志] auth fail的日志没有区分度
大量的相同的错误信息, 无法快速精确答复`调用方`的疑惑

```
msg = "Invalid token header. No credentials provided."
```


Discussion:
https://github.com/wklken/bk-user/blob/147c1b9878de468cba41a382b3581ba893f6075a/src/api/bkuser_core/enhanced_account/authentication.py#L51

Resolving patch:
diff --git a/src/api/bkuser_core/enhanced_account/authentication.py b/src/api/bkuser_core/enhanced_account/authentication.py
--- a/src/api/bkuser_core/enhanced_account/authentication.py
+++ b/src/api/bkuser_core/enhanced_account/authentication.py
@@ -48,21 +48,24 @@ def get_token_from_query_params(self, request):
         try:
             return request.query_params[self.query_params_keyword]
         except KeyError:
-            msg = "Invalid token header. No credentials provided."
+            msg = f"Invalid token header. No credentials provided. {self.query_params_keyword} is not in query params"
             raise exceptions.AuthenticationFailed(msg)
 
     def get_token_from_header(self, request):
         auth = get_authorization_header(request).split()
 
         if not auth or auth[0].lower() != self.keyword.lower().encode():
-            msg = "Invalid token header. No credentials provided."
+            msg = "Invalid token header. No credentials provided. The format should be `iBearer THE_TOKEN`"
             raise exceptions.AuthenticationFailed(msg)
 
         if len(auth) == 1:
-            msg = "Invalid token header. No credentials provided."
+            msg = "Invalid token header. No credentials provided. The size of auth array credentials is 0"
             raise exceptions.AuthenticationFailed(msg)
         elif len(auth) > 2:
-            msg = "Invalid token header. Token string should not contain spaces."
+            msg = (
+                "Invalid token header. Token string should not contain spaces. "
+                + "The size of auth array credentials is more than 2"
+            )
             raise exceptions.AuthenticationFailed(msg)
 
         try:
@@ -74,11 +77,6 @@ def get_token_from_header(self, request):
         return token
 
     def authenticate(self, request):
-        for white_url in settings.AUTH_EXEMPT_PATHS:
-            if re.search(white_url, request.path):
-                logger.info("%s path in white_url<%s>, exempting auth", request.path, white_url)
-                return None, None
-
         try:
             token = self.get_token_from_query_params(request)
         except exceptions.AuthenticationFailed:
@@ -92,7 +90,9 @@ def authenticate_credentials(self, key):
         if key in settings.INTERNAL_AUTH_TOKENS:
             user_info = settings.INTERNAL_AUTH_TOKENS[key]
             return create_user(user_info["username"]), None
-        raise exceptions.AuthenticationFailed("request failed: Invalid token header. No credentials provided.")
+        raise exceptions.AuthenticationFailed(
+            "request failed: Invalid token header. No credentials provided or Wrong credentials."
+        )
 
 
 class ESBOrAPIGatewayAuthentication(BaseAuthentication):


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[bug] HTTP 数据源同步失败, 一直展示`重试中`
bug: 重试结束后, 没有更新对应状态? 还是使用了不同的任务 ID 跟踪的重试? 

可能跟 #402 有关系


Discussion:
<img width="1694" alt="image" src="https://user-images.githubusercontent.com/2002216/167247922-d462c7ff-af0b-47d8-96d7-950fdfd54e57.png">


1. 手动同步, 失败重试, 始终是同一个task_id, 最终任务状态更新正确
2. 定时任务, 失败重试, 每次都是一个新的task_id, 最终第 4 个失败变更fail, 其他3个会一直是`重试`状态

所以, 定时任务会一直产生queue(as result backend) 没有做进一步消费?   #402 


https://github.com/TencentBlueKing/bk-user/blob/6ec96f8949fafbc595a6af23e280d795a2f2c55a/src/api/bkuser_core/categories/tasks.py#L84-L88

Resolving patch:
diff --git a/src/api/bkuser_core/categories/models.py b/src/api/bkuser_core/categories/models.py
--- a/src/api/bkuser_core/categories/models.py
+++ b/src/api/bkuser_core/categories/models.py
@@ -9,7 +9,7 @@
 specific language governing permissions and limitations under the License.
 """
 import datetime
-from typing import Dict, List
+from typing import Dict, List, Optional
 from uuid import UUID, uuid4
 
 from django.db import models
@@ -156,6 +156,12 @@ def register_task(
             _("当前目录处于同步状态, 请在 {timeout}s 后重试.").format(timeout=(TIMEOUT_THRESHOLD - delta).total_seconds())
         )
 
+    def get_crontab_retrying_task(self, category: ProfileCategory) -> Optional["SyncTask"]:
+        qs = self.filter(
+            category=category, status=SyncTaskStatus.RETRYING.value, type=SyncTaskType.AUTO.value
+        ).order_by("-create_time")
+        return qs.first()
+
 
 class SyncTask(TimestampedModel):
     id = models.UUIDField("UUID", default=uuid4, primary_key=True, editable=False, auto_created=True, unique=True)
diff --git a/src/api/bkuser_core/categories/tasks.py b/src/api/bkuser_core/categories/tasks.py
--- a/src/api/bkuser_core/categories/tasks.py
+++ b/src/api/bkuser_core/categories/tasks.py
@@ -82,7 +82,15 @@ def adapter_sync(instance_id: int, operator: str, task_id: Optional[uuid.UUID] =
     if task_id is None:
         # 只有定时任务未传递 task_id
         try:
-            task_id = SyncTask.objects.register_task(category=category, operator=operator, type_=SyncTaskType.AUTO).id
+            # 查询最近的一个状态处于retrying的task;
+            # 因为register_task做了防御(如果有正在运行的, 报错, 如果运行时间超过一个小时, 会设为失效后重新建一个)
+            retrying_task = SyncTask.objects.get_crontab_retrying_task(category=category)
+            if retrying_task:
+                task_id = retrying_task.id
+            else:
+                task_id = SyncTask.objects.register_task(
+                    category=category, operator=operator, type_=SyncTaskType.AUTO
+                ).id
         except ExistsSyncingTaskError as e:
             logger.exception("register task fail, the task is already exists")
             raise error_codes.LOAD_DATA_FAILED.f(str(e))


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[logging] mad/ldap支持独立的logger及log_level
并且, 默认日志等级`debug` 
背景: 开启ldap同步, 目前由于底层抛出异常无法进一步识别, 不好定位问题


Discussion:
ldap同步, 默认是debug日志? 默认开启

确保, 同步时, 有详细的报错? 

-----

平时也用不上 => 类型为sync的日志? 


Resolving patch:
diff --git a/src/api/bkuser_core/categories/plugins/ldap/client.py b/src/api/bkuser_core/categories/plugins/ldap/client.py
--- a/src/api/bkuser_core/categories/plugins/ldap/client.py
+++ b/src/api/bkuser_core/categories/plugins/ldap/client.py
@@ -15,6 +15,7 @@
 import ldap3
 from django.conf import settings
 from ldap3 import ALL, SIMPLE, Connection, Server
+from ldap3.utils import log as ldap3log
 
 from . import exceptions as local_exceptions
 
@@ -24,6 +25,11 @@
 
 logger = logging.getLogger(__name__)
 
+# reference: https://ldap3.readthedocs.io/en/latest/logging.html
+if settings.ENABLE_LDAP3_DEBUG:
+    ldap3log.set_library_log_detail_level(ldap3log.EXTENDED)
+    ldap3log.set_library_log_activation_level(logging.DEBUG)
+
 
 @dataclass
 class LDAPClient:
diff --git a/src/api/bkuser_core/config/common/system.py b/src/api/bkuser_core/config/common/system.py
--- a/src/api/bkuser_core/config/common/system.py
+++ b/src/api/bkuser_core/config/common/system.py
@@ -92,6 +92,9 @@
 # 是否使用进度条(本地开发方便)
 USE_PROGRESS_BAR = False
 
+# 是否开启ldap3 debug
+ENABLE_LDAP3_DEBUG = env.bool("ENABLE_LDAP3_DEBUG", default=False)
+
 # ==============================================================================
 # 数据同步
 # ==============================================================================


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[bug] 点击查看同步进度报错
``` 
'message': "unknown exception while handling the request, detail={'error': "
            "'unknown', 'path': "
            "'/api/v2/sync_task/1604444f-4530-4369-a48b-3351760996ef/logs', "
            "'method': 'GET', 'query_params': <QueryDict: {}>, 'request_id': "
            "'a2c3142893f3d38ff42eae2fb76f4088'}"
```

详细堆栈:

```
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/app/bkuser_core/categories/views.py", line 360, in show_logs
    task: SyncTask = self.get_object()
  File "/app/bkuser_core/apis/v2/viewset.py", line 262, in get_object
    return super().get_object()
  File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py", line 99, in get_object
    self.check_object_permissions(self.request, obj)
  File "/app/bkuser_core/apis/v2/viewset.py", line 240, in check_object_permissions
    self.permission_denied(request, message=getattr(permission, "message", None), obj=obj)
  File "/app/bkuser_core/apis/v2/viewset.py", line 246, in permission_denied
    extra_info=IAMPermissionExtraInfo.from_request(request, obj=obj).to_dict(),
  File "/app/bkuser_core/bkiam/permissions.py", line 145, in from_request
    auth_infos=[cls.AuthInfo.from_action(action, obj)],
  File "/app/bkuser_core/bkiam/permissions.py", line 122, in from_action
    related_resource = cls.RelatedResource.from_obj(obj)
  File "/app/bkuser_core/bkiam/permissions.py", line 100, in from_obj
    name_field_name = ResourceType.get_constants_by_model(obj, "get_id_name_pair")[1]
  File "/app/bkuser_core/bkiam/constants.py", line 259, in get_constants_by_model
    return getattr(cls, target)(cls.get_by_model(instance))
  File "/app/bkuser_core/bkiam/constants.py", line 215, in get_id_name_pair
    return _map[resource_type]
KeyError: <ResourceType.SYNCTASK: 'synctask'>
```


Discussion:

Resolving patch:
diff --git a/src/api/bkuser_core/bkiam/constants.py b/src/api/bkuser_core/bkiam/constants.py
--- a/src/api/bkuser_core/bkiam/constants.py
+++ b/src/api/bkuser_core/bkiam/constants.py
@@ -211,6 +211,8 @@ def get_id_name_pair(cls, resource_type: "ResourceType") -> tuple:
             cls.CATEGORY: ("id", "display_name"),
             cls.FIELD: ("id", "display_name"),
             cls.PROFILE: ("id", "username"),
+            # FIXME: not sure
+            cls.SYNCTASK: ("id", "id"),
         }
         return _map[resource_type]
 


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[bug] leader字段没有带域信息



Discussion:

Resolving patch:
diff --git a/src/api/bkuser_core/profiles/v2/views.py b/src/api/bkuser_core/profiles/v2/views.py
--- a/src/api/bkuser_core/profiles/v2/views.py
+++ b/src/api/bkuser_core/profiles/v2/views.py
@@ -198,6 +198,7 @@ def list(self, request, *args, **kwargs):
             # 直接在 DB 中拼接 username & domain，比在 serializer 中快很多
             if "username" in fields:
                 default_domain = ProfileCategory.objects.get_default().domain
+                # 这里拼装的 username@domain, 没有走到serializer中的get_username
                 queryset = queryset.extra(
                     select={"username": "if(`domain`= %s, username, CONCAT(username, '@', domain))"},
                     select_params=(default_domain,),
@@ -206,7 +207,9 @@ def list(self, request, *args, **kwargs):
         page = self.paginate_queryset(queryset)
         # page may be empty list
         if page is not None:
-            serializer = serializer_class(page, fields=fields, many=True)
+            # BUG: 这里必须显式传递 context给到slz, 下层self.context.get("request") 用到, 判断拼接 username@domain
+            # 坑, 修改或重构需要注意; 不要通过这种方式来决定字段格式, 非常容易遗漏
+            serializer = serializer_class(page, fields=fields, many=True, context=self.get_serializer_context())
             return self.get_paginated_response(serializer.data)
 
         fields = [x for x in fields if x in self._get_model_field_names()]


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
随机密码使用高强度密码
大小写字母+数字? 需要是一个强度高的密码, 目前过于简单


Discussion:

Resolving patch:
diff --git a/src/api/bkuser_core/profiles/utils.py b/src/api/bkuser_core/profiles/utils.py
--- a/src/api/bkuser_core/profiles/utils.py
+++ b/src/api/bkuser_core/profiles/utils.py
@@ -34,8 +34,16 @@
 
 
 def gen_password(length):
+    # 必须包含至少一个数字
     chars = string.ascii_letters + string.digits
-    return "".join([random.choice(chars) for _ in range(length)])
+
+    random_chars = [random.choice(chars) for _ in range(length)]
+    if any([c.isdigit() for c in random_chars]):
+        return "".join(random_chars)
+
+    random_chars[0] = random.choice(string.digits)
+    random.shuffle(random_chars)
+    return "".join(random_chars)
 
 
 USERNAME_DOMAIN_REGEX = re.compile(f"(?P<username>{USERNAME_REGEX})(@(?P<domain>{DOMAIN_PART_REGEX}))?$")
@@ -98,7 +106,7 @@ def make_password_by_config(category_id, return_raw: bool = False) -> Tuple[str,
         raw_password = config_loader["init_password"]
     else:
         # 当且仅当自动生成密码时发送邮件
-        raw_password = gen_password(8)
+        raw_password = gen_password(12)
         should_notify = True
 
     if return_raw:


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[API] property导致放大查询
现象: worker拉起来, `/api/v2/profiles`, 传`no_page=True`能查回去, 不传则阻塞到超时



原因: 

<img width="1273" alt="image" src="https://user-images.githubusercontent.com/2002216/185844600-efcea56f-9852-4b6e-94bc-647c853fe893.png">


代码位置: https://github.com/TencentBlueKing/bk-user/blob/7f3b8ad95caa6732e47a8d20bae127db11bbb743/src/api/bkuser_core/profiles/v2/views.py#L194

audit_login表过大导致的问题, 需要优化



Discussion:

Resolving patch:
diff --git a/src/api/bkuser_core/profiles/v2/views.py b/src/api/bkuser_core/profiles/v2/views.py
--- a/src/api/bkuser_core/profiles/v2/views.py
+++ b/src/api/bkuser_core/profiles/v2/views.py
@@ -186,6 +186,7 @@ def list(self, request, *args, **kwargs):
         if fields:
             self._check_fields(fields)
         else:
+            # 这里没传fields默认使用slz.fields是有问题的, 但是先保持接口行为一致, 不动fields声明(新版接口解决)
             fields = serializer_class().fields
 
         self._ensure_enabled_field(request, fields=fields)
@@ -197,7 +198,9 @@ def list(self, request, *args, **kwargs):
             raise error_codes.QUERY_PARAMS_ERROR
 
         # 提前将关系表拿出来
-        queryset = queryset.prefetch_related(*self.relation_fields)
+        # BUG: 这里需要去掉 login_set(百万级的表), 大表会导致prefetch就失败
+        # queryset = queryset.prefetch_related(*self.relation_fields)
+        queryset = queryset.prefetch_related("departments", "leader")
 
         # 当用户请求数据时，判断其是否强制输出原始 username
         if not force_use_raw_username(request):
@@ -213,6 +216,11 @@ def list(self, request, *args, **kwargs):
         page = self.paginate_queryset(queryset)
         # page may be empty list
         if page is not None:
+            # BUG: slz 中的 last_login_time 会导致放大查询, 需要剔除(即, 这个接口将不再支持last_login_time)
+            # another two property not in slz fields are: latest_check_time bad_check_cnt
+            if "last_login_time" in fields:
+                del fields["last_login_time"]
+
             # BUG: 这里必须显式传递 context给到slz, 下层self.context.get("request") 用到, 判断拼接 username@domain
             # 坑, 修改或重构需要注意; 不要通过这种方式来决定字段格式, 非常容易遗漏
             serializer = serializer_class(page, fields=fields, many=True, context=self.get_serializer_context())


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
[docs] 删除docs/release相关日志
指引用户到release.md查看


Discussion:

Resolving patch:
diff --git a/src/api/bkuser_core/departments/v2/serializers.py b/src/api/bkuser_core/departments/v2/serializers.py
--- a/src/api/bkuser_core/departments/v2/serializers.py
+++ b/src/api/bkuser_core/departments/v2/serializers.py
@@ -47,7 +47,7 @@ class Meta:
 class ForSyncDepartmentSerializer(CustomFieldsModelSerializer):
     """this serializer is for sync data from one bk-user to another
     the api protocol:
-    https://github.com/TencentBlueKing/bk-user/blob/development/src/api/bkuser_core/categories/plugins/custom/README.md
+    https://github.com/TencentBlueKing/bk-user/blob/develop/src/api/bkuser_core/categories/plugins/custom/README.md
     """
 
     class Meta:


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
启动命令: gunicorn 支持退出前打印堆栈
遇到gunicorn 直接退出的情况, 可以使用 https://stackoverflow.com/questions/57167240/is-it-possible-to-get-a-stack-trace-when-a-gunicorn-worker-hits-a-timeout  方式调试, 打印退出前堆栈, 从而推断问题代码位置


Discussion:
用户管理启动的地方加下, 确认二进制容器化部署能正确拉起即可
本周抽空处理

Resolving patch:
diff --git a/src/api/wsgi.py b/src/api/wsgi.py
--- a/src/api/wsgi.py
+++ b/src/api/wsgi.py
@@ -8,10 +8,13 @@
 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 faulthandler
 import os
 
 from django.core.wsgi import get_wsgi_application
 
+faulthandler.enable()
+
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bkuser_core.config.overlays.prod")
 
 application = get_wsgi_application()
diff --git a/src/login/wsgi.py b/src/login/wsgi.py
--- a/src/login/wsgi.py
+++ b/src/login/wsgi.py
@@ -10,11 +10,14 @@
 specific language governing permissions and limitations under the License.
 """
 
+import faulthandler
 import os
 
 from dj_static import Cling
 from django.core.wsgi import get_wsgi_application
 
+faulthandler.enable()
+
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bklogin.config.prod")
 
 application = Cling(get_wsgi_application())
diff --git a/src/saas/wsgi.py b/src/saas/wsgi.py
--- a/src/saas/wsgi.py
+++ b/src/saas/wsgi.py
@@ -8,10 +8,13 @@
 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 faulthandler
 import os
 
 from django.core.wsgi import get_wsgi_application
 
+faulthandler.enable()
+
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bkuser_shell.config.overlays.prod")
 
 application = get_wsgi_application()


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
定时任务异常
https://github.com/wklken/bk-user/blob/42ba8555d9cce799be7649e80cf10ce4555da7d4/src/api/bkuser_core/profiles/tasks.py#L253

<img width="1402" alt="image" src="https://user-images.githubusercontent.com/2002216/197699917-5c0211d3-4bd4-4966-b362-32d43d90855b.png">


需要修复, 但是需要注意, 内部正在使用的环境,做了自定义登录的环境(bk-dev/bk-op/saml等) 没有登陆日志, 不能导致用户被更新为lock

---------

没有登录日志, 应该怎么处理? 


Discussion:
内部上云环境需要: 将这个定时任务关掉 TODO
> 内部上云环境需要: 将这个定时任务关掉 TODO

已经关掉

```
select b.key, a.value, a.enabled, a.category_id, a.meta_id from user_settings_setting a, user_settings_settingmeta b where a.meta_id=b.id
and a.category_id=2;
```
```
expired_after_days = Setting.objects.filter(category_id=category_id, meta=meta).first().value
```

unknown exception while handling the request, detail={u'error': u'unknown', u'query_params': {}, u'request_id': u'2366d3735d49fee256b571cca90dd3ed', u'method': u'POST', u'path': u'/api/v1/web/profiles/'}

-------

同时需要修复: 原因, 把配置项关掉之后, 就查不到了, 代码写得不健壮, 需要先判断存不存在

<img width="1387" alt="image" src="https://user-images.githubusercontent.com/2002216/201606693-570b539a-7fd3-4ccb-ac4a-db9aa7091c8d.png">






Resolving patch:
diff --git a/src/api/bkuser_core/api/web/profile/views.py b/src/api/bkuser_core/api/web/profile/views.py
--- a/src/api/bkuser_core/api/web/profile/views.py
+++ b/src/api/bkuser_core/api/web/profile/views.py
@@ -292,7 +292,12 @@ def create(self, request, *args, **kwargs):
             meta = SettingMeta.objects.filter(
                 key="expired_after_days", namespace=SettingsEnableNamespaces.ACCOUNT.value
             ).first()
-            expired_after_days = Setting.objects.filter(category_id=category_id, meta=meta).first().value
+
+            # NOTE: maybe None here if the meta is not set
+            expired_after_days = -1
+            expired_after_days_setting = Setting.objects.filter(category_id=category_id, meta=meta).first()
+            if expired_after_days_setting:
+                expired_after_days = expired_after_days_setting.value
 
             # 账户有效期，不传，默认设置为目录设置项
             if expired_after_days == -1:


Test patch:
Repository: TencentBlueKing/bk-user

Issue:
登录审计导出报错
对登录日志进行导出，接口报错。

reason字段是一个经过ugettext_lazy后的对象，导致写入报错


Discussion:
提bug要提供版本, 报错日志等, 最好用bug report模板

有利于快速确认和解决

-------


当前develop分支，接口api/v1/web/audits/logs/types/login/operations/export/
<img width="930" alt="image" src="https://user-images.githubusercontent.com/2002216/203456918-ac1e1380-0847-490f-9249-949a0083cd6d.png">

bug report:
1. 版本
2. 现象描述
3. 如何复现
4. 日志/报错堆栈截图




v2.5.2修复

Resolving patch:
diff --git a/src/api/bkuser_core/api/web/audit/serializers.py b/src/api/bkuser_core/api/web/audit/serializers.py
--- a/src/api/bkuser_core/api/web/audit/serializers.py
+++ b/src/api/bkuser_core/api/web/audit/serializers.py
@@ -132,7 +132,8 @@ def get_reason(self, obj) -> Optional[str]:
         """get reason display name"""
         if obj.is_success:
             return None
-        return LOGIN_FAILED_REASON_MAP.get(obj.reason, _("未知失败原因"))
+        # bugfix: ugettext_lazy
+        return str(LOGIN_FAILED_REASON_MAP.get(obj.reason, _("未知失败原因")))
 
     def get_datetime(self, obj):
         return obj.create_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")


Test patch: