/
models.py
254 lines (198 loc) · 8.56 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from djblets.db.fields import JSONField, ModificationTimestampField
from djblets.secrets.token_generators import token_generator_registry
from djblets.webapi.managers import WebAPITokenManager
from djblets.webapi.signals import webapi_token_updated
class BaseWebAPIToken(models.Model):
"""Base class for an access token used for authenticating with the API.
Each token can be used to authenticate the token's owner with the API,
without requiring a username or password to be provided. Tokens can
be revoked, and new tokens added.
Tokens can store policy information, which will later be used for
restricting access to the API.
"""
user = models.ForeignKey(
User,
related_name='webapi_tokens',
on_delete=models.CASCADE,
help_text=_('The user that owns the token.'))
token = models.CharField(
max_length=255,
unique=True,
help_text=_('The access token.'))
token_generator_id = models.CharField(
max_length=255,
help_text=_('The token generator that generated the token.'))
time_added = models.DateTimeField(
default=timezone.now,
help_text=_('The date and time when the token was first added '
'to the database.'))
last_updated = ModificationTimestampField(
default=timezone.now,
help_text=_('The date and time when the token was last updated.'))
last_used = models.DateTimeField(
null=True,
blank=True,
help_text=_('The date and time when the token was last used '
'for authentication.'))
expires = models.DateTimeField(
null=True,
blank=True,
help_text=_('An optional field for the date and time that the token '
'will expire. The token will be invalid and unusable '
'for authentication after this point.'))
valid = models.BooleanField(
default=True,
help_text=_('Whether the token is currently valid.'))
invalid_date = models.DateTimeField(
null=True,
blank=True,
help_text=_('The date and time at which the token became invalid.'))
invalid_reason = models.TextField(
blank=True,
help_text=_('A message indicating why the token is no longer valid.'))
note = models.TextField(
blank=True,
help_text=_('A message describing the token.'))
policy = JSONField(
null=True,
help_text=_('The policy document describing what this token can '
'access in the API. If empty, this provides full access.'))
extra_data = JSONField(null=True)
objects = WebAPITokenManager()
def is_accessible_by(self, user):
return user.is_superuser or self.user == user
def is_mutable_by(self, user):
return user.is_superuser or self.user == user
def is_deletable_by(self, user):
return user.is_superuser or self.user == user
def is_deprecated(self) -> bool:
"""Return whether the token is deprecated or not.
This will be ``True`` if the token was generated by a deprecated
token generator.
Version Added:
3.1
Returns:
bool:
Whether the token is deprecated.
"""
generators = token_generator_registry.get_deprecated_token_generators()
return self.token_generator_id in generators
def is_expired(self) -> bool:
"""Return whether the token is expired or not.
This will be ``False`` if there is no expiration date set.
Version Added:
3.0
Returns:
bool:
Whether the token is expired.
"""
return self.expires is not None and timezone.now() >= self.expires
def __str__(self):
return 'Web API token for %s' % self.user
def save(self, *args, **kwargs):
"""Save the token.
If the token is being updated, the
:py:data:`~djblets.webapi.signals.webapi_token_updated` signal will be
emitted.
Args:
*args (tuple):
Positional arguments to pass to the superclass.
**kwargs (dict):
Keyword arguments to pass to the superclass.
"""
is_new = self.pk is None
super().save(*args, **kwargs)
if not is_new:
webapi_token_updated.send(instance=self, sender=type(self))
@classmethod
def get_root_resource(cls):
raise NotImplementedError
@classmethod
def validate_policy(cls, policy):
"""Validate an API policy.
This will check to ensure that the policy is in a suitable format
and contains the information required in a format that can be parsed.
If a failure is found, a ValidationError will be raised describing
the error and where it was found.
"""
if not isinstance(policy, dict):
raise ValidationError(_('The policy must be a JSON object.'))
if not policy:
# Empty policies are equivalent to allowing full access. If this
# is empty, we can stop here.
return
if 'resources' not in policy:
raise ValidationError(
_('The policy is missing a "resources" section.'))
resources_section = policy['resources']
if not isinstance(resources_section, dict):
raise ValidationError(
_('The policy\'s "resources" section must be a JSON object.'))
if not resources_section:
raise ValidationError(
_('The policy\'s "resources" section must not be empty.'))
if '*' in resources_section:
cls._validate_policy_section(resources_section, '*',
'resources.*')
resource_policies = [
(section_name, section)
for section_name, section in resources_section.items()
if section_name != '*'
]
if resource_policies:
valid_policy_ids = \
cls._get_valid_policy_ids(cls.get_root_resource())
for policy_id, section in resource_policies:
if policy_id not in valid_policy_ids:
raise ValidationError(
_('"%s" is not a valid resource policy ID.')
% policy_id)
for subsection_name, subsection in section.items():
if not isinstance(subsection_name, str):
raise ValidationError(
_('%s must be a string in "resources.%s"')
% (subsection_name, policy_id))
cls._validate_policy_section(
section, subsection_name,
'resources.%s.%s' % (policy_id, subsection_name))
@classmethod
def _validate_policy_section(cls, parent_section, section_name,
full_section_name):
section = parent_section[section_name]
if not isinstance(section, dict):
raise ValidationError(
_('The "%s" section must be a JSON object.')
% full_section_name)
if 'allow' not in section and 'block' not in section:
raise ValidationError(
_('The "%s" section must have "allow" and/or "block" '
'rules.')
% full_section_name)
if 'allow' in section and not isinstance(section['allow'], list):
raise ValidationError(
_('The "%s" section\'s "allow" rule must be a list.')
% full_section_name)
if 'block' in section and not isinstance(section['block'], list):
raise ValidationError(
_('The "%s" section\'s "block" rule must be a list.')
% full_section_name)
@classmethod
def _get_valid_policy_ids(cls, resource, result=None):
if result is None:
result = set()
if hasattr(resource, 'policy_id'):
result.add(resource.policy_id)
for child_resource in resource.list_child_resources:
cls._get_valid_policy_ids(child_resource, result)
for child_resource in resource.item_child_resources:
cls._get_valid_policy_ids(child_resource, result)
return result
class Meta:
abstract = True
verbose_name = _('Web API token')
verbose_name_plural = _('Web API tokens')