forked from readthedocs/readthedocs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
220 lines (190 loc) · 6.11 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""Audit models."""
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_extensions.db.models import TimeStampedModel
from readthedocs.acl.utils import get_auth_backend
from readthedocs.analytics.utils import get_client_ip
from readthedocs.projects.models import Project
class AuditLogManager(models.Manager):
"""AuditLog manager."""
def new(self, action, user=None, request=None, **kwargs):
"""
Create an audit log for `action`.
If user or request are given,
other fields will be auto-populated from that information.
"""
actions_requiring_user = (
AuditLog.PAGEVIEW,
AuditLog.DOWNLOAD,
AuditLog.AUTHN,
AuditLog.LOGOUT,
)
if action in actions_requiring_user and (not user or not request):
raise TypeError(f'A user and a request is required for the {action} action.')
if action in (AuditLog.PAGEVIEW, AuditLog.DOWNLOAD) and 'project' not in kwargs:
raise TypeError(f'A project is required for the {action} action.')
# Don't save anonymous users.
if user and user.is_anonymous:
user = None
if request:
kwargs['ip'] = get_client_ip(request)
kwargs['browser'] = request.headers.get('User-Agent')
kwargs.setdefault('resource', request.path_info)
kwargs.setdefault('auth_backend', get_auth_backend(request))
# Fill the project from the request if available.
# This is frequently on actions generated from a subdomain.
project_slug = getattr(request, 'host_project_slug', None)
if 'project' not in kwargs and project_slug:
kwargs['project'] = Project.objects.filter(slug=project_slug).first()
return self.create(
user=user,
action=action,
**kwargs,
)
class AuditLog(TimeStampedModel):
"""
Track user actions for audit purposes.
A log can be attached to a user and/or project and organization.
If the user, project or organization are deleted the log will be preserved,
and the deleted user/project/organization can be accessed via the ``log_*`` attributes.
"""
PAGEVIEW = 'pageview'
DOWNLOAD = 'download'
AUTHN = 'authentication'
AUTHN_FAILURE = 'authentication-failure'
LOGOUT = 'log-out'
CHOICES = (
(PAGEVIEW, 'Page view'),
(DOWNLOAD, 'Download'),
(AUTHN, 'Authentication'),
(AUTHN_FAILURE, 'Authentication failure'),
(LOGOUT, 'Log out'),
)
user = models.ForeignKey(
User,
verbose_name=_('User'),
null=True,
on_delete=models.SET_NULL,
db_index=True,
)
# Extra information in case the user is deleted.
log_user_id = models.IntegerField(
_('User ID'),
blank=True,
null=True,
db_index=True,
)
log_user_username = models.CharField(
_('Username'),
max_length=150,
blank=True,
null=True,
db_index=True,
)
project = models.ForeignKey(
'projects.Project',
verbose_name=_('Project'),
null=True,
db_index=True,
on_delete=models.SET_NULL,
)
# Extra information in case the project is deleted.
log_project_id = models.IntegerField(
_('Project ID'),
blank=True,
null=True,
db_index=True,
)
log_project_slug = models.CharField(
_('Project slug'),
max_length=63,
blank=True,
null=True,
db_index=True,
)
organization = models.ForeignKey(
'organizations.Organization',
verbose_name=_('Organization'),
null=True,
db_index=True,
on_delete=models.SET_NULL,
)
log_organization_id = models.IntegerField(
_('Organization ID'),
blank=True,
null=True,
db_index=True,
)
log_organization_slug = models.CharField(
_('Organization slug'),
max_length=255,
blank=True,
null=True,
db_index=True,
)
action = models.CharField(
_('Action'),
max_length=150,
choices=CHOICES,
)
auth_backend = models.CharField(
_('Auth backend'),
max_length=250,
blank=True,
null=True,
)
ip = models.CharField(
_('IP address'),
blank=True,
null=True,
max_length=250,
)
browser = models.CharField(
_('Browser user-agent'),
max_length=250,
blank=True,
null=True,
)
# Resource can be a path,
# set it slightly greater than ``HTMLFile.path``.
resource = models.CharField(
_('Resource'),
max_length=5500,
blank=True,
null=True,
)
objects = AuditLogManager()
class Meta:
ordering = ['-created']
def save(self, **kwargs):
if self.user:
self.log_user_id = self.user.id
self.log_user_username = self.user.username
if self.project:
self.log_project_id = self.project.id
self.log_project_slug = self.project.slug
organization = self.project.organizations.first()
if organization:
self.organization = organization
if self.organization:
self.log_organization_id = self.organization.id
self.log_organization_slug = self.organization.slug
super().save(**kwargs)
def auth_backend_display(self):
"""
Get a string representation for backends that aren't part of the normal login.
.. note::
The backends listed here are implemented on .com only.
"""
backend = self.auth_backend or ''
backend_displays = {
'TemporaryAccessTokenBackend': _('shared link'),
'TemporaryAccessPasswordBackend': _('shared password'),
}
for name, display in backend_displays.items():
if name in backend:
return display
return ''
def __str__(self):
return self.action