-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathvalidators.py
421 lines (334 loc) · 16 KB
/
validators.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# This file is part of Indico.
# Copyright (C) 2002 - 2024 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import re
from datetime import date, timedelta
from wtforms.validators import EqualTo, Length, Regexp, StopValidation, ValidationError
from indico.util.date_time import as_utc, format_date, format_datetime, format_human_timedelta, format_time, now_utc
from indico.util.i18n import _, ngettext
from indico.util.passwords import validate_secure_password
from indico.util.string import has_relative_links, is_valid_mail
class UsedIf:
"""Make a WTF field "used" if a given condition evaluates to True.
If the field is not used, validation stops.
"""
field_flags = {'conditional': True}
def __init__(self, condition):
self.condition = condition
def __call__(self, form, field):
if self.condition in (True, False):
if not self.condition:
field.errors[:] = []
raise StopValidation
elif not self.condition(form, field):
field.errors[:] = []
raise StopValidation
class HiddenUnless:
"""Hide and disable a field unless another field has a certain value.
:param field: The name of the other field to check
:param value: The value to check for. If unspecified, any truthy
value is accepted.
:param preserve_data: If True, a disabled field will keep whatever
``object_data`` it had before (i.e. data set
via `FormDefaults`).
"""
field_flags = {'initially_hidden': True}
def __init__(self, field, value=None, preserve_data=False):
self.field = field
self.value = value if value is None or isinstance(value, (set, list, tuple)) else {value}
self.preserve_data = preserve_data
def __call__(self, form, field):
value = form[self.field].data
active = (value and self.value is None) or (self.value is not None and value in self.value)
if not active:
field.errors[:] = []
if field.raw_data:
raise ValidationError('Received data for disabled field')
if not self.preserve_data:
# Clear existing data and use field default empty value
field.data = None
field.process_formdata([])
else:
# Clear existing data (just in case) and use the existing data for the field
field.data = None
field.process_data(field.object_data)
raise StopValidation
class Exclusive:
"""Make a WTF field mutually exclusive with other fields.
If any of the given fields have a value, the validated field may not have one.
:param fields: names of exclusive fields
:param strict: whether to check for none instead of falsiness
:param message: a custom message for the validation error
"""
def __init__(self, *fields, strict=True, message=None):
self.fields = fields
self.strict = strict
self.message = message
def _is_value(self, value):
return (value is not None) if self.strict else bool(value)
def __call__(self, form, field):
if not self._is_value(field.data):
return
if any(self._is_value(form[f].data) for f in self.fields):
if self.message:
raise ValidationError(self.message)
field_names = sorted(str(form[f].label.text) for f in self.fields)
msg = ngettext('This field is mutually exclusive with another field: {}',
'This field is mutually exclusive with other fields: {}',
len(field_names))
raise ValidationError(msg.format(', '.join(field_names)))
class ConfirmPassword(EqualTo):
def __init__(self, fieldname):
super().__init__(fieldname, message=_('The passwords do not match.'))
class IndicoEmail:
"""Validate one or more email addresses."""
def __init__(self, multi=False):
self.multi = multi
def __call__(self, form, field):
if field.data and not is_valid_mail(field.data, self.multi):
msg = _('Invalid email address list') if self.multi else _('Invalid email address')
raise ValidationError(msg)
class DateRange:
"""Validate that a date is within the specified boundaries."""
field_flags = {'date_range': True}
def __init__(self, earliest='today', latest=None):
self.earliest = earliest
self.latest = latest
# set to true in get_earliest/get_latest if applicable
self.earliest_today = False
self.latest_today = False
def __call__(self, form, field):
if field.data is None:
return
field_date = field.data
earliest_date = self.get_earliest(form, field)
latest_date = self.get_latest(form, field)
if field_date != field.object_data:
if earliest_date and field_date < earliest_date:
if self.earliest_today:
msg = _("'{}' can't be in the past").format(field.label)
else:
msg = _("'{}' can't be before {}").format(field.label, format_date(earliest_date))
raise ValidationError(msg)
if latest_date and field_date > latest_date:
if self.latest_today:
msg = _("'{}' can't be in the future").format(field.label)
else:
msg = _("'{}' can't be after {}").format(field.label, format_date(latest_date))
raise ValidationError(msg)
def get_earliest(self, form, field):
earliest = self.earliest(form, field) if callable(self.earliest) else self.earliest
if earliest == 'today':
self.earliest_today = True
return date.today()
return earliest
def get_latest(self, form, field):
latest = self.latest(form, field) if callable(self.latest) else self.latest
if latest == 'today':
self.latest_today = True
return date.today()
return latest
class DateTimeRange:
"""Validate that a datetime is within the specified boundaries."""
field_flags = {'datetime_range': True}
def __init__(self, earliest='now', latest=None):
self.earliest = earliest
self.latest = latest
# set to true in get_earliest/get_latest if applicable
self.earliest_now = False
self.latest_now = False
def __call__(self, form, field):
if field.data is None:
return
field_dt = as_utc(field.data)
earliest_dt = self.get_earliest(form, field)
latest_dt = self.get_latest(form, field)
if field_dt != field.object_data:
if earliest_dt and field_dt < earliest_dt:
if self.earliest_now:
msg = _("'{}' can't be in the past ({})").format(field.label, field.timezone)
else:
dt = format_datetime(earliest_dt, timezone=field.timezone)
msg = _("'{}' can't be before {} ({})").format(field.label, dt, field.timezone)
raise ValidationError(msg)
if latest_dt and field_dt > latest_dt:
if self.latest_now:
msg = _("'{}' can't be in the future ({})").format(field.label, field.timezone)
else:
dt = format_datetime(latest_dt, timezone=field.timezone)
msg = _("'{}' can't be after {} ({})").format(field.label, dt, field.timezone)
raise ValidationError(msg)
def get_earliest(self, form, field):
earliest = self.earliest(form, field) if callable(self.earliest) else self.earliest
if earliest == 'now':
self.earliest_now = True
return now_utc().replace(second=0, microsecond=0)
return as_utc(earliest) if earliest else earliest
def get_latest(self, form, field):
latest = self.latest(form, field) if callable(self.latest) else self.latest
if latest == 'now':
self.latest_now = True
return now_utc().replace(second=59, microsecond=999)
return as_utc(latest) if latest else latest
class LinkedDate:
"""Validate that a date field happens before or/and after another.
If both ``not_before`` and ``not_after`` are set to ``True``, both fields have to
be equal.
"""
field_flags = {'linked_date': True}
def __init__(self, field, not_before=True, not_after=False, not_equal=False):
if not not_before and not not_after:
raise ValueError('Invalid validation')
self.not_before = not_before
self.not_after = not_after
self.not_equal = not_equal
self.linked_field = field
def __call__(self, form, field):
if field.data is None:
return
linked_field = form[self.linked_field]
if linked_field.data is None:
return
linked_field_date = linked_field.data
field_date = field.data
if self.not_before and field_date < linked_field_date:
raise ValidationError(_("{} can't be before {}").format(field.label, linked_field.label))
if self.not_after and field_date > linked_field_date:
raise ValidationError(_("{} can't be after {}").format(field.label, linked_field.label))
if self.not_equal and field_date == linked_field_date:
raise ValidationError(_("{} can't be equal to {}").format(field.label, linked_field.label))
class LinkedDateTime:
"""Validate that a datetime field happens before or/and after another.
If both ``not_before`` and ``not_after`` are set to ``True``, both fields have to
be equal.
"""
field_flags = {'linked_datetime': True}
def __init__(self, field, not_before=True, not_after=False, not_equal=False):
if not not_before and not not_after:
raise ValueError('Invalid validation')
self.not_before = not_before
self.not_after = not_after
self.not_equal = not_equal
self.linked_field = field
def __call__(self, form, field):
if field.data is None:
return
linked_field = form[self.linked_field]
if linked_field.data is None:
return
linked_field_dt = as_utc(linked_field.data)
field_dt = as_utc(field.data)
if self.not_before and field_dt < linked_field_dt:
raise ValidationError(_("{} can't be before {}").format(field.label, linked_field.label))
if self.not_after and field_dt > linked_field_dt:
raise ValidationError(_("{} can't be after {}").format(field.label, linked_field.label))
if self.not_equal and field_dt == linked_field_dt:
raise ValidationError(_("{} can't be equal to {}").format(field.label, linked_field.label))
class UsedIfChecked(UsedIf):
def __init__(self, field_name):
def _condition(form, field):
return form._fields.get(field_name).data
super().__init__(_condition)
class MaxDuration:
"""Validate the duration doesn't exceed `max_duration`."""
def __init__(self, max_duration=None, **kwargs):
assert max_duration or kwargs
assert max_duration is None or not kwargs
self.max_duration = max_duration if max_duration is not None else timedelta(**kwargs)
def __call__(self, form, field):
if field.data is not None and field.data > self.max_duration:
raise ValidationError(_('Duration cannot exceed {}').format(format_human_timedelta(self.max_duration)))
class TimeRange:
"""Validate the time lies within boundaries."""
def __init__(self, earliest=None, latest=None):
assert earliest is not None or latest is not None, 'At least one of `earliest` or `latest` must be specified.'
if earliest is not None and latest is not None:
assert earliest <= latest, '`earliest` cannot be later than `latest`.'
self.earliest = earliest
self.latest = latest
def __call__(self, form, field):
def _format_time(value):
return format_time(value) if value else None
if (self.earliest and field.data < self.earliest) or (self.latest and field.data > self.latest):
if self.earliest is not None and self.latest is not None:
message = _('Must be between {earliest} and {latest}.')
elif self.latest is None:
message = _('Must be later than {earliest}.')
else:
message = _('Must be earlier than {latest}.')
raise ValidationError(message.format(earliest=_format_time(self.earliest), latest=_format_time(self.latest)))
class WordCount:
"""Validate the word count of a string.
:param min: The minimum number of words in the string. If not
provided, the minimum word count will not be checked.
:param min: The maximum number of words in the string. If not
provided, the maximum word count will not be checked.
"""
def __init__(self, min=-1, max=-1):
assert min != -1 or max != -1, 'At least one of `min` or `max` must be specified.'
assert max == -1 or min <= max, '`min` cannot be more than `max`.'
self.min = min
self.max = max
def __call__(self, form, field):
count = len(re.split(r'\s+', field.data, flags=re.UNICODE)) if field.data else 0
if count < self.min or (self.max != -1 and count > self.max):
if self.max == -1:
message = ngettext('Field must contain at least {min} word.',
'Field must contain at least {min} words.', self.min)
elif self.min == -1:
message = ngettext('Field cannot contain more than {max} word.',
'Field cannot contain more than {max} words.', self.max)
else:
message = _('Field must contain between {min} and {max} words.')
raise ValidationError(message.format(min=self.min, max=self.max, length=count))
class IndicoRegexp(Regexp):
"""
Like the WTForms `Regexp` validator, but supports populating the
HTML5 `patttern` attribute (the regex may not use any non-standard
Python extensions such as named groups in this case).
"""
def __init__(self, *args, **kwargs):
self.client_side = kwargs.pop('client_side', True)
super().__init__(*args, **kwargs)
class SoftLength(Length):
"""
Like the WTForms `Length` validator, but allows typing beyond the
limit and just fails validation once the limit has been exceeded.
The client-side implementation also skips leading/trailing
whitespace which is in line with the behavior in all our forms
where surrounding whitespace is stripped before validation.
"""
def __call__(self, form, field):
orig_data = field.data
if field.data is not None:
field.data = re.sub(r'(\r\n|\r)', '\n', field.data)
try:
super().__call__(form, field)
finally:
field.data = orig_data
class SecurePassword:
"""Validate that a string is a secure password."""
# This is only defined here so the `_attrs_for_validators` util does
# not need to hard-code it.
MIN_LENGTH = 8
def __init__(self, context='wtforms-field', username_field=None):
self.context = context
self.username_field = username_field
def __call__(self, form, field):
username = ''
if self.username_field:
username = form[self.username_field].data or ''
password = field.data or ''
if error := validate_secure_password(self.context, password, username=username):
raise ValidationError(error)
class NoRelativeURLs:
"""Validate that an HTML strings contains no relative URLs.
This checks only ``img[src]`` and ``a[href]``, but not URLs present as plain
text or in any other (unexpected) places.
"""
def __call__(self, form, field):
if field.data and has_relative_links(field.data):
raise ValidationError(_('Links and images may not use relative URLs.'))