django-auditlog/src/auditlog/middleware.py

49 lines
1.9 KiB
Python
Raw Normal View History

from django.conf import settings
2013-10-20 13:25:48 +00:00
from django.db.models.signals import pre_save
from django.utils.functional import curry
from django.db.models.loading import get_model
2013-10-20 13:25:48 +00:00
from auditlog.models import LogEntry
class AuditlogMiddleware(object):
2013-10-20 13:25:48 +00:00
"""
Middleware to couple the request's user to log items. This is accomplished by currying the signal receiver with the
user from the request (or None if the user is not authenticated).
"""
def process_request(self, request):
2013-11-06 19:48:16 +00:00
"""
Gets the current user from the request and prepares and connects a signal receiver with the user already
attached to it.
"""
2013-10-20 13:25:48 +00:00
if hasattr(request, 'user') and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated():
user = request.user
else:
user = None
set_actor = curry(self.set_actor, user)
pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=(self.__class__, request), weak=False)
2013-10-20 13:25:48 +00:00
def process_response(self, request, response):
2013-11-06 19:48:16 +00:00
"""
Disconnects the signal receiver to prevent it from staying active.
"""
# Disconnecting the signal receiver is required because it will not be garbage collected (non-weak reference)
2013-10-20 13:25:48 +00:00
pre_save.disconnect(dispatch_uid=(self.__class__, request))
2013-11-06 19:48:16 +00:00
2013-10-20 13:25:48 +00:00
return response
@staticmethod
def set_actor(user, sender, instance, **kwargs):
2013-11-06 19:48:16 +00:00
"""
Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when
it is curried with the actor.
"""
try:
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
auth_user_model = get_model(app_label, model_name)
except ValueError:
auth_user_model = get_model('auth', 'user')
if sender == LogEntry and isinstance(user, auth_user_model) and instance.actor is None:
2013-10-20 13:25:48 +00:00
instance.actor = user