models.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. from django.conf import settings
  2. from django.db import models, transaction
  3. from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
  4. from django.utils import timezone
  5. from django.core.exceptions import SuspiciousOperation, ValidationError
  6. from desecapi import pdns, mixins
  7. import datetime
  8. from django.core.validators import MinValueValidator
  9. class MyUserManager(BaseUserManager):
  10. def create_user(self, email, password=None, registration_remote_ip=None, captcha_required=False, dyn=False):
  11. """
  12. Creates and saves a User with the given email, date of
  13. birth and password.
  14. """
  15. if not email:
  16. raise ValueError('Users must have an email address')
  17. user = self.model(
  18. email=self.normalize_email(email),
  19. registration_remote_ip=registration_remote_ip,
  20. captcha_required=captcha_required,
  21. dyn=dyn,
  22. )
  23. user.set_password(password)
  24. user.save(using=self._db)
  25. return user
  26. def create_superuser(self, email, password):
  27. """
  28. Creates and saves a superuser with the given email, date of
  29. birth and password.
  30. """
  31. user = self.create_user(email,
  32. password=password
  33. )
  34. user.is_admin = True
  35. user.save(using=self._db)
  36. return user
  37. class User(AbstractBaseUser):
  38. email = models.EmailField(
  39. verbose_name='email address',
  40. max_length=191,
  41. unique=True,
  42. )
  43. is_active = models.BooleanField(default=True)
  44. is_admin = models.BooleanField(default=False)
  45. registration_remote_ip = models.CharField(max_length=1024, blank=True)
  46. captcha_required = models.BooleanField(default=False)
  47. created = models.DateTimeField(auto_now_add=True)
  48. limit_domains = models.IntegerField(default=settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT,null=True,blank=True)
  49. dyn = models.BooleanField(default=False)
  50. objects = MyUserManager()
  51. USERNAME_FIELD = 'email'
  52. REQUIRED_FIELDS = []
  53. def get_full_name(self):
  54. return self.email
  55. def get_short_name(self):
  56. return self.email
  57. def __str__(self):
  58. return self.email
  59. def has_perm(self, perm, obj=None):
  60. "Does the user have a specific permission?"
  61. # Simplest possible answer: Yes, always
  62. return True
  63. def has_module_perms(self, app_label):
  64. "Does the user have permissions to view the app `app_label`?"
  65. # Simplest possible answer: Yes, always
  66. return True
  67. @property
  68. def is_staff(self):
  69. "Is the user a member of staff?"
  70. # Simplest possible answer: All admins are staff
  71. return self.is_admin
  72. def unlock(self):
  73. self.captcha_required = False
  74. for domain in self.domains.all():
  75. domain.pdns_resync()
  76. self.save()
  77. class Domain(models.Model, mixins.SetterMixin):
  78. created = models.DateTimeField(auto_now_add=True)
  79. updated = models.DateTimeField(null=True)
  80. name = models.CharField(max_length=191, unique=True)
  81. arecord = models.GenericIPAddressField(protocol='IPv4', blank=False, null=True)
  82. aaaarecord = models.GenericIPAddressField(protocol='IPv6', blank=False, null=True)
  83. owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='domains')
  84. acme_challenge = models.CharField(max_length=255, blank=True)
  85. _dirtyName = False
  86. _dirtyRecords = False
  87. def setter_name(self, val):
  88. if val != self.name:
  89. self._dirtyName = True
  90. return val
  91. def setter_arecord(self, val):
  92. if val != self.arecord:
  93. self._dirtyRecords = True
  94. return val
  95. def setter_aaaarecord(self, val):
  96. if val != self.aaaarecord:
  97. self._dirtyRecords = True
  98. return val
  99. def setter_acme_challenge(self, val):
  100. if val != self.acme_challenge:
  101. self._dirtyRecords = True
  102. return val
  103. def clean(self):
  104. if self._dirtyName:
  105. raise ValidationError('You must not change the domain name')
  106. @property
  107. def pdns_id(self):
  108. if '/' in self.name or '?' in self.name:
  109. raise SuspiciousOperation('Invalid hostname ' + self.name)
  110. # Transform to be valid pdns API identifiers (:id in their docs). The
  111. # '/' case here is just a safety measure (this case should never occur due
  112. # to the above check).
  113. # See also pdns code, apiZoneNameToId() in ws-api.cc
  114. name = self.name.translate(str.maketrans({'/': '=2F', '_': '=5F'}))
  115. if not name.endswith('.'):
  116. name += '.'
  117. return name
  118. def pdns_resync(self):
  119. """
  120. Make sure that pdns gets the latest information about this domain/zone.
  121. Re-Syncing is relatively expensive and should not happen routinely.
  122. """
  123. # Create zone if it does not exist yet
  124. try:
  125. pdns.create_zone(self)
  126. except pdns.PdnsException as e:
  127. if e.status_code == 422 and e.detail.endswith(' already exists'):
  128. pass
  129. # update zone to latest information
  130. pdns.set_dyn_records(self)
  131. def pdns_sync(self, new_domain):
  132. """
  133. Command pdns updates as indicated by the local changes.
  134. """
  135. if self.owner.captcha_required:
  136. # suspend all updates
  137. return
  138. # if this zone is new, create it and set dirty flag if necessary
  139. if new_domain:
  140. pdns.create_zone(self)
  141. self._dirtyRecords = bool(self.arecord) or bool(self.aaaarecord) or bool(self.acme_challenge)
  142. # make changes if necessary
  143. if self._dirtyRecords:
  144. pdns.set_dyn_records(self)
  145. self._dirtyRecords = False
  146. def sync_from_pdns(self):
  147. with transaction.atomic():
  148. RRset.objects.filter(domain=self).delete()
  149. rrsets = pdns.get_rrsets(self)
  150. rrsets = [rrset for rrset in rrsets if rrset.type != 'SOA']
  151. RRset.objects.bulk_create(rrsets)
  152. @transaction.atomic
  153. def delete(self, *args, **kwargs):
  154. super(Domain, self).delete(*args, **kwargs)
  155. pdns.delete_zone(self)
  156. if self.name.endswith('.dedyn.io'):
  157. pdns.set_rrset_in_parent(self, 'DS', '')
  158. pdns.set_rrset_in_parent(self, 'NS', '')
  159. @transaction.atomic
  160. def save(self, *args, **kwargs):
  161. # Record here if this is a new domain (self.pk is only None until we call super.save())
  162. new_domain = self.pk is None
  163. self.updated = timezone.now()
  164. self.clean()
  165. super(Domain, self).save(*args, **kwargs)
  166. self.pdns_sync(new_domain)
  167. class Meta:
  168. ordering = ('created',)
  169. def get_default_value_created():
  170. return timezone.now()
  171. def get_default_value_due():
  172. return timezone.now() + datetime.timedelta(days=7)
  173. def get_default_value_mref():
  174. return "ONDON" + str((timezone.now() - timezone.datetime(1970,1,1,tzinfo=timezone.utc)).total_seconds())
  175. class Donation(models.Model):
  176. created = models.DateTimeField(default=get_default_value_created)
  177. name = models.CharField(max_length=255)
  178. iban = models.CharField(max_length=34)
  179. bic = models.CharField(max_length=11)
  180. amount = models.DecimalField(max_digits=8,decimal_places=2)
  181. message = models.CharField(max_length=255, blank=True)
  182. due = models.DateTimeField(default=get_default_value_due)
  183. mref = models.CharField(max_length=32,default=get_default_value_mref)
  184. email = models.EmailField(max_length=255, blank=True)
  185. def save(self, *args, **kwargs):
  186. self.iban = self.iban[:6] + "xxx" # do NOT save account details
  187. super(Donation, self).save(*args, **kwargs) # Call the "real" save() method.
  188. class Meta:
  189. ordering = ('created',)
  190. def validate_upper(value):
  191. if value != value.upper():
  192. raise ValidationError('Invalid value (not uppercase): %(value)s',
  193. code='invalid',
  194. params={'value': value})
  195. class RRset(models.Model, mixins.SetterMixin):
  196. created = models.DateTimeField(auto_now_add=True)
  197. updated = models.DateTimeField(null=True)
  198. domain = models.ForeignKey(Domain, on_delete=models.CASCADE, related_name='rrsets')
  199. subname = models.CharField(max_length=178, blank=True)
  200. type = models.CharField(max_length=10, validators=[validate_upper])
  201. records = models.CharField(max_length=64000, blank=True)
  202. ttl = models.PositiveIntegerField(validators=[MinValueValidator(1)])
  203. _dirty = False
  204. class Meta:
  205. unique_together = (("domain","subname","type"),)
  206. def __init__(self, *args, **kwargs):
  207. self._dirties = set()
  208. super().__init__(*args, **kwargs)
  209. def setter_domain(self, val):
  210. if val != self.domain:
  211. self._dirties.add('domain')
  212. return val
  213. def setter_subname(self, val):
  214. # On PUT, RRsetSerializer sends None, denoting the unchanged value
  215. if val is None:
  216. return self.subname
  217. if val != self.subname:
  218. self._dirties.add('subname')
  219. return val
  220. def setter_type(self, val):
  221. if val != self.type:
  222. self._dirties.add('type')
  223. return val
  224. def setter_records(self, val):
  225. if val != self.records:
  226. self._dirty = True
  227. return val
  228. def setter_ttl(self, val):
  229. if val != self.ttl:
  230. self._dirty = True
  231. return val
  232. def clean(self):
  233. errors = {}
  234. for field in self._dirties:
  235. errors[field] = ValidationError(
  236. 'You cannot change the `%s` field.' % field)
  237. if errors:
  238. raise ValidationError(errors)
  239. @property
  240. def name(self):
  241. return '.'.join(filter(None, [self.subname, self.domain.name])) + '.'
  242. def update_pdns(self):
  243. pdns.set_rrset(self)
  244. pdns.notify_zone(self.domain)
  245. @transaction.atomic
  246. def delete(self, *args, **kwargs):
  247. # Reset records so that our pdns update later will cause deletion
  248. self.records = '[]'
  249. super().delete(*args, **kwargs)
  250. self.update_pdns()
  251. @transaction.atomic
  252. def save(self, *args, **kwargs):
  253. new = self.pk is None
  254. self.updated = timezone.now()
  255. self.full_clean()
  256. super().save(*args, **kwargs)
  257. if self._dirty or new:
  258. self.update_pdns()