2013-10-20 17:24:33 +00:00
|
|
|
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
|
2013-11-27 22:35:34 +00:00
|
|
|
from django.db.models.loading import get_model
|
2013-10-20 13:25:48 +00:00
|
|
|
from auditlog.models import LogEntry
|
|
|
|
|
|
|
|
|
|
|
2013-11-07 16:02:31 +00:00
|
|
|
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
|
|
|
|
|
|
2013-10-20 17:24:33 +00:00
|
|
|
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
|
|
|
|
|
|
2013-12-18 16:16:39 +00:00
|
|
|
@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.
|
|
|
|
|
"""
|
2013-11-27 22:35:34 +00:00
|
|
|
try:
|
|
|
|
|
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
|
|
|
|
|
auth_user_model = get_model(app_label, model_name)
|
2013-12-18 16:16:39 +00:00
|
|
|
except ValueError:
|
2013-11-27 22:35:34 +00:00
|
|
|
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
|