From 0ae6e84818a17957463a83cd5ba1ed9b0a13a3b4 Mon Sep 17 00:00:00 2001 From: rolinchen Date: Tue, 3 Dec 2024 16:46:14 +0800 Subject: [PATCH] resolve: modify the code style --- .../bkuser/apis/web/data_source/views.py | 20 +- src/bk-user/bkuser/apis/web/idp/views.py | 24 ++- .../apis/web/organization/views/relations.py | 12 +- .../apis/web/organization/views/users.py | 4 +- src/bk-user/bkuser/biz/auditor.py | 182 ++++++++++-------- 5 files changed, 133 insertions(+), 109 deletions(-) diff --git a/src/bk-user/bkuser/apis/web/data_source/views.py b/src/bk-user/bkuser/apis/web/data_source/views.py index b5a87a6a8..c2e8f9ace 100644 --- a/src/bk-user/bkuser/apis/web/data_source/views.py +++ b/src/bk-user/bkuser/apis/web/data_source/views.py @@ -186,9 +186,9 @@ def post(self, request, *args, **kwargs): ) # 【审计】创建数据源审计对象 - auditor = DataSourceAuditor(request.user.username, current_tenant_id, ds) + auditor = DataSourceAuditor(request.user.username, current_tenant_id) # 【审计】将审计记录保存至数据库 - auditor.record_create() + auditor.record_create(ds) return Response( DataSourceCreateOutputSLZ(instance={"id": ds.id}).data, @@ -243,8 +243,8 @@ def put(self, request, *args, **kwargs): data = slz.validated_data # 【审计】创建数据源审计对象并记录变更前数据 - auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id, data_source) - auditor.pre_record_data_before() + auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id) + auditor.pre_record_data_before(data_source) with transaction.atomic(): data_source.field_mapping = data["field_mapping"] @@ -289,8 +289,8 @@ def delete(self, request, *args, **kwargs): waiting_delete_idps = Idp.objects.filter(**idp_filters) # 【审计】创建数据源审计对象并记录变更前数据 - auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id, data_source) - auditor.pre_record_data_before(list(waiting_delete_idps)) + auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id) + auditor.pre_record_data_before(data_source, list(waiting_delete_idps)) with transaction.atomic(): # 删除认证源敏感信息 @@ -506,9 +506,9 @@ def post(self, request, *args, **kwargs): raise error_codes.DATA_SOURCE_IMPORT_FAILED.f(str(e)) # 【审计】创建数据源审计对象 - auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id, data_source) + auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id) # 【审计】将审计记录保存至数据库 - auditor.record_sync(options) + auditor.record_sync(data_source, options) return Response( DataSourceImportOrSyncOutputSLZ( @@ -554,9 +554,9 @@ def post(self, request, *args, **kwargs): raise error_codes.DATA_SOURCE_SYNC_TASK_CREATE_FAILED.f(str(e)) # 【审计】创建数据源审计对象 - auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id, data_source) + auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id) # 【审计】将审计记录保存至数据库 - auditor.record_sync(options) + auditor.record_sync(data_source, options) return Response( DataSourceImportOrSyncOutputSLZ( diff --git a/src/bk-user/bkuser/apis/web/idp/views.py b/src/bk-user/bkuser/apis/web/idp/views.py index 13ebc14d6..d4e85e088 100644 --- a/src/bk-user/bkuser/apis/web/idp/views.py +++ b/src/bk-user/bkuser/apis/web/idp/views.py @@ -30,7 +30,7 @@ from bkuser.apps.idp.models import Idp, IdpPlugin, IdpSensitiveInfo from bkuser.apps.permission.constants import PermAction from bkuser.apps.permission.permissions import perm_class -from bkuser.biz.auditor import IdpAuditor +from bkuser.biz.auditor import DataSourceAuditor, IdpAuditor from bkuser.common.error_codes import error_codes from bkuser.common.views import ExcludePatchAPIViewMixin from bkuser.idp_plugins.constants import BuiltinIdpPluginEnum @@ -151,9 +151,9 @@ def post(self, request, *args, **kwargs): ) # 【审计】创建认证源审计对象 - auditor = IdpAuditor(request.user.username, current_tenant_id, idp) + auditor = IdpAuditor(request.user.username, current_tenant_id) # 【审计】将审计记录保存至数据库 - auditor.record_create() + auditor.record_create(idp) return Response(IdpCreateOutputSLZ(instance=idp).data, status=status.HTTP_201_CREATED) @@ -222,8 +222,8 @@ def put(self, request, *args, **kwargs): data = slz.validated_data # 【审计】创建认证源审计对象,并记录变更前数据 - auditor = IdpAuditor(request.user.username, current_tenant_id, idp) - auditor.pre_record_data_before() + auditor = IdpAuditor(request.user.username, current_tenant_id) + auditor.pre_record_data_before(idp) with transaction.atomic(): idp.name = data["name"] @@ -325,9 +325,9 @@ def post(self, request, *args, **kwargs): data_source.set_plugin_cfg(plugin_config) # 【审计】创建认证源审计对象 - auditor = IdpAuditor(request.user.username, current_tenant_id, idp) + auditor = IdpAuditor(request.user.username, current_tenant_id) # 【审计】将审计记录保存至数据库 - auditor.record_create() + auditor.record_create(idp) return Response(IdpCreateOutputSLZ(instance=idp).data, status=status.HTTP_201_CREATED) @@ -393,8 +393,11 @@ def put(self, request, *args, **kwargs): data = slz.validated_data # 【审计】创建认证源审计对象并记录变更前数据 - auditor = IdpAuditor(request.user.username, current_tenant_id, idp) - auditor.pre_record_data_before() + idp_auditor = IdpAuditor(request.user.username, current_tenant_id) + idp_auditor.pre_record_data_before(idp) + # 【审计】创建数据源审计对象并记录变更前数据(本地数据源插件配置) + ds_auditor = DataSourceAuditor(request.user.username, data_source.owner_tenant_id) + ds_auditor.pre_record_data_before(data_source) with transaction.atomic(): idp.name = data["name"] @@ -404,6 +407,7 @@ def put(self, request, *args, **kwargs): data_source.set_plugin_cfg(data["plugin_config"]) # 【审计】将审计记录保存至数据库 - auditor.record_update(idp) + idp_auditor.record_update(idp) + ds_auditor.record_update(data_source) return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/src/bk-user/bkuser/apis/web/organization/views/relations.py b/src/bk-user/bkuser/apis/web/organization/views/relations.py index fc1410008..ba89b86b4 100644 --- a/src/bk-user/bkuser/apis/web/organization/views/relations.py +++ b/src/bk-user/bkuser/apis/web/organization/views/relations.py @@ -73,7 +73,6 @@ def post(self, request, *args, **kwargs): request.user.username, cur_tenant_id, data_source_user_ids, - OperationEnum.CREATE_USER_DEPARTMENT, ) auditor.pre_record_data_before() @@ -86,7 +85,7 @@ def post(self, request, *args, **kwargs): DataSourceDepartmentUserRelation.objects.bulk_create(relations, ignore_conflicts=True) # 【审计】将审计记录保存至数据库 - auditor.record(extras={"department_ids": list(data_source_dept_ids)}) + auditor.record(OperationEnum.CREATE_USER_DEPARTMENT, extras={"department_ids": list(data_source_dept_ids)}) return Response(status=status.HTTP_204_NO_CONTENT) @@ -126,7 +125,6 @@ def put(self, request, *args, **kwargs): request.user.username, cur_tenant_id, data_source_user_ids, - OperationEnum.MODIFY_USER_DEPARTMENT, ) auditor.pre_record_data_before() @@ -142,7 +140,7 @@ def put(self, request, *args, **kwargs): DataSourceDepartmentUserRelation.objects.bulk_create(relations) # 【审计】将审计记录保存至数据库 - auditor.record(extras={"department_ids": list(data_source_dept_ids)}) + auditor.record(OperationEnum.MODIFY_USER_DEPARTMENT, extras={"department_ids": list(data_source_dept_ids)}) return Response(status=status.HTTP_204_NO_CONTENT) @@ -178,7 +176,6 @@ def patch(self, request, *args, **kwargs): request.user.username, cur_tenant_id, data_source_user_ids, - OperationEnum.MODIFY_USER_DEPARTMENT, ) auditor.pre_record_data_before() @@ -196,7 +193,7 @@ def patch(self, request, *args, **kwargs): DataSourceDepartmentUserRelation.objects.bulk_create(relations, ignore_conflicts=True) # 【审计】将审计记录保存至数据库 - auditor.record(extras={"department_id": source_data_source_dept.id}) + auditor.record(OperationEnum.MODIFY_USER_DEPARTMENT, extras={"department_id": source_data_source_dept.id}) return Response(status=status.HTTP_204_NO_CONTENT) @@ -234,7 +231,6 @@ def delete(self, request, *args, **kwargs): request.user.username, cur_tenant_id, data_source_user_ids, - OperationEnum.DELETE_USER_DEPARTMENT, ) auditor.pre_record_data_before() @@ -243,6 +239,6 @@ def delete(self, request, *args, **kwargs): ).delete() # 【审计】将审计记录保存至数据库 - auditor.record(extras={"department_id": source_data_source_dept.id}) + auditor.record(OperationEnum.DELETE_USER_DEPARTMENT, extras={"department_id": source_data_source_dept.id}) return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/src/bk-user/bkuser/apis/web/organization/views/users.py b/src/bk-user/bkuser/apis/web/organization/views/users.py index 69601392e..8343d2bac 100644 --- a/src/bk-user/bkuser/apis/web/organization/views/users.py +++ b/src/bk-user/bkuser/apis/web/organization/views/users.py @@ -507,7 +507,7 @@ def put(self, request, *args, **kwargs): # 【审计】创建租户用户修改操作审计对象并记录变更前的用户相关信息(数据源用户、部门、上级、租户用户) auditor = TenantUserUpdateAuditor(request.user.username, cur_tenant_id) - auditor.pre_record_data_before(tenant_user, data_source_user) + auditor.pre_record_data_before(tenant_user) with transaction.atomic(): data_source_user.username = data["username"] @@ -535,7 +535,7 @@ def put(self, request, *args, **kwargs): tenant_user.save(update_fields=["account_expired_at", "status", "updater", "updated_at"]) # 【审计】将审计记录保存至数据库 - auditor.record(tenant_user, data_source_user) + auditor.record(tenant_user) return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/src/bk-user/bkuser/biz/auditor.py b/src/bk-user/bkuser/biz/auditor.py index 326ecd87a..ac2f3d6a0 100644 --- a/src/bk-user/bkuser/biz/auditor.py +++ b/src/bk-user/bkuser/biz/auditor.py @@ -43,26 +43,25 @@ class DataSourceAuditor: """用于记录数据源相关操作的审计""" - def __init__(self, operator: str, tenant_id: str, data_source: DataSource): + def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.data_source = data_source self.data_befores: Dict[str, Any] = {} - def pre_record_data_before(self, waiting_delete_idps: List[Idp] | None = None): + def pre_record_data_before(self, data_source: DataSource, waiting_delete_idps: List[Idp] | None = None): """记录变更前的相关数据记录""" - self.data_befores["data_source"] = get_model_dict(self.data_source) + self.data_befores["data_source"] = get_model_dict(data_source) self.data_befores["idps"] = [get_model_dict(idp) for idp in (waiting_delete_idps or [])] - def record_create(self): + def record_create(self, data_source: DataSource): """记录数据源创建操作""" add_audit_record( operator=self.operator, tenant_id=self.tenant_id, operation=OperationEnum.CREATE_DATA_SOURCE, object_type=ObjectTypeEnum.DATA_SOURCE, - object_id=self.data_source.id, - data_after=get_model_dict(self.data_source), + object_id=data_source.id, + data_after=get_model_dict(data_source), ) def record_update(self, data_source: DataSource): @@ -72,7 +71,7 @@ def record_update(self, data_source: DataSource): tenant_id=self.tenant_id, operation=OperationEnum.MODIFY_DATA_SOURCE, object_type=ObjectTypeEnum.DATA_SOURCE, - object_id=self.data_source.id, + object_id=data_source.id, data_before=self.data_befores["data_source"], data_after=get_model_dict(data_source), ) @@ -102,14 +101,14 @@ def record_delete(self): objects=[data_source_audit_object] + idp_audit_objects, ) - def record_sync(self, options: DataSourceSyncOptions): + def record_sync(self, data_source: DataSource, options: DataSourceSyncOptions): """记录数据源同步操作""" add_audit_record( operator=self.operator, tenant_id=self.tenant_id, operation=OperationEnum.SYNC_DATA_SOURCE, object_type=ObjectTypeEnum.DATA_SOURCE, - object_id=self.data_source.id, + object_id=data_source.id, extras={"overwrite": options.overwrite, "incremental": options.incremental, "trigger": options.trigger}, ) @@ -120,44 +119,45 @@ class TenantUserUpdateAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.data_befores: Dict[str, Any] = {} - self.audit_objects: List[AuditObject] = [] - def pre_record_data_before(self, tenant_user: TenantUser, data_source_user: DataSourceUser): + def pre_record_data_before(self, tenant_user: TenantUser): """记录变更前的相关数据记录""" # 初始化对应 tenant_user 的审计数据 self.data_befores = { "tenant_user": get_model_dict(tenant_user), - "data_source_user": get_model_dict(data_source_user), + "data_source_user": get_model_dict(tenant_user.data_source_user), # 记录修改前的用户部门 "department_ids": list( DataSourceDepartmentUserRelation.objects.filter( - user=data_source_user, + user=tenant_user.data_source_user, ).values_list("department_id", flat=True) ), # 记录修改前的用户上级 "leader_ids": list( - DataSourceUserLeaderRelation.objects.filter(user=data_source_user).values_list("leader_id", flat=True) + DataSourceUserLeaderRelation.objects.filter(user=tenant_user.data_source_user).values_list( + "leader_id", flat=True + ) ), } - def record(self, tenant_user: TenantUser, data_source_user: DataSourceUser): + def record(self, tenant_user: TenantUser): """组装相关数据,并调用 apps.audit 模块里的方法进行记录""" - ds_user_id = data_source_user.id - ds_user_name = data_source_user.username + ds_user_id = tenant_user.data_source_user.id + ds_user_name = tenant_user.data_source_user.username ds_user_object = {"id": ds_user_id, "name": ds_user_name, "type": ObjectTypeEnum.DATA_SOURCE_USER} - self.audit_objects.extend( + audit_objects: List[AuditObject] = [] + audit_objects.extend( [ # 数据源用户本身信息 AuditObject( **ds_user_object, operation=OperationEnum.MODIFY_DATA_SOURCE_USER, data_before=self.data_befores["data_source_user"], - data_after=get_model_dict(data_source_user), + data_after=get_model_dict(tenant_user.data_source_user), ), # 数据源用户的部门 AuditObject( @@ -167,7 +167,7 @@ def record(self, tenant_user: TenantUser, data_source_user: DataSourceUser): data_after={ "department_ids": list( DataSourceDepartmentUserRelation.objects.filter( - user=data_source_user, + user=tenant_user.data_source_user, ).values_list("department_id", flat=True) ) }, @@ -179,7 +179,7 @@ def record(self, tenant_user: TenantUser, data_source_user: DataSourceUser): data_before={"leader_ids": self.data_befores["leader_ids"]}, data_after={ "leader_ids": list( - DataSourceUserLeaderRelation.objects.filter(user=data_source_user).values_list( + DataSourceUserLeaderRelation.objects.filter(user=tenant_user.data_source_user).values_list( "leader_id", flat=True ) ) @@ -196,7 +196,7 @@ def record(self, tenant_user: TenantUser, data_source_user: DataSourceUser): ] ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) class TenantUserDestroyAuditor: @@ -205,11 +205,9 @@ class TenantUserDestroyAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.data_befores: Dict[str, Dict] = {} - self.audit_objects: List[AuditObject] = [] - def pre_record_data_before(self, tenant_user: TenantUser, data_source_user: DataSourceUser): + def pre_record_data_before(self, tenant_user: TenantUser): """记录变更前的相关数据记录""" # 为每个用户的审计数据创建唯一的键 @@ -220,16 +218,16 @@ def pre_record_data_before(self, tenant_user: TenantUser, data_source_user: Data if tenant_user.tenant_id == self.tenant_id: self.data_befores[tenant_user_id] = { "tenant_user": get_model_dict(tenant_user), - "data_source_user": get_model_dict(data_source_user), + "data_source_user": get_model_dict(tenant_user.data_source_user), # 记录修改前的用户部门 "department_ids": list( DataSourceDepartmentUserRelation.objects.filter( - user=data_source_user, + user=tenant_user.data_source_user, ).values_list("department_id", flat=True) ), # 记录修改前的用户上级 "leader_ids": list( - DataSourceUserLeaderRelation.objects.filter(user=data_source_user).values_list( + DataSourceUserLeaderRelation.objects.filter(user=tenant_user.data_source_user).values_list( "leader_id", flat=True ) ), @@ -246,10 +244,12 @@ def batch_pre_record_data_before(self, tenant_users: List[TenantUser]): """批量记录变更前的相关数据记录""" for tenant_user in tenant_users: - self.pre_record_data_before(tenant_user, tenant_user.data_source_user) + self.pre_record_data_before(tenant_user) def record(self): """组装相关数据,并调用 apps.audit 模块里的方法进行记录""" + audit_objects: List[AuditObject] = [] + for tenant_user_id, data_befores in self.data_befores.items(): # 若为本租户下的用户 if data_befores["tenant_id"] == self.tenant_id: @@ -258,19 +258,20 @@ def record(self): "name": data_befores["data_source_user"]["username"], "type": ObjectTypeEnum.DATA_SOURCE_USER, } - self.audit_objects.extend(self.generate_audit_objects(data_befores, tenant_user_id, ds_user_object)) + audit_objects.extend(self.generate_audit_objects(data_befores, tenant_user_id, ds_user_object)) # 若为协同租户下的用户 else: - self.audit_objects.append( + audit_objects.append( # 协同租户用户 AuditObject( id=tenant_user_id, type=ObjectTypeEnum.TENANT_USER, operation=OperationEnum.DELETE_COLLABORATION_TENANT_USER, data_before=data_befores["tenant_user"], + extras={"collaboration_tenant_id": data_befores["tenant_id"]}, ) ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) @staticmethod def generate_audit_objects(data_befores, tenant_user_id, ds_user_object): @@ -311,10 +312,10 @@ class TenantUserCreateAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.audit_objects: List[AuditObject] = [] def record(self, tenant_users: List[TenantUser]): """组装相关数据,并调用 apps.audit 模块里的方法进行记录""" + audit_objects: List[AuditObject] = [] for tenant_user in tenant_users: # 若为本租户下的用户 if tenant_user.tenant_id == self.tenant_id: @@ -325,7 +326,7 @@ def record(self, tenant_users: List[TenantUser]): "type": ObjectTypeEnum.DATA_SOURCE_USER, } - self.audit_objects.extend( + audit_objects.extend( [ # 数据源用户本身信息 AuditObject( @@ -356,29 +357,28 @@ def record(self, tenant_users: List[TenantUser]): ) # 若为协同租户下的用户 else: - self.audit_objects.append( + audit_objects.append( # 协同租户用户信息 AuditObject( id=tenant_user.id, type=ObjectTypeEnum.TENANT_USER, operation=OperationEnum.CREATE_COLLABORATION_TENANT_USER, data_after=get_model_dict(tenant_user), + extras={"collaboration_tenant_id": tenant_user.tenant_id}, ), ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) class TenantUserDepartmentRelationsAuditor: """用于记录用户-部门关系变更操作的审计""" - def __init__(self, operator: str, tenant_id: str, data_source_user_ids: List[int], operation: OperationEnum): + def __init__(self, operator: str, tenant_id: str, data_source_user_ids: List[int]): self.operator = operator self.tenant_id = tenant_id - self.audit_objects: List[AuditObject] = [] self.data_befores: Dict[int, Dict] = {} self.data_source_user_ids = data_source_user_ids - self.operation = operation def pre_record_data_before(self): """记录变更前的相关数据记录""" @@ -389,7 +389,7 @@ def pre_record_data_before(self): for data_source_user_id in self.data_source_user_ids: self.data_befores[data_source_user_id] = {"department_ids": data_before_user_dept_map[data_source_user_id]} - def record(self, extras: Dict[str, List] | None = None): + def record(self, operation: OperationEnum, extras: Dict[str, List] | None = None): """批量记录""" data_source_users = DataSourceUser.objects.filter( id__in=self.data_source_user_ids, @@ -397,21 +397,23 @@ def record(self, extras: Dict[str, List] | None = None): # 记录变更后的用户与部门之间的映射关系 data_after_user_dept_map = self.get_user_department_map(self.data_source_user_ids) + audit_objects: List[AuditObject] = [] + for data_source_user in data_source_users: data_before = self.data_befores[data_source_user.id] data_after = {"department_ids": data_after_user_dept_map[data_source_user.id]} - self.audit_objects.append( + audit_objects.append( AuditObject( id=data_source_user.id, name=data_source_user.username, type=ObjectTypeEnum.DATA_SOURCE_USER, - operation=self.operation, + operation=operation, data_before=data_before, data_after=data_after, extras=extras or {}, ) ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) @staticmethod def get_user_department_map(data_source_user_ids: List[int]) -> Dict: @@ -434,7 +436,6 @@ class TenantUserLeaderRelationsUpdateAuditor: def __init__(self, operator: str, tenant_id: str, data_source_user_ids: List[int]): self.operator = operator self.tenant_id = tenant_id - self.audit_objects: List[AuditObject] = [] self.data_befores: Dict[int, Dict] = {} self.data_source_user_ids = data_source_user_ids @@ -455,10 +456,12 @@ def record(self, extras: Dict[str, List] | None = None): # 记录变更后的用户与上级之间的映射关系 data_after_user_leader_map = self.get_user_leader_map(self.data_source_user_ids) + audit_objects: List[AuditObject] = [] + for data_source_user in data_source_users: data_before = self.data_befores[data_source_user.id] data_after = {"leader_ids": data_after_user_leader_map[data_source_user.id]} - self.audit_objects.append( + audit_objects.append( AuditObject( id=data_source_user.id, name=data_source_user.username, @@ -469,7 +472,7 @@ def record(self, extras: Dict[str, List] | None = None): extras=extras or {}, ) ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) @staticmethod def get_user_leader_map(data_source_user_ids: List[int]) -> Dict: @@ -492,7 +495,6 @@ class TenantUserAccountExpiredAtUpdateAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.audit_objects: List[AuditObject] = [] self.data_befores: Dict[str, Dict] = {} def pre_record_data_before(self, tenant_user: TenantUser): @@ -507,6 +509,8 @@ def batch_pre_record_data_before(self, tenant_users: List[TenantUser]): def record(self, tenant_user: TenantUser): # 重新获取 tenant_user 数据 + # Q: 为什么要重新获取? + # A: tenant_user 的 account_expired_at 字段在存入数据库时会被转换为 UTC 时间,所以需要重新获取 tenant_user.refresh_from_db() add_audit_record( @@ -523,8 +527,10 @@ def record(self, tenant_user: TenantUser): ) def batch_record(self, tenant_users: List[TenantUser]): - for tenant_user in tenant_users: - self.audit_objects.append( + audit_objects: List[AuditObject] = [] + + audit_objects.extend( + [ AuditObject( id=tenant_user.id, type=ObjectTypeEnum.TENANT_USER, @@ -535,8 +541,10 @@ def batch_record(self, tenant_users: List[TenantUser]): "status": tenant_user.status, }, ) - ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + for tenant_user in tenant_users + ] + ) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) class TenantUserStatusUpdateAuditor: @@ -545,7 +553,6 @@ class TenantUserStatusUpdateAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.audit_objects: List[AuditObject] = [] self.data_befores: Dict[str, Dict] = {} def pre_record_data_before(self, tenant_user: TenantUser): @@ -567,8 +574,10 @@ def record(self, tenant_user: TenantUser): ) def batch_record(self, tenant_users: List[TenantUser]): - for tenant_user in tenant_users: - self.audit_objects.append( + audit_objects: List[AuditObject] = [] + + audit_objects.extend( + [ AuditObject( id=tenant_user.id, type=ObjectTypeEnum.TENANT_USER, @@ -576,8 +585,10 @@ def batch_record(self, tenant_users: List[TenantUser]): data_before=self.data_befores[tenant_user.id], data_after={"status": tenant_user.status}, ) - ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + for tenant_user in tenant_users + ] + ) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) class TenantUserPasswordResetAuditor: @@ -586,7 +597,6 @@ class TenantUserPasswordResetAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.audit_objects: List[AuditObject] = [] def record(self, data_source_user: DataSourceUser, extras: Dict[str, int]): add_audit_record( @@ -600,8 +610,10 @@ def record(self, data_source_user: DataSourceUser, extras: Dict[str, int]): ) def batch_record(self, data_source_users: List[DataSourceUser], extras: Dict[str, int]): - for data_source_user in data_source_users: - self.audit_objects.append( + audit_objects: List[AuditObject] = [] + + audit_objects.extend( + [ AuditObject( id=data_source_user.id, type=ObjectTypeEnum.DATA_SOURCE_USER, @@ -609,32 +621,33 @@ def batch_record(self, data_source_users: List[DataSourceUser], extras: Dict[str operation=OperationEnum.MODIFY_USER_PASSWORD, extras=extras, ) - ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_objects) + for data_source_user in data_source_users + ] + ) + batch_add_audit_records(self.operator, self.tenant_id, audit_objects) class IdpAuditor: """用于记录认证源相关操作的审计""" - def __init__(self, operator: str, tenant_id: str, idp: Idp): + def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id self.data_before: Dict[str, Any] = {} - self.idp = idp - def pre_record_data_before(self): + def pre_record_data_before(self, idp: Idp): """记录变更前的相关数据记录""" - self.data_before = get_model_dict(self.idp) + self.data_before = get_model_dict(idp) - def record_create(self): + def record_create(self, idp: Idp): """记录认证源创建操作""" add_audit_record( operator=self.operator, tenant_id=self.tenant_id, operation=OperationEnum.CREATE_IDP, object_type=ObjectTypeEnum.IDP, - object_id=self.idp.id, - data_after=get_model_dict(self.idp), + object_id=idp.id, + data_after=get_model_dict(idp), ) def record_update(self, idp: Idp): @@ -657,7 +670,6 @@ def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id self.data_befores: Dict[int, Any] = {} - self.audit_records: List[AuditObject] = [] def pre_record_data_before(self, tenant_department: TenantDepartment): """记录变更前的相关数据记录""" @@ -684,6 +696,7 @@ def batch_pre_record_data_before(self, tenant_departments: List[TenantDepartment def record_create(self, tenant_departments: List[TenantDepartment]): """记录部门创建操作""" + audit_records = [] for tenant_department in tenant_departments: # 若为本租户下的部门 if tenant_department.tenant_id == self.tenant_id: @@ -699,7 +712,7 @@ def record_create(self, tenant_departments: List[TenantDepartment]): department=data_source_department, data_source=data_source_department.data_source ).parent_id - self.audit_records.extend( + audit_records.extend( [ # 租户部门 AuditObject( @@ -724,16 +737,17 @@ def record_create(self, tenant_departments: List[TenantDepartment]): ) else: # 若为协同租户下的部门 - self.audit_records.append( + audit_records.append( # 协同租户部门 AuditObject( id=tenant_department.id, type=ObjectTypeEnum.TENANT_DEPARTMENT, operation=OperationEnum.CREATE_COLLABORATION_TENANT_DEPARTMENT, data_after=get_model_dict(tenant_department), + extras={"collaboration_tenant_id": tenant_department.tenant_id}, ) ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_records) + batch_add_audit_records(self.operator, self.tenant_id, audit_records) def record_update(self, tenant_department: TenantDepartment): """记录部门更新操作""" @@ -769,6 +783,7 @@ def record_update_parent_department(self, tenant_department: TenantDepartment): def record_delete(self): """记录部门删除操作""" + audit_records = [] for tenant_department_id, data_befores in self.data_befores.items(): # 若为本租户下的部门 if data_befores["tenant_id"] == self.tenant_id: @@ -777,7 +792,7 @@ def record_delete(self): "type": ObjectTypeEnum.DATA_SOURCE_DEPARTMENT, "name": data_befores["data_source_department"]["name"], } - self.audit_records.extend( + audit_records.extend( [ # 租户部门 AuditObject( @@ -802,17 +817,18 @@ def record_delete(self): ) else: # 若为协同租户下的部门 - self.audit_records.append( + audit_records.append( # 协同租户部门 AuditObject( id=tenant_department_id, type=ObjectTypeEnum.TENANT_DEPARTMENT, operation=OperationEnum.DELETE_COLLABORATION_TENANT_DEPARTMENT, data_before=data_befores["collaboration_tenant_department"], + extras={"collaboration_tenant_id": data_befores["tenant_id"]}, ) ) - batch_add_audit_records(self.operator, self.tenant_id, self.audit_records) + batch_add_audit_records(self.operator, self.tenant_id, audit_records) class VirtualUserAuditor: @@ -905,7 +921,11 @@ def pre_record_data_before(self, tenant_user: TenantUser): def record_update_email(self, tenant_user: TenantUser): """记录用户邮箱更新操作""" + # 重新获取 tenant_user 数据 + # Q: 为什么要重新获取? + # A: 在更新邮箱的接口中,没有对 tenant_user 进行 save 操作,所以需要重新获取 tenant_user.refresh_from_db() + add_audit_record( operator=self.operator, tenant_id=self.tenant_id, @@ -918,7 +938,11 @@ def record_update_email(self, tenant_user: TenantUser): def record_update_phone(self, tenant_user: TenantUser): """记录用户手机号更新操作""" + # 重新获取 tenant_user 数据 + # Q: 为什么要重新获取? + # A: 在更新手机号的接口中,没有对 tenant_user 进行 save 操作,所以需要重新获取 tenant_user.refresh_from_db() + add_audit_record( operator=self.operator, tenant_id=self.tenant_id, @@ -999,7 +1023,6 @@ class TenantRealManagerAuditor: def __init__(self, operator: str, tenant_id: str): self.operator = operator self.tenant_id = tenant_id - self.tenant_name = Tenant.objects.get(id=tenant_id).name self.data_befores: Dict[str, Any] = {} def pre_record_data_before(self): @@ -1009,6 +1032,7 @@ def pre_record_data_before(self): tenant_id=self.tenant_id, tenant_user__data_source__type=DataSourceTypeEnum.REAL ).values_list("tenant_user_id", flat=True) ) + self.data_befores["tenant_name"] = Tenant.objects.get(id=self.tenant_id).name def record_create(self): """记录租户实名管理员创建操作""" @@ -1025,7 +1049,7 @@ def create_audit_record(self, operation: OperationEnum): operation=operation, object_type=ObjectTypeEnum.TENANT, object_id=self.tenant_id, - object_name=self.tenant_name, + object_name=self.data_befores["tenant_name"], data_before={"real_manager_ids": self.data_befores["real_manager_ids"]}, data_after={ "real_manager_ids": list(