Skip to content

Commit

Permalink
lint care/audit_logs
Browse files Browse the repository at this point in the history
  • Loading branch information
sainak committed Sep 23, 2024
1 parent ea1fa04 commit 15a2705
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 28 deletions.
21 changes: 10 additions & 11 deletions care/audit_log/helpers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# ruff: noqa: SLF001
import re
from fnmatch import fnmatch
from functools import lru_cache
Expand All @@ -14,7 +15,7 @@ def remove_non_member_fields(d: dict):
def instance_finder(v):
return isinstance(
v,
(list, dict, set),
list | dict | set,
)


Expand All @@ -41,10 +42,9 @@ class Search(NamedTuple):

def _make_search(item):
splits = item.split(":")
if len(splits) == 2:
if len(splits) == 2: # noqa: PLR2004
return Search(type=splits[0], value=splits[1])
else:
return Search(type="plain", value=splits[0])
return Search(type="plain", value=splits[0])


def candidate_in_scope(
Expand All @@ -62,7 +62,7 @@ def candidate_in_scope(
search_candidate = candidate
if is_application:
splits = candidate.split(".")
if len(splits) == 2:
if len(splits) == 2: # noqa: PLR2004
app_label, model_name = splits
search_candidate = app_label

Expand Down Expand Up @@ -91,12 +91,11 @@ def exclude_model(model_name):
):
return True

if candidate_in_scope(
model_name, settings.AUDIT_LOG["models"]["exclude"]["models"]
):
return True

return False
return bool(
candidate_in_scope(
model_name, settings.AUDIT_LOG["models"]["exclude"]["models"]
)
)


class MetaDataContainer(dict):
Expand Down
18 changes: 9 additions & 9 deletions care/audit_log/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class RequestInformation(NamedTuple):
response: HttpResponse | None
exception: Exception | None


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -50,7 +51,7 @@ def save(request, response=None, exception=None):
if not dal_request_id:
dal_request_id = (
f"{request.method.lower()}::"
f"{md5(request.path.lower().encode('utf-8')).hexdigest()}::"
f"{md5(request.path.lower().encode('utf-8')).hexdigest()}::" # noqa: S324
f"{uuid.uuid4().hex}"
)
request.dal_request_id = dal_request_id
Expand All @@ -69,8 +70,7 @@ def get_current_user():
environ = RequestInformation(*AuditLogMiddleware.thread.__dal__)
if isinstance(environ.request.user, AnonymousUser):
return None
else:
return environ.request.user
return environ.request.user

@staticmethod
def get_current_request():
Expand All @@ -85,14 +85,14 @@ def __call__(self, request: HttpRequest):
response: HttpResponse = self.get_response(request)
self.save(request, response)

if request.user:
current_user_str = f"{request.user.id}|{request.user}"
else:
current_user_str = None
current_user_str = f"{request.user.id}|{request.user}" if request.user else None

logger.info(
f"{request.method} {request.path} {response.status_code} "
f"User:[{current_user_str}]"
"%s %s %s User:[%s]",
request.method,
request.path,
response.status_code,
current_user_str,
)
return response

Expand Down
25 changes: 17 additions & 8 deletions care/audit_log/receivers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# ruff: noqa: SLF001
import json
import logging
from typing import NamedTuple
Expand All @@ -22,6 +23,7 @@

logger = logging.getLogger(__name__)


class Event(NamedTuple):
model: str
actor: AbstractUser
Expand All @@ -42,7 +44,7 @@ def pre_save_signal(sender, instance, **kwargs) -> None:

model_name = get_model_name(instance)
if exclude_model(model_name):
logger.debug(f"{model_name} ignored as per settings")
logger.debug("%s ignored as per settings", model_name)
return

get_or_create_meta(instance)
Expand All @@ -61,8 +63,9 @@ def pre_save_signal(sender, instance, **kwargs) -> None:
changes = {}

if operation not in {Operation.INSERT, Operation.DELETE}:
old, new = remove_non_member_fields(pre.__dict__), remove_non_member_fields(
instance.__dict__
old, new = (
remove_non_member_fields(pre.__dict__),
remove_non_member_fields(instance.__dict__),
)

try:
Expand Down Expand Up @@ -107,7 +110,7 @@ def _post_processor(instance, event: Event | None, operation: Operation):
model_name = get_model_name(instance)

if not event and operation != Operation.DELETE:
logger.debug(f"Event not received for {operation}. Ignoring.")
logger.debug("Event not received for %s. Ignoring.", operation)
return

try:
Expand All @@ -118,11 +121,17 @@ def _post_processor(instance, event: Event | None, operation: Operation):
else:
changes = json.dumps(event.changes if event else {}, cls=LogJsonEncoder)
except Exception:
logger.warning(f"Failed to log {event}", exc_info=True)
logger.warning("Failed to log %s", event, exc_info=True)
return

logger.info(
f"AUDIT_LOG::{request_id}|{actor}|{operation.value}|{model_name}|ID:{instance.pk}|{changes}"
"AUDIT_LOG::%s|%s|%s|%s|ID:%s|%s",
request_id,
actor,
operation.value,
model_name,
instance.pk,
changes,
)


Expand All @@ -137,7 +146,7 @@ def post_save_signal(sender, instance, created, update_fields: frozenset, **kwar

model_name = get_model_name(instance)
if exclude_model(model_name):
logger.debug(f"Ignoring {model_name}.")
logger.debug("Ignoring %s.", model_name)
return

operation = Operation.INSERT if created else Operation.UPDATE
Expand All @@ -158,7 +167,7 @@ def post_delete_signal(sender, instance, **kwargs) -> None:

model_name = get_model_name(instance)
if exclude_model(model_name):
logger.debug(f"Ignoring {model_name}.")
logger.debug("Ignoring %s.", model_name)
return

event = instance._meta.dal.event
Expand Down

0 comments on commit 15a2705

Please sign in to comment.