models.py 27 KB

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