|
| 1 | +import contextlib |
| 2 | + |
1 | 3 | from auditlog.models import LogEntry |
2 | 4 | from django.conf import settings |
3 | 5 | from django.contrib.contenttypes.models import ContentType |
|
14 | 16 | def finding_group_post_delete(sender, instance, using, origin, **kwargs): |
15 | 17 | if instance == origin: |
16 | 18 | description = _('The finding group "%(name)s" was deleted') % {"name": instance.name} |
| 19 | + user = None |
| 20 | + |
17 | 21 | if settings.ENABLE_AUDITLOG: |
18 | | - if le := LogEntry.objects.filter( |
19 | | - action=LogEntry.Action.DELETE, |
20 | | - content_type=ContentType.objects.get(app_label="dojo", model="finding_group"), |
21 | | - object_id=instance.id, |
22 | | - ).order_by("-id").first(): |
| 22 | + # First try to find deletion author in pghistory events |
| 23 | + from dojo.pghistory_models import DojoEvents |
| 24 | + # Look for delete events for this specific finding_group instance |
| 25 | + pghistory_delete_events = DojoEvents.objects.filter( |
| 26 | + pgh_obj_model="dojo.Finding_Group", |
| 27 | + pgh_obj_id=instance.id, |
| 28 | + pgh_label="delete", |
| 29 | + ).order_by("-pgh_created_at") |
| 30 | + |
| 31 | + if pghistory_delete_events.exists(): |
| 32 | + latest_delete = pghistory_delete_events.first() |
| 33 | + # Extract user from pghistory context |
| 34 | + if latest_delete.user: |
| 35 | + from django.contrib.auth import get_user_model |
| 36 | + User = get_user_model() |
| 37 | + with contextlib.suppress(User.DoesNotExist): |
| 38 | + user = User.objects.get(id=latest_delete.user) |
| 39 | + |
| 40 | + # Fall back to django-auditlog if no user found in pghistory |
| 41 | + if not user: |
| 42 | + if le := LogEntry.objects.filter( |
| 43 | + action=LogEntry.Action.DELETE, |
| 44 | + content_type=ContentType.objects.get(app_label="dojo", model="finding_group"), |
| 45 | + object_id=instance.id, |
| 46 | + ).order_by("-id").first(): |
| 47 | + user = le.actor |
| 48 | + |
| 49 | + # Update description with user if found |
| 50 | + if user: |
23 | 51 | description = _('The finding group "%(name)s" was deleted by %(user)s') % { |
24 | | - "name": instance.name, "user": le.actor} |
| 52 | + "name": instance.name, "user": user} |
25 | 53 | create_notification(event="finding_group_deleted", # template does not exists, it will default to "other" but this event name needs to stay because of unit testing |
26 | 54 | title=_("Deletion of %(name)s") % {"name": instance.name}, |
27 | 55 | description=description, |
|
0 commit comments