Source code for superdjango.contrib.accounts.impersonation.models

# Imports

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from superdjango.db.timed.models import TimedModel

# Exports

__all__ = (
    "ImpersonationHistoryModel",
)

# Constants

AUTH_USER_MODEL = settings.AUTH_USER_MODEL

# Models


[docs]class ImpersonationHistoryModel(TimedModel): """Base class for creating an impersonation log.""" impersonation_by = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, help_text=_("The user that impersonated another user."), related_name="user_impersonations", verbose_name=_("impersonator") ) impersonation_for = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, help_text=_("The user being impersonated."), related_name="impersonations_by", verbose_name=_("impersonating") ) session_key = models.CharField( max_length=40, help_text=_("The session key of the impersonation.") ) ACTIVE_STATUS = "active" CLOSED_STATUS = "closed" STATUS_CHOICES = ( (ACTIVE_STATUS, _("Active")), (CLOSED_STATUS, _("Closed")) ) status = models.CharField( _("status"), choices=STATUS_CHOICES, default=ACTIVE_STATUS, help_text=_("The current status of the impersonation."), max_length=128 ) class Meta: abstract = True def __str__(self): return self.session_key
[docs] @classmethod def start(cls, impersonation_by, impersonation_for, session_key): """Create a log entry for impersonation. :param impersonation_by: The user doing the impersonation. :type impersonation_by: AUTH_USER_MODEL :param impersonation_for: The user being impersonated. :type impersonation_for: AUTH_USER_MODEL :param session_key: The Django session key. :type session_key: str :rtype: ImpersonationHistoryModel """ record = cls.objects.create( impersonation_by=impersonation_by, impersonation_for=impersonation_for, session_key=session_key ) record.start_timer(impersonation_by) return record
[docs] def stop(self): """Close the log entry.""" self.status = self.CLOSED_STATUS self.stop_timer(self.impersonation_by, commit=False) self.save(update_fields=["elapsed_seconds", "is_running", "stop_dt", "status"])