Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from django.conf import settings
4from django.db import models
5from django.utils.translation import ugettext_lazy as _
6from superdjango.db.timed.models import TimedModel
8# Exports
10__all__ = (
11 "ImpersonationHistoryModel",
12)
14# Constants
16AUTH_USER_MODEL = settings.AUTH_USER_MODEL
18# Models
21class ImpersonationHistoryModel(TimedModel):
22 """Base class for creating an impersonation log."""
24 impersonation_by = models.ForeignKey(
25 AUTH_USER_MODEL,
26 on_delete=models.CASCADE,
27 help_text=_("The user that impersonated another user."),
28 related_name="user_impersonations",
29 verbose_name=_("impersonator")
30 )
32 impersonation_for = models.ForeignKey(
33 AUTH_USER_MODEL,
34 on_delete=models.CASCADE,
35 help_text=_("The user being impersonated."),
36 related_name="impersonations_by",
37 verbose_name=_("impersonating")
38 )
40 session_key = models.CharField(
41 max_length=40,
42 help_text=_("The session key of the impersonation.")
43 )
45 ACTIVE_STATUS = "active"
46 CLOSED_STATUS = "closed"
47 STATUS_CHOICES = (
48 (ACTIVE_STATUS, _("Active")),
49 (CLOSED_STATUS, _("Closed"))
50 )
51 status = models.CharField(
52 _("status"),
53 choices=STATUS_CHOICES,
54 default=ACTIVE_STATUS,
55 help_text=_("The current status of the impersonation."),
56 max_length=128
57 )
59 class Meta:
60 abstract = True
62 def __str__(self):
63 return self.session_key
65 @classmethod
66 def start(cls, impersonation_by, impersonation_for, session_key):
67 """Create a log entry for impersonation.
69 :param impersonation_by: The user doing the impersonation.
70 :type impersonation_by: AUTH_USER_MODEL
72 :param impersonation_for: The user being impersonated.
73 :type impersonation_for: AUTH_USER_MODEL
75 :param session_key: The Django session key.
76 :type session_key: str
78 :rtype: ImpersonationHistoryModel
80 """
81 record = cls.objects.create(
82 impersonation_by=impersonation_by,
83 impersonation_for=impersonation_for,
84 session_key=session_key
85 )
86 record.start_timer(impersonation_by)
87 return record
89 def stop(self):
90 """Close the log entry."""
91 self.status = self.CLOSED_STATUS
92 self.stop_timer(self.impersonation_by, commit=False)
93 self.save(update_fields=["elapsed_seconds", "is_running", "stop_dt", "status"])