models.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. from __future__ import annotations
  2. import json
  3. import logging
  4. import random
  5. import time
  6. import uuid
  7. from base64 import b64encode
  8. from datetime import datetime, timedelta
  9. from os import urandom
  10. import rest_framework.authtoken.models
  11. from django.conf import settings
  12. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
  13. from django.core.exceptions import ValidationError
  14. from django.core.mail import EmailMessage
  15. from django.core.signing import Signer
  16. from django.core.validators import RegexValidator
  17. from django.db import models
  18. from django.db.models import Manager
  19. from django.template.loader import get_template
  20. from django.utils import timezone
  21. from django.utils.crypto import constant_time_compare
  22. from rest_framework.exceptions import APIException
  23. from desecapi import pdns
  24. logger = logging.getLogger(__name__)
  25. def validate_lower(value):
  26. if value != value.lower():
  27. raise ValidationError('Invalid value (not lowercase): %(value)s',
  28. code='invalid',
  29. params={'value': value})
  30. def validate_upper(value):
  31. if value != value.upper():
  32. raise ValidationError('Invalid value (not uppercase): %(value)s',
  33. code='invalid',
  34. params={'value': value})
  35. class MyUserManager(BaseUserManager):
  36. def create_user(self, email, password, **extra_fields):
  37. """
  38. Creates and saves a User with the given email, date of
  39. birth and password.
  40. """
  41. if not email:
  42. raise ValueError('Users must have an email address')
  43. email = self.normalize_email(email)
  44. extra_fields.setdefault('registration_remote_ip')
  45. user = self.model(email=email, **extra_fields)
  46. user.set_password(password)
  47. user.save(using=self._db)
  48. return user
  49. def create_superuser(self, email, password):
  50. """
  51. Creates and saves a superuser with the given email, date of
  52. birth and password.
  53. """
  54. user = self.create_user(email, password=password)
  55. user.is_admin = True
  56. user.save(using=self._db)
  57. return user
  58. class User(AbstractBaseUser):
  59. email = models.EmailField(
  60. verbose_name='email address',
  61. max_length=191,
  62. unique=True,
  63. )
  64. is_active = models.BooleanField(default=True)
  65. is_admin = models.BooleanField(default=False)
  66. registration_remote_ip = models.CharField(max_length=1024, blank=True)
  67. created = models.DateTimeField(auto_now_add=True)
  68. limit_domains = models.IntegerField(default=settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT, null=True, blank=True)
  69. objects = MyUserManager()
  70. USERNAME_FIELD = 'email'
  71. REQUIRED_FIELDS = []
  72. def get_full_name(self):
  73. return self.email
  74. def get_short_name(self):
  75. return self.email
  76. def get_or_create_first_token(self):
  77. try:
  78. token = Token.objects.filter(user=self).earliest('created')
  79. except Token.DoesNotExist:
  80. token = Token.objects.create(user=self)
  81. return token.key
  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 send_email(self, reason, context=None, recipient=None):
  113. context = context or {}
  114. reasons = [
  115. 'activate',
  116. 'activate-with-domain',
  117. 'change-email',
  118. 'change-email-confirmation-old-email',
  119. 'password-change-confirmation',
  120. 'reset-password',
  121. 'delete-user',
  122. ]
  123. recipient = recipient or self.email
  124. if reason not in reasons:
  125. raise ValueError('Cannot send email to user {} without a good reason: {}'.format(self.email, reason))
  126. content_tmpl = get_template('emails/{}/content.txt'.format(reason))
  127. subject_tmpl = get_template('emails/{}/subject.txt'.format(reason))
  128. from_tmpl = get_template('emails/from.txt')
  129. footer_tmpl = get_template('emails/footer.txt')
  130. email = EmailMessage(subject_tmpl.render(context).strip(),
  131. content_tmpl.render(context) + footer_tmpl.render(),
  132. from_tmpl.render(),
  133. [recipient])
  134. logger.warning('Sending email for user account %s (reason: %s)', str(self.pk), reason)
  135. email.send()
  136. class Token(rest_framework.authtoken.models.Token):
  137. key = models.CharField("Key", max_length=40, db_index=True, unique=True)
  138. # relation to user is a ForeignKey, so each user can have more than one token
  139. user = models.ForeignKey(
  140. User, related_name='auth_tokens',
  141. on_delete=models.CASCADE, verbose_name="User"
  142. )
  143. name = models.CharField("Name", max_length=64, default="")
  144. user_specific_id = models.BigIntegerField("User-Specific ID")
  145. def save(self, *args, **kwargs):
  146. if not self.user_specific_id:
  147. self.user_specific_id = random.randrange(16 ** 8)
  148. super().save(*args, **kwargs) # Call the "real" save() method.
  149. def generate_key(self):
  150. return b64encode(urandom(21)).decode('utf-8').replace('/', '-').replace('=', '_').replace('+', '.')
  151. class Meta:
  152. abstract = False
  153. unique_together = (('user', 'user_specific_id'),)
  154. class Domain(models.Model):
  155. created = models.DateTimeField(auto_now_add=True)
  156. name = models.CharField(max_length=191,
  157. unique=True,
  158. validators=[validate_lower,
  159. RegexValidator(regex=r'^[a-z0-9_.-]*[a-z]$',
  160. message='Invalid value (not a DNS name).',
  161. code='invalid_domain_name')
  162. ])
  163. owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='domains')
  164. published = models.DateTimeField(null=True, blank=True)
  165. minimum_ttl = models.PositiveIntegerField(default=settings.MINIMUM_TTL_DEFAULT)
  166. @property
  167. def keys(self):
  168. return pdns.get_keys(self)
  169. def has_local_public_suffix(self):
  170. return self.partition_name()[1] in settings.LOCAL_PUBLIC_SUFFIXES
  171. def parent_domain_name(self):
  172. return self.partition_name()[1]
  173. def partition_name(domain):
  174. name = domain.name if isinstance(domain, Domain) else domain
  175. subname, _, parent_name = name.partition('.')
  176. return subname, parent_name or None
  177. def save(self, *args, **kwargs):
  178. self.full_clean(validate_unique=False)
  179. super().save(*args, **kwargs)
  180. def update_delegation(self, child_domain: Domain):
  181. child_subname, child_domain_name = child_domain.partition_name()
  182. if self.name != child_domain_name:
  183. raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
  184. (child_domain.name, self.name))
  185. if child_domain.pk:
  186. # Domain real: set delegation
  187. child_keys = child_domain.keys
  188. if not child_keys:
  189. raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
  190. RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
  191. RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
  192. contents=[ds for k in child_keys for ds in k['ds']])
  193. else:
  194. # Domain not real: remove delegation
  195. for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
  196. rrset.delete()
  197. def __str__(self):
  198. return self.name
  199. class Meta:
  200. ordering = ('created',)
  201. def get_default_value_created():
  202. return timezone.now()
  203. def get_default_value_due():
  204. return timezone.now() + timedelta(days=7)
  205. def get_default_value_mref():
  206. return "ONDON" + str(time.time())
  207. class Donation(models.Model):
  208. created = models.DateTimeField(default=get_default_value_created)
  209. name = models.CharField(max_length=255)
  210. iban = models.CharField(max_length=34)
  211. bic = models.CharField(max_length=11)
  212. amount = models.DecimalField(max_digits=8, decimal_places=2)
  213. message = models.CharField(max_length=255, blank=True)
  214. due = models.DateTimeField(default=get_default_value_due)
  215. mref = models.CharField(max_length=32, default=get_default_value_mref)
  216. email = models.EmailField(max_length=255, blank=True)
  217. def save(self, *args, **kwargs):
  218. self.iban = self.iban[:6] + "xxx" # do NOT save account details
  219. super().save(*args, **kwargs)
  220. class Meta:
  221. ordering = ('created',)
  222. class RRsetManager(Manager):
  223. def create(self, contents=None, **kwargs):
  224. rrset = super().create(**kwargs)
  225. for content in contents or []:
  226. RR.objects.create(rrset=rrset, content=content)
  227. return rrset
  228. class RRset(models.Model):
  229. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  230. created = models.DateTimeField(auto_now_add=True)
  231. updated = models.DateTimeField(null=True)
  232. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  233. subname = models.CharField(
  234. max_length=178,
  235. blank=True,
  236. validators=[
  237. validate_lower,
  238. RegexValidator(
  239. regex=r'^([*]|(([*][.])?[a-z0-9_.-]*))$',
  240. message='Subname can only use (lowercase) a-z, 0-9, ., -, and _, '
  241. 'may start with a \'*.\', or just be \'*\'.',
  242. code='invalid_subname'
  243. )
  244. ]
  245. )
  246. type = models.CharField(
  247. max_length=10,
  248. validators=[
  249. validate_upper,
  250. RegexValidator(
  251. regex=r'^[A-Z][A-Z0-9]*$',
  252. message='Type must be uppercase alphanumeric and start with a letter.',
  253. code='invalid_type'
  254. )
  255. ]
  256. )
  257. ttl = models.PositiveIntegerField()
  258. objects = RRsetManager()
  259. DEAD_TYPES = ('ALIAS', 'DNAME')
  260. RESTRICTED_TYPES = ('SOA', 'RRSIG', 'DNSKEY', 'NSEC3PARAM', 'OPT')
  261. class Meta:
  262. unique_together = (("domain", "subname", "type"),)
  263. @staticmethod
  264. def construct_name(subname, domain_name):
  265. return '.'.join(filter(None, [subname, domain_name])) + '.'
  266. @property
  267. def name(self):
  268. return self.construct_name(self.subname, self.domain.name)
  269. def save(self, *args, **kwargs):
  270. self.updated = timezone.now()
  271. self.full_clean(validate_unique=False)
  272. super().save(*args, **kwargs)
  273. def __str__(self):
  274. return '<RRSet domain=%s type=%s subname=%s>' % (self.domain.name, self.type, self.subname)
  275. class RRManager(Manager):
  276. def bulk_create(self, rrs, **kwargs):
  277. ret = super().bulk_create(rrs, **kwargs)
  278. # For each rrset, save once to update published timestamp and trigger signal for post-save processing
  279. rrsets = {rr.rrset for rr in rrs}
  280. for rrset in rrsets:
  281. rrset.save()
  282. return ret
  283. class RR(models.Model):
  284. created = models.DateTimeField(auto_now_add=True)
  285. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  286. # max_length is determined based on the calculation in
  287. # https://lists.isc.org/pipermail/bind-users/2008-April/070148.html
  288. content = models.CharField(max_length=4092)
  289. objects = RRManager()
  290. def __str__(self):
  291. return '<RR %s>' % self.content
  292. def authenticated_action_default_timestamp():
  293. return int(datetime.timestamp(datetime.now()))
  294. class AuthenticatedAction(models.Model):
  295. """
  296. Represents a procedure call on a defined set of arguments.
  297. Subclasses can define additional arguments by adding Django model fields and must define the action to be taken by
  298. implementing the `act` method.
  299. AuthenticatedAction provides the `mac` property that returns a Message Authentication Code (MAC) based on the
  300. state. By default, the state contains the action's name (defined by the `name` property) and a timestamp; the
  301. state can be extended by (carefully) overriding the `mac_state` method. Any AuthenticatedAction instance of
  302. the same subclass and state will deterministically have the same MAC, effectively allowing authenticated
  303. procedure calls by third parties according to the following protocol:
  304. (1) Instantiate the AuthenticatedAction subclass representing the action to be taken with the desired state,
  305. (2) provide information on how to instantiate the instance and the MAC to a third party,
  306. (3) when provided with data that allows instantiation and a valid MAC, take the defined action, possibly with
  307. additional parameters chosen by the third party that do not belong to the verified state.
  308. """
  309. created = models.PositiveIntegerField(default=lambda: int(datetime.timestamp(datetime.now())))
  310. class Meta:
  311. managed = False
  312. def __init__(self, *args, **kwargs):
  313. # silently ignore any value supplied for the mac value, that makes it easier to use with DRF serializers
  314. kwargs.pop('mac', None)
  315. super().__init__(*args, **kwargs)
  316. @property
  317. def name(self):
  318. """
  319. Returns a human-readable string containing the name of this action class that uniquely identifies this action.
  320. """
  321. return NotImplementedError
  322. @property
  323. def mac(self):
  324. """
  325. Deterministically generates a message authentication code (MAC) for this action, based on the state as defined
  326. by `self.mac_state`. Identical state is guaranteed to yield identical MAC.
  327. :return:
  328. """
  329. return Signer().signature(json.dumps(self.mac_state))
  330. def check_mac(self, mac):
  331. """
  332. Checks if the message authentication code (MAC) provided by the first argument matches the MAC of this action.
  333. Note that expiration is not verified by this method.
  334. :param mac: Message Authentication Code
  335. :return: True, if MAC is valid; False otherwise.
  336. """
  337. return constant_time_compare(
  338. mac,
  339. self.mac,
  340. )
  341. def check_expiration(self, validity_period: timedelta, check_time: datetime = None):
  342. """
  343. Checks if the action's timestamp is no older than the given validity period. Note that the message
  344. authentication code itself is not verified by this method.
  345. :param validity_period: How long after issuance the MAC of this action is considered valid.
  346. :param check_time: Point in time for which to check the expiration. Defaults to datetime.now().
  347. :return: True if valid, False if expired.
  348. """
  349. issue_time = datetime.fromtimestamp(self.created)
  350. check_time = check_time or datetime.now()
  351. return check_time - issue_time <= validity_period
  352. @property
  353. def mac_state(self):
  354. """
  355. Returns a list that defines the state of this action (used for MAC calculation).
  356. Return value must be JSON-serializable.
  357. Values not included in the return value will not be used for MAC calculation, i.e. the MAC will be independent
  358. of them.
  359. Use caution when overriding this method. You will usually want to append a value to the list returned by the
  360. parent. Overriding the behavior altogether could result in reducing the state to fewer variables, resulting
  361. in valid signatures when they were intended to be invalid. The suggested method for overriding is
  362. @property
  363. def mac_state:
  364. return super().mac_state + [self.important_value, self.another_added_value]
  365. :return: List of values to be signed.
  366. """
  367. # TODO consider adding a "last change" attribute of the user to the state to avoid code
  368. # re-use after the the state has been changed and changed back.
  369. return [self.created, self.name]
  370. def act(self):
  371. """
  372. Conduct the action represented by this class.
  373. :return: None
  374. """
  375. raise NotImplementedError
  376. class AuthenticatedUserAction(AuthenticatedAction):
  377. """
  378. Abstract AuthenticatedAction involving an user instance, incorporating the user's id, email, password, and
  379. is_active flag into the Message Authentication Code state.
  380. """
  381. user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
  382. class Meta:
  383. managed = False
  384. @property
  385. def name(self):
  386. raise NotImplementedError
  387. @property
  388. def mac_state(self):
  389. return super().mac_state + [self.user.id, self.user.email, self.user.password, self.user.is_active]
  390. def act(self):
  391. raise NotImplementedError
  392. class AuthenticatedActivateUserAction(AuthenticatedUserAction):
  393. domain = models.CharField(max_length=191)
  394. class Meta:
  395. managed = False
  396. @property
  397. def name(self):
  398. return 'user/activate'
  399. def act(self):
  400. self.user.activate()
  401. class AuthenticatedChangeEmailUserAction(AuthenticatedUserAction):
  402. new_email = models.EmailField()
  403. class Meta:
  404. managed = False
  405. @property
  406. def name(self):
  407. return 'user/change_email'
  408. @property
  409. def mac_state(self):
  410. return super().mac_state + [self.new_email]
  411. def act(self):
  412. self.user.change_email(self.new_email)
  413. class AuthenticatedResetPasswordUserAction(AuthenticatedUserAction):
  414. new_password = models.CharField(max_length=128)
  415. class Meta:
  416. managed = False
  417. @property
  418. def name(self):
  419. return 'user/reset_password'
  420. def act(self):
  421. self.user.change_password(self.new_password)
  422. class AuthenticatedDeleteUserAction(AuthenticatedUserAction):
  423. class Meta:
  424. managed = False
  425. @property
  426. def name(self):
  427. return 'user/delete'
  428. def act(self):
  429. self.user.delete()