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

rebase from development #156

Merged
merged 13 commits into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion deploy/helm/bk-user-stack/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: bk-user-stack
description: A Helm chart for bk-user
type: application
version: 0.6.0
appVersion: v2.3.0
appVersion: v2.3.1-beta.2

dependencies:
- name: bkuserapi
Expand Down
9 changes: 6 additions & 3 deletions src/api/bkuser_core/audit/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,13 @@ def _catch_exc(self, request, *args, **kwargs):
"operator": request.operator,
"operate_type": operate_type,
"request": request,
"operator_obj": self.get_object(),
}
try:
_result = func(self, request, *args, **kwargs)
except Exception as e:
# get updated obj
_params["operator_obj"] = self.get_object()
if operate_type == OperationType.UPDATE.value:
_params["operator_obj"] = self.get_object()

if isinstance(e, CoreAPIError):
failed_info = f"{e.message}"
Expand All @@ -130,7 +131,9 @@ def _catch_exc(self, request, *args, **kwargs):
)
raise
else:
_params["operator_obj"] = self.get_object()
if operate_type == OperationType.UPDATE.value:
_params["operator_obj"] = self.get_object()

create_general_log(**_params)
return _result

Expand Down
5 changes: 4 additions & 1 deletion src/api/bkuser_core/bkiam/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import regex
from bkuser_core.categories.constants import CategoryType
from bkuser_core.categories.models import ProfileCategory
from bkuser_core.categories.models import ProfileCategory, SyncTask
from bkuser_core.common.enum import AutoLowerEnum
from bkuser_core.departments.models import Department
from bkuser_core.profiles.models import DynamicFieldInfo, Profile
Expand Down Expand Up @@ -125,6 +125,7 @@ class ResourceType(AutoLowerEnum):
CATEGORY = auto()
DEPARTMENT = auto()
PROFILE = auto()
SYNCTASK = auto()

@classmethod
def get_type_name(cls, resource_type: "ResourceType") -> str:
Expand All @@ -142,6 +143,7 @@ def get_by_model(cls, instance) -> "ResourceType":
ProfileCategory: cls.CATEGORY,
DynamicFieldInfo: cls.FIELD,
Profile: cls.PROFILE,
SyncTask: cls.SYNCTASK,
}[type(instance)]

@classmethod
Expand Down Expand Up @@ -196,6 +198,7 @@ def parse_department_path(data):
cls.CATEGORY: {"category.id": "id"},
cls.FIELD: {"field.id": "name"},
cls.PROFILE: {},
cls.SYNCTASK: {"category.id": "category_id"},
}
return _map[resource_type]

Expand Down
4 changes: 2 additions & 2 deletions src/api/bkuser_core/common/error_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,10 @@ def __getattr__(self, code_name):
ErrorCode("USER_IS_LOCKED", _("账号长时间未登录,已被冻结,请联系管理员"), 3210015),
ErrorCode("USER_IS_DISABLED", _("账号已被管理员禁用,请联系管理员"), 3210016),
ErrorCode("DOMAIN_UNKNOWN", _("未知登陆域"), 3210017),
ErrorCode("PASSWORD_EXPIRED", _("该账户密码已到期,请修改密码后登录"), 3210018),
ErrorCode("PASSWORD_EXPIRED", _("该账户密码已到期"), 3210018),
ErrorCode("CATEGORY_NOT_ENABLED", _("用户目录未启用"), 3210019),
ErrorCode("ERROR_FORMAT", _("传入参数错误"), 3210020),
ErrorCode("SHOULD_CHANGE_INITIAL_PASSWORD", _("请修改初始密码"), 3210021),
ErrorCode("SHOULD_CHANGE_INITIAL_PASSWORD", _("平台分配的初始密码未修改"), 3210021),
# 用户相关
ErrorCode("EMAIL_NOT_PROVIDED", _("该用户没有提供邮箱,发送邮件失败")),
ErrorCode("USER_ALREADY_EXISTED", _("该目录下此用户名已存在"), status_code=HTTP_409_CONFLICT),
Expand Down
18 changes: 18 additions & 0 deletions src/api/bkuser_core/profiles/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ class ProfileSerializer(CustomFieldsModelSerializer):
departments = SimpleDepartmentSerializer(many=True, required=False)
extras = serializers.SerializerMethodField(required=False)
leader = LeaderSerializer(many=True, required=False)
last_login_time = serializers.SerializerMethodField(required=False, read_only=True)

