|
| 1 | +from datetime import datetime, timezone |
| 2 | +from typing import Callable, Optional, Union |
| 3 | + |
| 4 | +from django.conf import settings |
| 5 | +from django.contrib.auth import get_user_model |
| 6 | +from django.contrib.auth.models import AnonymousUser |
| 7 | +from django.db.models import Model |
| 8 | +from django.db.models.base import ModelBase |
| 9 | + |
| 10 | +from audit_log.enums import Operation, Role, Status |
| 11 | +from audit_log.models import AuditLogEntry |
| 12 | + |
| 13 | +User = get_user_model() |
| 14 | + |
| 15 | + |
| 16 | +def _now() -> datetime: |
| 17 | + """Returns the current time in UTC timezone.""" |
| 18 | + return datetime.now(tz=timezone.utc) |
| 19 | + |
| 20 | + |
| 21 | +def _iso8601_date(time: datetime) -> str: |
| 22 | + """Formats the timestamp in ISO-8601 format, e.g. '2020-06-01T00:00:00.000Z'.""" |
| 23 | + return f"{time.replace(tzinfo=None).isoformat(timespec='milliseconds')}Z" |
| 24 | + |
| 25 | + |
| 26 | +def log( |
| 27 | + actor: Optional[Union[User, AnonymousUser]], |
| 28 | + actor_backend: str, |
| 29 | + operation: Operation, |
| 30 | + target: Union[Model, ModelBase], |
| 31 | + status: Status = Status.SUCCESS, |
| 32 | + get_time: Callable[[], datetime] = _now, |
| 33 | + ip_address: str = "", |
| 34 | + additional_information: str = "", |
| 35 | +): |
| 36 | + """ |
| 37 | + Write an event to the audit log. |
| 38 | +
|
| 39 | + Each audit log event has an actor (or None for system events), |
| 40 | + an operation(e.g. READ or UPDATE), the target of the operation |
| 41 | + (a Django model instance), status (e.g. SUCCESS), and a timestamp. |
| 42 | + """ |
| 43 | + current_time = get_time() |
| 44 | + user_id_field_name = getattr(target, "audit_log_id_field", "pk") |
| 45 | + user_id = str(getattr(actor, user_id_field_name, "")) |
| 46 | + |
| 47 | + if actor is None: |
| 48 | + role = Role.SYSTEM |
| 49 | + elif isinstance(actor, AnonymousUser): |
| 50 | + role = Role.ANONYMOUS |
| 51 | + elif actor.id == target.pk: |
| 52 | + role = Role.OWNER |
| 53 | + else: |
| 54 | + role = Role.USER |
| 55 | + |
| 56 | + message = { |
| 57 | + "audit_event": { |
| 58 | + "origin": settings.AUDIT_LOG_ORIGIN, |
| 59 | + "status": status.value, |
| 60 | + "date_time_epoch": int(current_time.timestamp() * 1000), |
| 61 | + "date_time": _iso8601_date(current_time), |
| 62 | + "actor": { |
| 63 | + "role": role.value, |
| 64 | + "user_id": user_id, |
| 65 | + "provider": actor_backend if actor_backend else "", |
| 66 | + "ip_address": ip_address, |
| 67 | + }, |
| 68 | + "operation": operation.value, |
| 69 | + "additional_information": additional_information, |
| 70 | + "target": { |
| 71 | + "id": _get_target_id(target), |
| 72 | + "type": _get_target_type(target), |
| 73 | + }, |
| 74 | + }, |
| 75 | + } |
| 76 | + AuditLogEntry.objects.create(message=message) |
| 77 | + |
| 78 | + |
| 79 | +def _get_target_id(target: Union[Model, ModelBase]) -> str: |
| 80 | + if isinstance(target, ModelBase): |
| 81 | + return "" |
| 82 | + field_name = getattr(target, "audit_log_id_field", "pk") |
| 83 | + audit_log_id = getattr(target, field_name, "") |
| 84 | + return str(audit_log_id) |
| 85 | + |
| 86 | + |
| 87 | +def _get_target_type(target: Union[Model, ModelBase]) -> str: |
| 88 | + return ( |
| 89 | + str(target.__class__.__name__) |
| 90 | + if isinstance(target, Model) |
| 91 | + else str(target.__name__) |
| 92 | + ) |
0 commit comments