models.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. from __future__ import annotations
  2. import json
  3. import logging
  4. import secrets
  5. import string
  6. import time
  7. import uuid
  8. from datetime import timedelta
  9. from hashlib import sha256
  10. import psl_dns
  11. import rest_framework.authtoken.models
  12. from django.conf import settings
  13. from django.contrib.auth.hashers import make_password
  14. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
  15. from django.core.exceptions import ValidationError
  16. from django.core.mail import EmailMessage, get_connection
  17. from django.core.validators import RegexValidator
  18. from django.db import models
  19. from django.db.models import Manager, Q
  20. from django.template.loader import get_template
  21. from django.utils import timezone
  22. from django_prometheus.models import ExportModelOperationsMixin
  23. from dns.exception import Timeout
  24. from dns.resolver import NoNameservers
  25. from rest_framework.exceptions import APIException
  26. from desecapi import metrics
  27. from desecapi import pdns
  28. logger = logging.getLogger(__name__)
  29. psl = psl_dns.PSL(resolver=settings.PSL_RESOLVER, timeout=.5)
  30. def validate_lower(value):
  31. if value != value.lower():
  32. raise ValidationError('Invalid value (not lowercase): %(value)s',
  33. code='invalid',
  34. params={'value': value})
  35. def validate_upper(value):
  36. if value != value.upper():
  37. raise ValidationError('Invalid value (not uppercase): %(value)s',
  38. code='invalid',
  39. params={'value': value})
  40. class MyUserManager(BaseUserManager):
  41. def create_user(self, email, password, **extra_fields):
  42. """
  43. Creates and saves a User with the given email, date of
  44. birth and password.
  45. """
  46. if not email:
  47. raise ValueError('Users must have an email address')
  48. email = self.normalize_email(email)
  49. user = self.model(email=email, **extra_fields)
  50. user.set_password(password)
  51. user.save(using=self._db)
  52. return user
  53. def create_superuser(self, email, password):
  54. """
  55. Creates and saves a superuser with the given email, date of
  56. birth and password.
  57. """
  58. user = self.create_user(email, password=password)
  59. user.is_admin = True
  60. user.save(using=self._db)
  61. return user
  62. class User(ExportModelOperationsMixin('User'), AbstractBaseUser):
  63. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  64. email = models.EmailField(
  65. verbose_name='email address',
  66. max_length=191,
  67. unique=True,
  68. )
  69. is_active = models.BooleanField(default=True)
  70. is_admin = models.BooleanField(default=False)
  71. created = models.DateTimeField(auto_now_add=True)
  72. limit_domains = models.IntegerField(default=settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT, null=True, blank=True)
  73. objects = MyUserManager()
  74. USERNAME_FIELD = 'email'
  75. REQUIRED_FIELDS = []
  76. def get_full_name(self):
  77. return self.email
  78. def get_short_name(self):
  79. return self.email
  80. def __str__(self):
  81. return self.email
  82. # noinspection PyMethodMayBeStatic
  83. def has_perm(self, *_):
  84. """Does the user have a specific permission?"""
  85. # Simplest possible answer: Yes, always
  86. return True
  87. # noinspection PyMethodMayBeStatic
  88. def has_module_perms(self, *_):
  89. """Does the user have permissions to view the app `app_label`?"""
  90. # Simplest possible answer: Yes, always
  91. return True
  92. @property
  93. def is_staff(self):
  94. """Is the user a member of staff?"""
  95. # Simplest possible answer: All admins are staff
  96. return self.is_admin
  97. def activate(self):
  98. self.is_active = True
  99. self.save()
  100. def change_email(self, email):
  101. old_email = self.email
  102. self.email = email
  103. self.validate_unique()
  104. self.save()
  105. self.send_email('change-email-confirmation-old-email', recipient=old_email)
  106. def change_password(self, raw_password):
  107. self.set_password(raw_password)
  108. self.save()
  109. self.send_email('password-change-confirmation')
  110. def send_email(self, reason, context=None, recipient=None):
  111. fast_lane = 'email_fast_lane'
  112. slow_lane = 'email_slow_lane'
  113. lanes = {
  114. 'activate': slow_lane,
  115. 'activate-with-domain': slow_lane,
  116. 'change-email': slow_lane,
  117. 'change-email-confirmation-old-email': fast_lane,
  118. 'password-change-confirmation': fast_lane,
  119. 'reset-password': fast_lane,
  120. 'delete-user': fast_lane,
  121. 'domain-dyndns': fast_lane,
  122. }
  123. if reason not in lanes:
  124. raise ValueError(f'Cannot send email to user {self.pk} without a good reason: {reason}')
  125. context = context or {}
  126. context.setdefault('link_expiration_hours',
  127. settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE // timedelta(hours=1))
  128. content = get_template(f'emails/{reason}/content.txt').render(context)
  129. content += f'\nSupport Reference: user_id = {self.pk}\n'
  130. footer = get_template('emails/footer.txt').render()
  131. logger.warning(f'Queuing email for user account {self.pk} (reason: {reason})')
  132. num_queued = EmailMessage(
  133. subject=get_template(f'emails/{reason}/subject.txt').render(context).strip(),
  134. body=content + footer,
  135. from_email=get_template('emails/from.txt').render(),
  136. to=[recipient or self.email],
  137. connection=get_connection(lane=lanes[reason], debug={'user': self.pk, 'reason': reason})
  138. ).send()
  139. metrics.get('desecapi_messages_queued').labels(reason, self.pk, lanes[reason]).observe(num_queued)
  140. return num_queued
  141. class Token(ExportModelOperationsMixin('Token'), rest_framework.authtoken.models.Token):
  142. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  143. key = models.CharField("Key", max_length=128, db_index=True, unique=True)
  144. user = models.ForeignKey(
  145. User, related_name='auth_tokens',
  146. on_delete=models.CASCADE, verbose_name="User"
  147. )
  148. name = models.CharField('Name', blank=True, max_length=64)
  149. last_used = models.DateTimeField(null=True, blank=True)
  150. plain = None
  151. def generate_key(self):
  152. self.plain = secrets.token_urlsafe(21)
  153. self.key = Token.make_hash(self.plain)
  154. return self.key
  155. @staticmethod
  156. def make_hash(plain):
  157. return make_password(plain, salt='static', hasher='pbkdf2_sha256_iter1')
  158. validate_domain_name = [
  159. validate_lower,
  160. RegexValidator(
  161. # TODO See how far this validation can be relaxed
  162. regex=r'^(([a-z0-9][a-z0-9-]{0,61}[a-z0-9]|[a-z0-9])\.)*[a-z]{1,63}$',
  163. message='Domain names must be labels separated dots. Labels may only use hyphens, digits, and lowercase '
  164. 'letters, must not start or end with a hyphen, and must not exceed 63 byte. The last label may only '
  165. 'have lowercase letters.',
  166. code='invalid_domain_name'
  167. )
  168. ]
  169. def get_minimum_ttl_default():
  170. return settings.MINIMUM_TTL_DEFAULT
  171. class Domain(ExportModelOperationsMixin('Domain'), models.Model):
  172. created = models.DateTimeField(auto_now_add=True)
  173. name = models.CharField(max_length=191,
  174. unique=True,
  175. validators=validate_domain_name)
  176. owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='domains')
  177. published = models.DateTimeField(null=True, blank=True)
  178. minimum_ttl = models.PositiveIntegerField(default=get_minimum_ttl_default)
  179. _keys = None
  180. def is_registrable(self):
  181. """
  182. Returns False in any of the following cases:
  183. (a) the domain name is under .internal,
  184. (b) the domain_name appears on the public suffix list,
  185. (c) the domain is descendant to a zone that belongs to any user different from the given one,
  186. unless it's parent is a public suffix, either through the Internet PSL or local settings.
  187. Otherwise, True is returned.
  188. """
  189. if self.name != self.name.lower():
  190. raise ValueError
  191. if f'.{self.name}'.endswith('.internal'):
  192. return False
  193. try:
  194. public_suffix = psl.get_public_suffix(self.name)
  195. is_public_suffix = psl.is_public_suffix(self.name)
  196. except (Timeout, NoNameservers):
  197. public_suffix = self.name.rpartition('.')[2]
  198. is_public_suffix = ('.' not in self.name) # TLDs are public suffixes
  199. except psl_dns.exceptions.UnsupportedRule as e:
  200. # It would probably be fine to treat this as a non-public suffix (with the TLD acting as the
  201. # public suffix and setting both public_suffix and is_public_suffix accordingly).
  202. # However, in order to allow to investigate the situation, it's better not catch
  203. # this exception. For web requests, our error handler turns it into a 503 error
  204. # and makes sure admins are notified.
  205. raise e
  206. if not is_public_suffix:
  207. # Take into account that any of the parent domains could be a local public suffix. To that
  208. # end, identify the longest local public suffix that is actually a suffix of domain_name.
  209. # Then, override the global PSL result.
  210. for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
  211. has_local_public_suffix_parent = ('.' + self.name).endswith('.' + local_public_suffix)
  212. if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
  213. public_suffix = local_public_suffix
  214. is_public_suffix = (public_suffix == self.name)
  215. if is_public_suffix and self.name not in settings.LOCAL_PUBLIC_SUFFIXES:
  216. return False
  217. # Generate a list of all domains connecting this one and its public suffix.
  218. # If another user owns a zone with one of these names, then the requested
  219. # domain is unavailable because it is part of the other user's zone.
  220. private_components = self.name.rsplit(public_suffix, 1)[0].rstrip('.')
  221. private_components = private_components.split('.') if private_components else []
  222. private_components += [public_suffix]
  223. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components) - 1)]
  224. assert is_public_suffix or self.name == private_domains[0]
  225. # Deny registration for non-local public suffixes and for domains covered by other users' zones
  226. try:
  227. owner = self.owner
  228. except Domain.owner.RelatedObjectDoesNotExist:
  229. owner = None
  230. return not Domain.objects.filter(Q(name__in=private_domains) & ~Q(owner=owner)).exists()
  231. @property
  232. def keys(self):
  233. if not self._keys:
  234. self._keys = pdns.get_keys(self)
  235. return self._keys
  236. @property
  237. def touched(self):
  238. try:
  239. rrset_touched = max(updated for updated in self.rrset_set.values_list('touched', flat=True))
  240. # If the domain has not been published yet, self.published is None and max() would fail
  241. return rrset_touched if not self.published else max(rrset_touched, self.published)
  242. except ValueError:
  243. # This can be none if the domain was never published and has no records (but there should be at least NS)
  244. return self.published
  245. @property
  246. def is_locally_registrable(self):
  247. return self.parent_domain_name in settings.LOCAL_PUBLIC_SUFFIXES
  248. @property
  249. def parent_domain_name(self):
  250. return self._partitioned_name[1]
  251. @property
  252. def _partitioned_name(self):
  253. subname, _, parent_name = self.name.partition('.')
  254. return subname, parent_name or None
  255. def save(self, *args, **kwargs):
  256. self.full_clean(validate_unique=False)
  257. super().save(*args, **kwargs)
  258. def update_delegation(self, child_domain: Domain):
  259. child_subname, child_domain_name = child_domain._partitioned_name
  260. if self.name != child_domain_name:
  261. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  262. (child_domain.name, self.name))
  263. if child_domain.pk:
  264. # Domain real: set delegation
  265. child_keys = child_domain.keys
  266. if not child_keys:
  267. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  268. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  269. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  270. contents=[ds for k in child_keys for ds in k['ds']])
  271. metrics.get('desecapi_autodelegation_created').inc()
  272. else:
  273. # Domain not real: remove delegation
  274. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  275. rrset.delete()
  276. metrics.get('desecapi_autodelegation_deleted').inc()
  277. def delete(self):
  278. ret = super().delete()
  279. logger.warning(f'Domain {self.name} deleted (owner: {self.owner.pk})')
  280. return ret
  281. def __str__(self):
  282. return self.name
  283. class Meta:
  284. ordering = ('created',)
  285. def get_default_value_created():
  286. return timezone.now()
  287. def get_default_value_due():
  288. return timezone.now() + timedelta(days=7)
  289. def get_default_value_mref():
  290. return "ONDON" + str(time.time())
  291. class Donation(ExportModelOperationsMixin('Donation'), models.Model):
  292. created = models.DateTimeField(default=get_default_value_created)
  293. name = models.CharField(max_length=255)
  294. iban = models.CharField(max_length=34)
  295. bic = models.CharField(max_length=11, blank=True)
  296. amount = models.DecimalField(max_digits=8, decimal_places=2)
  297. message = models.CharField(max_length=255, blank=True)
  298. due = models.DateTimeField(default=get_default_value_due)
  299. mref = models.CharField(max_length=32, default=get_default_value_mref)
  300. email = models.EmailField(max_length=255, blank=True)
  301. class Meta:
  302. managed = False
  303. class RRsetManager(Manager):
  304. def create(self, contents=None, **kwargs):
  305. rrset = super().create(**kwargs)
  306. for content in contents or []:
  307. RR.objects.create(rrset=rrset, content=content)
  308. return rrset
  309. class RRset(ExportModelOperationsMixin('RRset'), models.Model):
  310. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  311. created = models.DateTimeField(auto_now_add=True)
  312. touched = models.DateTimeField(auto_now=True)
  313. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  314. subname = models.CharField(
  315. max_length=178,
  316. blank=True,
  317. validators=[
  318. validate_lower,
  319. RegexValidator(
  320. regex=r'^([*]|(([*][.])?[a-z0-9_.-]*))$',
  321. message='Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
  322. 'may start with a \'*.\', or just be \'*\'.',
  323. code='invalid_subname'
  324. )
  325. ]
  326. )
  327. type = models.CharField(
  328. max_length=10,
  329. validators=[
  330. validate_upper,
  331. RegexValidator(
  332. regex=r'^[A-Z][A-Z0-9]*$',
  333. message='Type must be uppercase alphanumeric and start with a letter.',
  334. code='invalid_type'
  335. )
  336. ]
  337. )
  338. ttl = models.PositiveIntegerField()
  339. objects = RRsetManager()
  340. DEAD_TYPES = ('ALIAS', 'DNAME')
  341. RESTRICTED_TYPES = ('SOA', 'RRSIG', 'DNSKEY', 'NSEC3PARAM', 'OPT')
  342. class Meta:
  343. unique_together = (("domain", "subname", "type"),)
  344. @staticmethod
  345. def construct_name(subname, domain_name):
  346. return '.'.join(filter(None, [subname, domain_name])) + '.'
  347. @property
  348. def name(self):
  349. return self.construct_name(self.subname, self.domain.name)
  350. def save(self, *args, **kwargs):
  351. self.full_clean(validate_unique=False)
  352. super().save(*args, **kwargs)
  353. def __str__(self):
  354. return '<RRSet %s domain=%s type=%s subname=%s>' % (self.pk, self.domain.name, self.type, self.subname)
  355. class RRManager(Manager):
  356. def bulk_create(self, rrs, **kwargs):
  357. ret = super().bulk_create(rrs, **kwargs)
  358. # For each rrset, save once to set RRset.updated timestamp and trigger signal for post-save processing
  359. rrsets = {rr.rrset for rr in rrs}
  360. for rrset in rrsets:
  361. rrset.save()
  362. return ret
  363. class RR(ExportModelOperationsMixin('RR'), models.Model):
  364. created = models.DateTimeField(auto_now_add=True)
  365. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  366. # The pdns lmdb backend used on our slaves does not only store the record contents itself, but other metadata (such
  367. # as type etc.) Both together have to fit into the lmdb backend's current total limit of 512 bytes per RR, see
  368. # https://github.com/PowerDNS/pdns/issues/8012
  369. # I found the additional data to be 12 bytes (by trial and error). I believe these are the 12 bytes mentioned here:
  370. # https://lists.isc.org/pipermail/bind-users/2008-April/070137.html So we can use 500 bytes for the actual content.
  371. # Note: This is a conservative estimate, as record contents may be stored more efficiently depending on their type,
  372. # effectively allowing a longer length in "presentation format". For example, A record contents take up 4 bytes,
  373. # although the presentation format (usual IPv4 representation) takes up to 15 bytes. Similarly, OPENPGPKEY contents
  374. # are base64-decoded before storage in binary format, so a "presentation format" value (which is the value our API
  375. # sees) can have up to 668 bytes. Instead of introducing per-type limits, setting it to 500 should always work.
  376. content = models.CharField(max_length=500) #
  377. objects = RRManager()
  378. def __str__(self):
  379. return '<RR %s %s rr_set=%s>' % (self.pk, self.content, self.rrset.pk)
  380. class AuthenticatedAction(ExportModelOperationsMixin('AuthenticatedAction'), models.Model):
  381. """
  382. Represents a procedure call on a defined set of arguments.
  383. Subclasses can define additional arguments by adding Django model fields and must define the action to be taken by
  384. implementing the `_act` method.
  385. AuthenticatedAction provides the `state` property which by default is a hash of the action type (defined by the
  386. action's class path). Other information such as user state can be included in the state hash by (carefully)
  387. overriding the `_state_fields` property. Instantiation of the model, if given a `state` kwarg, will raise an error
  388. if the given state argument does not match the state computed from `_state_fields` at the moment of instantiation.
  389. The same applies to the `act` method: If called on an object that was instantiated without a `state` kwargs, an
  390. error will be raised.
  391. This effectively allows hash-authenticated procedure calls by third parties as long as the server-side state is
  392. unaltered, according to the following protocol:
  393. (1) Instantiate the AuthenticatedAction subclass representing the action to be taken (no `state` kwarg here),
  394. (2) provide information on how to instantiate the instance, and the state hash, to a third party,
  395. (3) when provided with data that allows instantiation and a valid state hash, take the defined action, possibly with
  396. additional parameters chosen by the third party that do not belong to the verified state.
  397. """
  398. _validated = False
  399. class Meta:
  400. managed = False
  401. def __init__(self, *args, **kwargs):
  402. state = kwargs.pop('state', None)
  403. super().__init__(*args, **kwargs)
  404. if state is not None:
  405. self._validated = self.validate_state(state)
  406. if not self._validated:
  407. raise ValueError
  408. @property
  409. def _state_fields(self):
  410. """
  411. Returns a list that defines the state of this action (used for authentication of this action).
  412. Return value must be JSON-serializable.
  413. Values not included in the return value will not be used for authentication, i.e. those values can be varied
  414. freely and function as unauthenticated action input parameters.
  415. Use caution when overriding this method. You will usually want to append a value to the list returned by the
  416. parent. Overriding the behavior altogether could result in reducing the state to fewer variables, resulting
  417. in valid signatures when they were intended to be invalid. The suggested method for overriding is
  418. @property
  419. def _state_fields:
  420. return super()._state_fields + [self.important_value, self.another_added_value]
  421. :return: List of values to be signed.
  422. """
  423. # TODO consider adding a "last change" attribute of the user to the state to avoid code
  424. # re-use after the the state has been changed and changed back.
  425. name = '.'.join([self.__module__, self.__class__.__qualname__])
  426. return [name]
  427. @property
  428. def state(self):
  429. state = json.dumps(self._state_fields).encode()
  430. hash = sha256()
  431. hash.update(state)
  432. return hash.hexdigest()
  433. def validate_state(self, value):
  434. return value == self.state
  435. def _act(self):
  436. """
  437. Conduct the action represented by this class.
  438. :return: None
  439. """
  440. raise NotImplementedError
  441. def act(self):
  442. if not self._validated:
  443. raise RuntimeError('Action state could not be verified.')
  444. return self._act()
  445. class AuthenticatedUserAction(ExportModelOperationsMixin('AuthenticatedUserAction'), AuthenticatedAction):
  446. """
  447. Abstract AuthenticatedAction involving an user instance, incorporating the user's id, email, password, and
  448. is_active flag into the Message Authentication Code state.
  449. """
  450. user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
  451. class Meta:
  452. managed = False
  453. @property
  454. def _state_fields(self):
  455. return super()._state_fields + [str(self.user.id), self.user.email, self.user.password, self.user.is_active]
  456. def _act(self):
  457. raise NotImplementedError
  458. class AuthenticatedActivateUserAction(ExportModelOperationsMixin('AuthenticatedActivateUserAction'), AuthenticatedUserAction):
  459. domain = models.CharField(max_length=191)
  460. class Meta:
  461. managed = False
  462. @property
  463. def _state_fields(self):
  464. return super()._state_fields + [self.domain]
  465. def _act(self):
  466. self.user.activate()
  467. class AuthenticatedChangeEmailUserAction(ExportModelOperationsMixin('AuthenticatedChangeEmailUserAction'), AuthenticatedUserAction):
  468. new_email = models.EmailField()
  469. class Meta:
  470. managed = False
  471. @property
  472. def _state_fields(self):
  473. return super()._state_fields + [self.new_email]
  474. def _act(self):
  475. self.user.change_email(self.new_email)
  476. class AuthenticatedResetPasswordUserAction(ExportModelOperationsMixin('AuthenticatedResetPasswordUserAction'), AuthenticatedUserAction):
  477. new_password = models.CharField(max_length=128)
  478. class Meta:
  479. managed = False
  480. def _act(self):
  481. self.user.change_password(self.new_password)
  482. class AuthenticatedDeleteUserAction(ExportModelOperationsMixin('AuthenticatedDeleteUserAction'), AuthenticatedUserAction):
  483. class Meta:
  484. managed = False
  485. def _act(self):
  486. self.user.delete()
  487. def captcha_default_content():
  488. alphabet = (string.ascii_uppercase + string.digits).translate({ord(c): None for c in 'IO0'})
  489. content = ''.join([secrets.choice(alphabet) for _ in range(5)])
  490. metrics.get('desecapi_captcha_content_created').inc()
  491. return content
  492. class Captcha(ExportModelOperationsMixin('Captcha'), models.Model):
  493. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  494. created = models.DateTimeField(auto_now_add=True)
  495. content = models.CharField(
  496. max_length=24,
  497. default=captcha_default_content,
  498. )
  499. def verify(self, solution: str):
  500. age = timezone.now() - self.created
  501. self.delete()
  502. return (
  503. str(solution).upper().strip() == self.content # solution correct
  504. and
  505. age <= settings.CAPTCHA_VALIDITY_PERIOD # not expired
  506. )