def get_last_login_time(self, obj: "Profile") -> Optional[str]:
"""获取用户最近一次登录时间"""
latest_logins = obj.login_set.filter(is_success=True)
if latest_logins:
return latest_logins.latest().create_time

return None

def get_extras(self, obj) -> dict:
"""尝试从 context 中获取默认字段值"""
Expand All @@ -97,6 +106,7 @@ class RapidProfileSerializer(CustomFieldsMixin, serializers.Serializer):

departments = SimpleDepartmentSerializer(many=True, required=False)
leader = LeaderSerializer(many=True, required=False)
last_login_time = serializers.SerializerMethodField(required=False, read_only=True)

create_time = serializers.DateTimeField(required=False, read_only=True)
update_time = serializers.DateTimeField(required=False, read_only=True)
Expand All @@ -120,6 +130,14 @@ class RapidProfileSerializer(CustomFieldsMixin, serializers.Serializer):
status = serializers.CharField(read_only=True)
logo = serializers.CharField(read_only=True, allow_blank=True)

def get_last_login_time(self, obj: "Profile") -> Optional[str]:
"""获取用户最近一次登录时间"""
latest_logins = obj.login_set.filter(is_success=True)
if latest_logins:
return latest_logins.latest().create_time

return None

def get_extras(self, obj: "Profile") -> dict:
"""尝试从 context 中获取默认字段值"""
return get_extras(obj.extras, self.context.get("extra_defaults", {}).copy())
Expand Down
13 changes: 7 additions & 6 deletions src/api/bkuser_core/profiles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class ProfileViewSet(AdvancedModelViewSet, AdvancedListAPIView):
lookup_field = "username"
filter_backends = [ProfileSearchFilter, filters.OrderingFilter]

relation_fields = ["departments", "leader"]
relation_fields = ["departments", "leader", "login_set"]

def get_object(self):
_default_lookup_field = self.lookup_field
Expand Down Expand Up @@ -170,9 +170,12 @@ def list(self, request, *args, **kwargs):
_query_slz.is_valid(True)
query_data = _query_slz.validated_data

fields = query_data.get("fields", self.get_serializer().fields)
fields = query_data.get("fields", [])
if fields:
self._check_fields(fields)
else:
fields = self.get_serializer().fields
self._ensure_enabled_field(request, fields=fields)
self._check_fields(fields)

try:
queryset = self.filter_queryset(self.get_queryset())
Expand All @@ -181,9 +184,7 @@ def list(self, request, *args, **kwargs):
raise error_codes.QUERY_PARAMS_ERROR

# 提前将关系表拿出来
chosen_fields = [_f for _f in self.relation_fields if _f in fields]
if chosen_fields:
queryset = queryset.prefetch_related(*chosen_fields)
queryset = queryset.prefetch_related(*self.relation_fields)

