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

feat: support manager to change data source user password #1480

Merged
merged 20 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from 19 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
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@
DataSourceDepartment,
DataSourceDepartmentUserRelation,
DataSourceUser,
DataSourceUserDeprecatedPasswordRecord,
DataSourceUserLeaderRelation,
)
from bkuser.apps.tenant.constants import UserFieldDataType
from bkuser.apps.tenant.models import TenantUserCustomField
from bkuser.biz.validators import validate_data_source_user_username
from bkuser.common.hashers import check_password
from bkuser.common.passwd import PasswordValidator
from bkuser.common.validators import validate_phone_with_country_code

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -297,5 +300,35 @@ def validate_extras(self, extras: Dict[str, Any]) -> Dict[str, Any]:
)


class DataSourceUserPasswordResetInputSLZ(serializers.Serializer):
password = serializers.CharField(help_text="数据源用户重置的新密码")
narasux marked this conversation as resolved.
Show resolved Hide resolved

def validate_password(self, password: str) -> str:
# 新密码不可与当前正在使用的密码相同
if check_password(password, self.context["current_password"]):
raise ValidationError(_("新密码不可与当前密码相同"))

# 密码规则校验
plugin_config = self.context["plugin_config"]
ret = PasswordValidator(plugin_config.password_rule.to_rule()).validate(password)
if not ret.ok:
raise ValidationError(_("密码不符合规则:{}").format(ret.exception_message))

reseved_cnt = plugin_config.password_initial.reserved_previous_password_count
# 当历史密码保留数量小于等于 1 时,只需要检查不与当前密码相同即可
if reseved_cnt <= 1:
return password

used_passwords = DataSourceUserDeprecatedPasswordRecord.objects.filter(
user_id=self.context["data_source_user_id"],
)[:reseved_cnt-1].values_list("password", flat=True)

for used_pwd in used_passwords:
if check_password(password, used_pwd):
raise ValidationError(_("新密码不能与近 {} 次使用的密码相同".format(reseved_cnt)))

return password
narasux marked this conversation as resolved.
Show resolved Hide resolved


class DataSourceUserOrganizationPathOutputSLZ(serializers.Serializer):
organization_paths = serializers.ListField(help_text="数据源用户所属部门路径列表", child=serializers.CharField())
5 changes: 5 additions & 0 deletions src/bk-user/bkuser/apis/web/data_source_organization/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
# 数据源部门
path("<int:id>/departments/", views.DataSourceDepartmentsListApi.as_view(), name="data_source_department.list"),
path("users/<int:id>/", views.DataSourceUserRetrieveUpdateApi.as_view(), name="data_source_user.retrieve_update"),
path(
"users/<int:id>/password/",
views.DataSourceUserPasswordResetApi.as_view(),
name="data_source_user.password.reset",
),
# 数据源用户所属部门路径
path(
"users/<int:id>/organization-paths/",
Expand Down
53 changes: 53 additions & 0 deletions src/bk-user/bkuser/apis/web/data_source_organization/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
from collections import defaultdict
from typing import List

from django.db import transaction
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from bkuser.apis.web.data_source_organization.serializers import (
DataSourceUserOrganizationPathOutputSLZ,
DataSourceUserPasswordResetInputSLZ,
DepartmentSearchInputSLZ,
DepartmentSearchOutputSLZ,
LeaderSearchInputSLZ,
Expand All @@ -36,6 +39,8 @@
DataSourceDepartmentRelation,
DataSourceDepartmentUserRelation,
DataSourceUser,
DataSourceUserDeprecatedPasswordRecord,
LocalDataSourceIdentityInfo,
)
from bkuser.apps.permission.constants import PermAction
from bkuser.apps.permission.permissions import perm_class
Expand All @@ -46,6 +51,7 @@
DataSourceUserRelationInfo,
)
from bkuser.common.error_codes import error_codes
from bkuser.common.hashers import make_password
from bkuser.common.views import ExcludePatchAPIViewMixin


Expand Down Expand Up @@ -251,6 +257,53 @@ def put(self, request, *args, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)


class DataSourceUserPasswordResetApi(ExcludePatchAPIViewMixin, generics.UpdateAPIView):
queryset = DataSourceUser.objects.all()
lookup_url_kwarg = "id"
permission_classes = [IsAuthenticated, perm_class(PermAction.MANAGE_TENANT)]

@swagger_auto_schema(
tags=["data_source_organization"],
operation_description="重置数据源用户密码",
request_body=DataSourceUserPasswordResetInputSLZ(),
responses={status.HTTP_204_NO_CONTENT: ""},
)
def put(self, request, *args, **kwargs):
user = self.get_object()
data_source = user.data_source
plugin_config = data_source.get_plugin_cfg()

if not (data_source.is_local and plugin_config.enable_account_password_login):
raise error_codes.DATA_SOURCE_OPERATION_UNSUPPORTED.f(
_("仅可以重置 已经启用账密登录功能 的 本地数据源 的用户密码")
)

identify_info = LocalDataSourceIdentityInfo.objects.get(user=user)
current_password = identify_info.password
slz = DataSourceUserPasswordResetInputSLZ(
data=request.data,
context={
"plugin_config": plugin_config,
"data_source_user_id": user.id,
"current_password": current_password,
},
)
slz.is_valid(raise_exception=True)
raw_password = slz.validated_data["password"]

with transaction.atomic():
identify_info.password = make_password(raw_password)
identify_info.save(update_fields=["password", "password_updated_at", "updated_at"])

DataSourceUserDeprecatedPasswordRecord.objects.create(
user=user,
password=current_password,
operator=request.user.username,
)

return Response(status=status.HTTP_204_NO_CONTENT)


class DataSourceUserOrganizationPathListApi(generics.ListAPIView):
queryset = DataSourceUser.objects.all()
lookup_url_kwarg = "id"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 3.2.20 on 2023-12-20 02:53

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('data_source', '0004_auto_20231201_1650'),
]

operations = [
migrations.CreateModel(
name='DataSourceUserDeprecatedPasswordRecord',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('password', models.CharField(max_length=128, verbose_name='用户曾用密码')),
('operator', models.CharField(max_length=128, verbose_name='操作人')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='data_source.datasourceuser')),
],
options={
'ordering': ['-created_at'],
},
),
]
11 changes: 11 additions & 0 deletions src/bk-user/bkuser/apps/data_source/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@ def check_password(self, raw_password: str) -> bool:
return check_password(raw_password, self.password)


class DataSourceUserDeprecatedPasswordRecord(TimestampedModel):
"""用户密码废弃记录"""

user = models.ForeignKey(DataSourceUser, on_delete=models.CASCADE)
password = models.CharField("用户曾用密码", max_length=128)
operator = models.CharField("操作人", max_length=128)

class Meta:
ordering = ["-created_at"]
narasux marked this conversation as resolved.
Show resolved Hide resolved


class DataSourceDepartment(TimestampedModel):
"""
数据源部门
Expand Down