add comment to middleware

This commit is contained in:
2025-03-27 21:49:09 -03:00
parent f757334899
commit 88c2585d2a
2 changed files with 22 additions and 3 deletions

View File

@@ -11,6 +11,7 @@ from aws_lambda_powertools.shared.functions import (
) )
from layercake.dateutils import now, ttl from layercake.dateutils import now, ttl
from layercake.dynamodb import ComposeKey, DynamoDBCollection, KeyPair from layercake.dynamodb import ComposeKey, DynamoDBCollection, KeyPair
from layercake.funcs import pick
from pydantic import UUID4, BaseModel, Field from pydantic import UUID4, BaseModel, Field
LOG_RETENTION_DAYS = 365 * 2 # 2 years LOG_RETENTION_DAYS = 365 * 2 # 2 years
@@ -43,17 +44,33 @@ class AuthorizerMiddleware(BaseMiddlewareHandler):
class AuditLogMiddleware(BaseMiddlewareHandler): class AuditLogMiddleware(BaseMiddlewareHandler):
"""This middleware logs audit details for successful requests, storing user, """This middleware logs audit details for successful requests, storing user,
action, and IP info with a specified retention period..""" action, and IP info with a specified retention period.
Parameters
----------
action : str
The identifier for the audit log action.
collect : DynamoDBCollection
The collection instance used to persist the audit log data.
audit_attrs : tuple of str, optional
A tuple of attribute names to extract from the response body for logging.
These represent the specific fields to include in the audit log.
retention_days : int or None, optional
The number of days the log is retained on the server.
If None, no time-to-live (TTL) will be applied.
"""
def __init__( def __init__(
self, self,
action: str, action: str,
/, /,
collect: DynamoDBCollection, collect: DynamoDBCollection,
audit_attrs: tuple[str, ...] = (),
retention_days: int | None = LOG_RETENTION_DAYS, retention_days: int | None = LOG_RETENTION_DAYS,
) -> None: ) -> None:
self.action = action self.action = action
self.collect = collect self.collect = collect
self.audit_attrs = audit_attrs
self.retention_days = retention_days self.retention_days = retention_days
def handler( def handler(
@@ -71,7 +88,7 @@ class AuditLogMiddleware(BaseMiddlewareHandler):
if 200 <= response.status_code < 300 and user: if 200 <= response.status_code < 300 and user:
now_ = now() now_ = now()
data = ( data = (
extract_event_from_common_models(response.body) pick(self.audit_attrs, extract_event_from_common_models(response.body))
if response.is_json() if response.is_json()
else None else None
) )

View File

@@ -43,7 +43,9 @@ def get_courses():
'/', '/',
compress=True, compress=True,
tags=['Course'], tags=['Course'],
middlewares=[AuditLogMiddleware('COURSE_ADD', collect)], middlewares=[
AuditLogMiddleware('COURSE_ADD', collect, ('id', 'name')),
],
) )
def post_course(payload: Course): def post_course(payload: Course):
create_course( create_course(