# 当用户请求数据时,判断其是否强制输出原始 username
if not force_use_raw_username(request):
Expand Down
2 changes: 1 addition & 1 deletion src/login/bklogin/templates/account/login_ce.html
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
{% if error_message %}
<span>{{ error_message }}</span>
{% if token_set_password_url %}
<a href="{{ token_set_password_url }}" target="_blank">>>去修改</a>
<a href="{{ token_set_password_url }}" target="_blank">,请修改密码</a>
{% endif %}
{% endif %}
</p>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/src/views/organization/details/UserMaterial.vue
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@
<span class="name">{{$t('最近一次登录时间')}}</span>
<span class="gap">:</span>
<p class="desc">
<span class="text">{{currentProfile.update_time}}</span>
<span class="text">{{currentProfile.last_login_time}}</span>
</p>
</div>
</li>
Expand Down
6 changes: 5 additions & 1 deletion src/pages/src/views/organization/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -885,7 +885,11 @@ export default {
// 查看当前用户的信息
viewDetails(item) {
item.create_time = moment(item.create_time).format('YYYY-MM-DD HH:mm:ss');
item.update_time = moment(item.update_time).format('YYYY-MM-DD HH:mm:ss');
if (item.last_login_time) {
item.last_login_time = moment(item.last_login_time).format('YYYY-MM-DD HH:mm:ss');
} else {
item.last_login_time = '--';
}
this.currentProfile = item;
this.detailsBarInfo.type = 'view';
this.detailsBarInfo.title = this.currentProfile.display_name;
Expand Down
2 changes: 2 additions & 0 deletions src/saas/bkuser_shell/organization/serializers/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class ProfileSerializer(Serializer):
category_id = IntegerField(required=False)
departments = SubDepartmentSerializer(many=True)
update_time = DateTimeField(required=False)
create_time = DateTimeField(required=False)
last_login_time = DateTimeField(required=False)

def get_logo(self, data):
if isinstance(data, dict):
Expand Down
2 changes: 1 addition & 1 deletion src/saas/bkuser_shell/organization/views/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def retrieve(self, request, profile_id):
@inject_serializer(tag=["profiles"])
def restoration(self, request, profile_id):
"""恢复 profile"""
api_instance = bkuser_sdk.ProfilesApi(self.get_api_client_by_request(request))
api_instance = bkuser_sdk.ProfilesApi(self.get_api_client_by_request(request, no_auth=True))
try:
api_instance.v2_profiles_restoration(
lookup_value=profile_id, lookup_field="id", body={}, include_disabled=True
Expand Down
Binary file modified src/saas/media/excel/export_org_tmpl.xlsx
Binary file not shown.
3 changes: 2 additions & 1 deletion src/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ except ApiException as e:

## Documentation for API Endpoints

All URIs are relative to *http://localhost:8000/*
All URIs are relative to *http://localhost:8004/*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
Expand Down Expand Up @@ -255,6 +255,7 @@ Class | Method | HTTP request | Description
- [Department](docs/Department.md)
- [DepartmentAddProfiles](docs/DepartmentAddProfiles.md)
- [DepartmentProfileEdgesSLZ](docs/DepartmentProfileEdgesSLZ.md)
- [DepartmentUpdate](docs/DepartmentUpdate.md)
- [DepartmentsWithAncestors](docs/DepartmentsWithAncestors.md)
- [DynamicFields](docs/DynamicFields.md)
- [Empty](docs/Empty.md)
Expand Down
1 change: 1 addition & 0 deletions src/sdk/bkuser_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from bkuser_sdk.models.department import Department
from bkuser_sdk.models.department_add_profiles import DepartmentAddProfiles
from bkuser_sdk.models.department_profile_edges_slz import DepartmentProfileEdgesSLZ
from bkuser_sdk.models.department_update import DepartmentUpdate
from bkuser_sdk.models.departments_with_ancestors import DepartmentsWithAncestors
from bkuser_sdk.models.dynamic_fields import DynamicFields
from bkuser_sdk.models.empty import Empty
Expand Down
8 changes: 4 additions & 4 deletions src/sdk/bkuser_sdk/api/departments_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ def v2_departments_partial_update(self, body, lookup_value, **kwargs): # noqa:
>>> result = thread.get()

:param async_req bool
:param Department body: (required)
:param DepartmentUpdate body: (required)
:param str lookup_value: (required)
:return: Department
If the method is called asynchronously,
Expand All @@ -650,7 +650,7 @@ def v2_departments_partial_update_with_http_info(self, body, lookup_value, **kwa
>>> result = thread.get()

:param async_req bool
:param Department body: (required)
:param DepartmentUpdate body: (required)
:param str lookup_value: (required)
:return: Department
If the method is called asynchronously,
Expand Down Expand Up @@ -1200,7 +1200,7 @@ def v2_departments_update(self, body, lookup_value, **kwargs): # noqa: E501
>>> result = thread.get()

:param async_req bool
:param Department body: (required)
:param DepartmentUpdate body: (required)
:param str lookup_value: (required)
:return: Department
If the method is called asynchronously,
Expand All @@ -1223,7 +1223,7 @@ def v2_departments_update_with_http_info(self, body, lookup_value, **kwargs): #
>>> result = thread.get()

:param async_req bool
:param Department body: (required)
:param DepartmentUpdate body: (required)
:param str lookup_value: (required)
:return: Department
If the method is called asynchronously,
Expand Down
2 changes: 1 addition & 1 deletion src/sdk/bkuser_sdk/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)):
def __init__(self):
"""Constructor"""
# Default Base url
self.host = "http://localhost:8000/"
self.host = "http://localhost:8004/"
# Temp file folder for downloading files
self.temp_folder_path = None

Expand Down
1 change: 1 addition & 0 deletions src/sdk/bkuser_sdk/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from bkuser_sdk.models.department import Department
from bkuser_sdk.models.department_add_profiles import DepartmentAddProfiles
from bkuser_sdk.models.department_profile_edges_slz import DepartmentProfileEdgesSLZ
from bkuser_sdk.models.department_update import DepartmentUpdate
from bkuser_sdk.models.departments_with_ancestors import DepartmentsWithAncestors
from bkuser_sdk.models.dynamic_fields import DynamicFields
from bkuser_sdk.models.empty import Empty
Expand Down
Loading