apiVersion: v1 kind: ConfigMap metadata: name: activities-tasks-configmap namespace: django data: tasks.py: | from datetime import datetime, timedelta from enum import Enum from typing import Optional, Dict, Any, Union import uuid from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.conf import settings from pydantic import BaseModel from config.celery import app from sarex.activities.choices import ACTION_CHOICES from sarex.activities.models import Action from sarex.services import services from sarex.services.gateway.intefaces import SystemLogInterface User = get_user_model() class MethodEnum(str, Enum): get = 'GET' post = 'POST' put = "PUT" patch = "PATCH" delete = "DELETE" class ActionInterface(BaseModel): method: MethodEnum timestamp: datetime uri: str verbose_name: Optional[Any] = None model_name: Optional[str] = None status_code: int succeded: bool ip_address: str user_id: Optional[int] = None id: Optional[Union[int, str]] = None modified: bool request_body: Optional[dict | list] = None response_body: Optional[Dict] = None def validate_action(message: Dict) -> ActionInterface: return ActionInterface(**message) def validate_systemlog(message: Dict) -> SystemLogInterface: return SystemLogInterface(**message) def convert_uuids_to_str(data: Union[dict, list]) -> Union[dict, list]: if isinstance(data, dict): for key, value in data.items(): if isinstance(value, uuid.UUID): data[key] = str(value) elif isinstance(value, (dict, list)): convert_uuids_to_str(value) elif isinstance(data, list): for index, item in enumerate(data): if isinstance(item, uuid.UUID): data[index] = str(item) elif isinstance(item, (dict, list)): convert_uuids_to_str(item) return data @app.task(name="send_to_django_action") def send_to_django_action(message: Dict) -> None: action_data = validate_action(message) if action_data.method == "POST": action_type = ACTION_CHOICES.create action_type_name = "создано" elif action_data.method in ("PUT", "PATCH"): action_type = ACTION_CHOICES.update action_type_name = "изменено" elif action_data.method == "DELETE": action_type = ACTION_CHOICES.delete action_type_name = "удалено" elif action_data.uri == "/api/login/" or action_data.uri.startswith("/api/token"): action_type = ACTION_CHOICES.auth action_type_name = 'Успешно авторизовался' if action_data.succeded: action_data.verbose_name = 'Успешно авторизовался' else: action_data.verbose_name = 'Попытался авторизоваться' else: action_type = ACTION_CHOICES.undefined action_type_name = "" if not action_data.user_id: action_data.user_id = User.objects.get(username='AnonymousUser').id if action_data.model_name: try: target_content_type = ContentType.objects.get(model=action_data.model_name.lower()) target_object_id = action_data.id except ContentType.DoesNotExist: target_content_type = None target_object_id = None else: target_content_type = None target_object_id = None if action_data.id: msg = f"{action_type_name} {action_data.verbose_name}:{action_data.id}" else: msg = f"{action_data.verbose_name}: {action_data.user_id}" if settings.SERVERSETTINGS.logingg_body_action: request_body = convert_uuids_to_str(action_data.request_body) response_body = convert_uuids_to_str(action_data.response_body) else: request_body = None response_body = None item = Action( actor_id=action_data.user_id, action_type=action_type, verb=msg, ip_address=action_data.ip_address, succeded=action_data.modified, timestamp=action_data.timestamp, target_content_type=target_content_type, target_object_id=target_object_id, data={ "uri": action_data.uri, "request_body": request_body, "response_body": response_body, } ) item.save() if settings.SERVERSETTINGS.changelog_rotation: now = datetime.now() - timedelta(days=settings.SERVERSETTINGS.changelog_period_in_days) Action.objects.filter(timestamp__lte=now).delete() @app.task(name="send_to_system_log") def send_to_system_log(message: Dict) -> None: action_data = validate_action(message) multiple_deletion_entity = [] is_admin_request = False if settings.SERVERSETTINGS.donstroi_style: is_admin_request = "/admin/" in action_data.uri if action_data.method == "POST": if is_admin_request and "/change/" in action_data.uri: action_type = "update" action_type_name = "изменено" elif (is_admin_request and action_data.response_body is not None and "delete_selected" in action_data.response_body.get("action", [])): multiple_deletion_entity.extend(action_data.response_body.get('_selected_action', [])) action_type = "delete" action_type_name = "удалено" elif is_admin_request and "/delete/" in action_data.uri: action_type = "delete" action_type_name = "удалено" else: action_type = "create" action_type_name = "создано" elif action_data.method in ("PUT", "PATCH"): action_type = "update" action_type_name = "изменено" elif action_data.method == "DELETE": action_type = "delete" action_type_name = "удалено" elif action_data.uri == "/api/login/": action_type = "auth" action_type_name = 'Успешно авторизовался' if action_data.succeded: action_data.verbose_name = 'Успешно авторизовался' else: action_data.verbose_name = 'Попытался авторизоваться' else: action_type = "undefined" action_type_name = "" if action_data.id: msg = f"{action_type_name} {action_data.verbose_name}:{action_data.id}" elif settings.SERVERSETTINGS.donstroi_style and multiple_deletion_entity: str_ids_delete_entitys = " ".join(multiple_deletion_entity) msg = f"{action_type_name} {action_data.verbose_name}:{str_ids_delete_entitys}" else: msg = f"{action_data.verbose_name}: {action_data.user_id}" if action_data.id and action_data.id.isdigit(): instance_id_filed = "instance_id" else: instance_id_filed = "instance_uuid" if action_data.succeded: status = "successful" else: status = "unsuccessful" timestamp_iso = action_data.timestamp.isoformat() formatted_timestamp = datetime.strptime(timestamp_iso, '%Y-%m-%dT%H:%M:%S.%f').strftime('%Y-%m-%dT%H:%M:%SZ') metadata = { "id": action_data.id, "model_name": action_data.model_name, "ip_address": action_data.ip_address, "instance_id_filed": action_data.id, } if settings.SERVERSETTINGS.donstroi_style and is_admin_request: metadata['from_admin_panel'] = True if not settings.SERVERSETTINGS.logingg_body_action: metadata['request_body'] = action_data.request_body metadata['response_body'] = action_data.response_body if action_data.model_name: action_data.model_name = action_data.model_name.lower() system_log_data = validate_systemlog( { "actor_id": action_data.user_id, "event_name": action_type, "model_name": action_data.model_name, instance_id_filed: action_data.id, "registered_at": formatted_timestamp, "metadata": metadata, "message": msg, "status": status, } ) services.gateway.send_system_log(system_log_data)