models.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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, uuid
  8. from django.core.validators import MinValueValidator
  9. from rest_framework.authtoken.models import Token
  10. from collections import OrderedDict
  11. class MyUserManager(BaseUserManager):
  12. def create_user(self, email, password=None, registration_remote_ip=None, lock=False, dyn=False):
  13. """
  14. Creates and saves a User with the given email, date of
  15. birth and password.
  16. """
  17. if not email:
  18. raise ValueError('Users must have an email address')
  19. user = self.model(
  20. email=self.normalize_email(email),
  21. registration_remote_ip=registration_remote_ip,
  22. locked=timezone.now() if lock else None,
  23. dyn=dyn,
  24. )
  25. user.set_password(password)
  26. user.save(using=self._db)
  27. return user
  28. def create_superuser(self, email, password):
  29. """
  30. Creates and saves a superuser with the given email, date of
  31. birth and password.
  32. """
  33. user = self.create_user(email,
  34. password=password
  35. )
  36. user.is_admin = True
  37. user.save(using=self._db)
  38. return user
  39. class User(AbstractBaseUser):
  40. email = models.EmailField(
  41. verbose_name='email address',
  42. max_length=191,
  43. unique=True,
  44. )
  45. is_active = models.BooleanField(default=True)
  46. is_admin = models.BooleanField(default=False)
  47. registration_remote_ip = models.CharField(max_length=1024, blank=True)
  48. locked = models.DateTimeField(null=True,blank=True)
  49. created = models.DateTimeField(auto_now_add=True)
  50. limit_domains = models.IntegerField(default=settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT,null=True,blank=True)
  51. dyn = models.BooleanField(default=False)
  52. objects = MyUserManager()
  53. USERNAME_FIELD = 'email'
  54. REQUIRED_FIELDS = []
  55. def get_full_name(self):
  56. return self.email
  57. def get_short_name(self):
  58. return self.email
  59. def get_token(self):
  60. token, created = Token.objects.get_or_create(user=self)
  61. return token.key
  62. def __str__(self):
  63. return self.email
  64. def has_perm(self, perm, obj=None):
  65. "Does the user have a specific permission?"
  66. # Simplest possible answer: Yes, always
  67. return True
  68. def has_module_perms(self, app_label):
  69. "Does the user have permissions to view the app `app_label`?"
  70. # Simplest possible answer: Yes, always
  71. return True
  72. @property
  73. def is_staff(self):
  74. "Is the user a member of staff?"
  75. # Simplest possible answer: All admins are staff
  76. return self.is_admin
  77. def unlock(self):
  78. # self.locked is used by domain.sync_to_pdns(), so call that first
  79. for domain in self.domains.all():
  80. domain.sync_to_pdns()
  81. self.locked = None
  82. self.save()
  83. class Domain(models.Model, mixins.SetterMixin):
  84. created = models.DateTimeField(auto_now_add=True)
  85. name = models.CharField(max_length=191, unique=True)
  86. owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='domains')
  87. _dirtyName = False
  88. def setter_name(self, val):
  89. if val != self.name:
  90. self._dirtyName = True
  91. return val
  92. def clean(self):
  93. if self._dirtyName:
  94. raise ValidationError('You must not change the domain name')
  95. @property
  96. def keys(self):
  97. return pdns.get_keys(self)
  98. @property
  99. def pdns_id(self):
  100. if '/' in self.name or '?' in self.name:
  101. raise SuspiciousOperation('Invalid hostname ' + self.name)
  102. # Transform to be valid pdns API identifiers (:id in their docs). The
  103. # '/' case here is just a safety measure (this case should never occur due
  104. # to the above check).
  105. # See also pdns code, apiZoneNameToId() in ws-api.cc
  106. name = self.name.translate(str.maketrans({'/': '=2F', '_': '=5F'}))
  107. if not name.endswith('.'):
  108. name += '.'
  109. return name
  110. def sync_to_pdns(self):
  111. """
  112. Make sure that pdns gets the latest information about this domain/zone.
  113. Re-syncing is relatively expensive and should not happen routinely.
  114. This method should only be called for new domains or on user unlocking.
  115. For unlocked users, it assumes that the domain is a new one.
  116. """
  117. # Determine if this domain is expected to be new on pdns. This is the
  118. # case if the user is not locked (by assumption) or if the domain was
  119. # created after the user was locked. (If the user had this domain
  120. # before locking, it is not new on pdns.)
  121. new = self.owner.locked is None or self.owner.locked < self.created
  122. if new:
  123. # Create zone
  124. # Throws exception if pdns already knows this zone for some reason
  125. # which means that it is not ours and we should not mess with it.
  126. # We escalate the exception to let the next level deal with the
  127. # response.
  128. pdns.create_zone(self, settings.DEFAULT_NS)
  129. # Import RRsets that may have been created (e.g. during lock).
  130. rrsets = self.rrset_set.all()
  131. if rrsets:
  132. pdns.set_rrsets(self, rrsets)
  133. # Make our RRsets consistent with pdns (specifically, NS may exist)
  134. self.sync_from_pdns()
  135. # For dedyn.io domains, propagate NS and DS delegation RRsets
  136. subname, parent_pdns_id = self.pdns_id.split('.', 1)
  137. if parent_pdns_id == 'dedyn.io.':
  138. try:
  139. parent = Domain.objects.get(name='dedyn.io')
  140. except Domain.DoesNotExist:
  141. pass
  142. else:
  143. rrsets = RRset.plain_to_RRsets([
  144. {'subname': subname, 'type': 'NS', 'ttl': 3600,
  145. 'contents': settings.DEFAULT_NS},
  146. {'subname': subname, 'type': 'DS', 'ttl': 60,
  147. 'contents': [ds for k in self.keys for ds in k['ds']]}
  148. ], domain=parent)
  149. parent.write_rrsets(rrsets)
  150. else:
  151. # Zone exists. For the case that pdns knows records that we do not
  152. # (e.g. if a locked account has deleted an RRset), it is necessary
  153. # to purge all records here. However, there is currently no way to
  154. # do this through the pdns API (not to mention doing it atomically
  155. # with setting the new RRsets). So for now, we have disabled RRset
  156. # deletion for locked accounts.
  157. rrsets = self.rrset_set.all()
  158. if rrsets:
  159. pdns.set_rrsets(self, rrsets)
  160. @transaction.atomic
  161. def sync_from_pdns(self):
  162. self.rrset_set.all().delete()
  163. rrsets = []
  164. rrs = []
  165. for rrset_data in pdns.get_rrset_datas(self):
  166. if rrset_data['type'] in RRset.RESTRICTED_TYPES:
  167. continue
  168. records = rrset_data.pop('records')
  169. rrset = RRset(**rrset_data)
  170. rrsets.append(rrset)
  171. rrs.extend([RR(rrset=rrset, content=record) for record in records])
  172. RRset.objects.bulk_create(rrsets)
  173. RR.objects.bulk_create(rrs)
  174. @transaction.atomic
  175. def write_rrsets(self, rrsets):
  176. # Base queryset for all RRsets of the current domain
  177. rrset_qs = RRset.objects.filter(domain=self)
  178. # Set to check RRset uniqueness
  179. rrsets_seen = set()
  180. # We want to return all new, changed, and unchanged RRsets (but not
  181. # deleted ones). We store them here, indexed by (subname, type).
  182. rrsets_to_return = OrderedDict()
  183. # Record contents to send to pdns, indexed by their RRset
  184. rrsets_for_pdns = {}
  185. # Always-false Q object: https://stackoverflow.com/a/35894246/6867099
  186. q_meaty = models.Q(pk__isnull=True)
  187. q_empty = models.Q(pk__isnull=True)
  188. # Determine which RRsets need to be updated or deleted
  189. for rrset, rrs in rrsets.items():
  190. if rrset.domain != self:
  191. raise ValueError('RRset has wrong domain')
  192. if (rrset.subname, rrset.type) in rrsets_seen:
  193. raise ValueError('RRset repeated with same subname and type')
  194. if rrs is not None and not all(rr.rrset is rrset for rr in rrs):
  195. raise ValueError('RR has wrong parent RRset')
  196. rrsets_seen.add((rrset.subname, rrset.type))
  197. q = models.Q(subname=rrset.subname, type=rrset.type)
  198. if rrs or rrs is None:
  199. rrsets_to_return[(rrset.subname, rrset.type)] = rrset
  200. q_meaty |= q
  201. else:
  202. # Set TTL so that pdns does not get confused if missing
  203. rrset.ttl = 1
  204. rrsets_for_pdns[rrset] = []
  205. q_empty |= q
  206. # Construct querysets representing RRsets that do (not) have RR
  207. # contents and lock them
  208. qs_meaty = rrset_qs.filter(q_meaty).select_for_update()
  209. qs_empty = rrset_qs.filter(q_empty).select_for_update()
  210. # For existing RRsets, execute TTL updates and/or mark for RR update.
  211. # First, let's create a to-do dict; we'll need it later for new RRsets.
  212. rrsets_with_new_rrs = []
  213. rrsets_meaty_todo = dict(rrsets_to_return)
  214. for rrset in qs_meaty.all():
  215. rrsets_to_return[(rrset.subname, rrset.type)] = rrset
  216. rrset_temp = rrsets_meaty_todo.pop((rrset.subname, rrset.type))
  217. rrs = {rr.content for rr in rrset.records.all()}
  218. partial = rrsets[rrset_temp] is None
  219. if partial:
  220. rrs_temp = rrs
  221. else:
  222. rrs_temp = {rr.content for rr in rrsets[rrset_temp]}
  223. # Take current TTL if none was given
  224. rrset_temp.ttl = rrset_temp.ttl or rrset.ttl
  225. changed_ttl = (rrset_temp.ttl != rrset.ttl)
  226. changed_rrs = not partial and (rrs_temp != rrs)
  227. if changed_ttl:
  228. rrset.ttl = rrset_temp.ttl
  229. rrset.save()
  230. if changed_rrs:
  231. rrsets_with_new_rrs.append(rrset)
  232. if changed_ttl or changed_rrs:
  233. rrsets_for_pdns[rrset] = [RR(rrset=rrset, content=rr_content)
  234. for rr_content in rrs_temp]
  235. # At this point, rrsets_meaty_todo contains new RRsets only, with
  236. # a list of RRs or with None associated.
  237. for key, rrset in list(rrsets_meaty_todo.items()):
  238. if rrsets[rrset] is None:
  239. # None means "don't change RRs". In the context of a new RRset,
  240. # this really is no-op, and we do not need to return the RRset.
  241. rrsets_to_return.pop((rrset.subname, rrset.type))
  242. else:
  243. # If there are associated RRs, let's save the RRset. This does
  244. # not save the RRs yet.
  245. rrsets_with_new_rrs.append(rrset)
  246. rrset.save()
  247. # In either case, send a request to pdns so that we can take
  248. # advantage of pdns' type validation check (even if no RRs given).
  249. rrsets_for_pdns[rrset] = rrsets[rrset]
  250. # Repeat lock to make sure new RRsets are also locked
  251. rrset_qs.filter(q_meaty).select_for_update()
  252. # Delete empty RRsets
  253. qs_empty.delete()
  254. # Update contents of modified RRsets
  255. RR.objects.filter(rrset__in=rrsets_with_new_rrs).delete()
  256. RR.objects.bulk_create([rr
  257. for (rrset, rrs) in rrsets_for_pdns.items()
  258. if rrs and rrset in rrsets_with_new_rrs
  259. for rr in rrs])
  260. # Send RRsets to pdns
  261. if rrsets_for_pdns and not self.owner.locked:
  262. pdns.set_rrsets(self, rrsets_for_pdns)
  263. # Return RRsets
  264. return list(rrsets_to_return.values())
  265. @transaction.atomic
  266. def delete(self, *args, **kwargs):
  267. # Delete delegation for dynDNS domains (direct child of dedyn.io)
  268. subname, parent_pdns_id = self.pdns_id.split('.', 1)
  269. if parent_pdns_id == 'dedyn.io.':
  270. try:
  271. parent = Domain.objects.get(name='dedyn.io')
  272. except Domain.DoesNotExist:
  273. pass
  274. else:
  275. rrsets = parent.rrset_set.filter(subname=subname,
  276. type__in=['NS', 'DS']).all()
  277. parent.write_rrsets({rrset: [] for rrset in rrsets})
  278. # Delete domain
  279. super().delete(*args, **kwargs)
  280. pdns.delete_zone(self)
  281. @transaction.atomic
  282. def save(self, *args, **kwargs):
  283. new = self.pk is None
  284. self.clean()
  285. super().save(*args, **kwargs)
  286. if new and not self.owner.locked:
  287. self.sync_to_pdns()
  288. def __str__(self):
  289. """
  290. Return domain name. Needed for serialization via StringRelatedField.
  291. (Must be unique.)
  292. """
  293. return self.name
  294. class Meta:
  295. ordering = ('created',)
  296. def get_default_value_created():
  297. return timezone.now()
  298. def get_default_value_due():
  299. return timezone.now() + datetime.timedelta(days=7)
  300. def get_default_value_mref():
  301. return "ONDON" + str((timezone.now() - timezone.datetime(1970,1,1,tzinfo=timezone.utc)).total_seconds())
  302. class Donation(models.Model):
  303. created = models.DateTimeField(default=get_default_value_created)
  304. name = models.CharField(max_length=255)
  305. iban = models.CharField(max_length=34)
  306. bic = models.CharField(max_length=11)
  307. amount = models.DecimalField(max_digits=8,decimal_places=2)
  308. message = models.CharField(max_length=255, blank=True)
  309. due = models.DateTimeField(default=get_default_value_due)
  310. mref = models.CharField(max_length=32,default=get_default_value_mref)
  311. email = models.EmailField(max_length=255, blank=True)
  312. def save(self, *args, **kwargs):
  313. self.iban = self.iban[:6] + "xxx" # do NOT save account details
  314. super().save(*args, **kwargs) # Call the "real" save() method.
  315. class Meta:
  316. ordering = ('created',)
  317. def validate_upper(value):
  318. if value != value.upper():
  319. raise ValidationError('Invalid value (not uppercase): %(value)s',
  320. code='invalid',
  321. params={'value': value})
  322. class RRset(models.Model, mixins.SetterMixin):
  323. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  324. created = models.DateTimeField(auto_now_add=True)
  325. updated = models.DateTimeField(null=True)
  326. domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
  327. subname = models.CharField(max_length=178, blank=True)
  328. type = models.CharField(max_length=10, validators=[validate_upper])
  329. ttl = models.PositiveIntegerField(validators=[MinValueValidator(1)])
  330. _dirty = False
  331. RESTRICTED_TYPES = ('SOA', 'RRSIG', 'DNSKEY', 'NSEC3PARAM')
  332. class Meta:
  333. unique_together = (("domain","subname","type"),)
  334. def __init__(self, *args, **kwargs):
  335. self._dirties = set()
  336. super().__init__(*args, **kwargs)
  337. def setter_domain(self, val):
  338. if val != self.domain:
  339. self._dirties.add('domain')
  340. return val
  341. def setter_subname(self, val):
  342. # On PUT, RRsetSerializer sends None, denoting the unchanged value
  343. if val is None:
  344. return self.subname
  345. if val != self.subname:
  346. self._dirties.add('subname')
  347. return val
  348. def setter_type(self, val):
  349. if val != self.type:
  350. self._dirties.add('type')
  351. return val
  352. def setter_ttl(self, val):
  353. if val != self.ttl:
  354. self._dirties.add('ttl')
  355. return val
  356. def clean(self):
  357. errors = {}
  358. for field in (self._dirties & {'domain', 'subname', 'type'}):
  359. errors[field] = ValidationError(
  360. 'You cannot change the `%s` field.' % field)
  361. if errors:
  362. raise ValidationError(errors)
  363. def get_dirties(self):
  364. return self._dirties
  365. @property
  366. def name(self):
  367. return '.'.join(filter(None, [self.subname, self.domain.name])) + '.'
  368. @transaction.atomic
  369. def delete(self, *args, **kwargs):
  370. # For locked users, we can't easily sync deleted RRsets to pdns later,
  371. # so let's forbid it for now.
  372. assert not self.domain.owner.locked
  373. super().delete(*args, **kwargs)
  374. pdns.set_rrset(self)
  375. self._dirties = {}
  376. def save(self, *args, **kwargs):
  377. # If not new, the only thing that can change is the TTL
  378. if self.created is None or 'ttl' in self.get_dirties():
  379. self.updated = timezone.now()
  380. self.full_clean()
  381. # Tell Django to not attempt an update, although the pk is not None
  382. kwargs['force_insert'] = (self.created is None)
  383. super().save(*args, **kwargs)
  384. self._dirties = {}
  385. @staticmethod
  386. def plain_to_RRsets(datas, *, domain):
  387. rrsets = {}
  388. for data in datas:
  389. rrset = RRset(domain=domain, subname=data['subname'],
  390. type=data['type'], ttl=data['ttl'])
  391. rrsets[rrset] = [RR(rrset=rrset, content=content)
  392. for content in data['contents']]
  393. return rrsets
  394. class RR(models.Model):
  395. created = models.DateTimeField(auto_now_add=True)
  396. rrset = models.ForeignKey(RRset, on_delete=models.CASCADE, related_name='records')
  397. # max_length is determined based on the calculation in
  398. # https://lists.isc.org/pipermail/bind-users/2008-April/070148.html
  399. content = models.CharField(max_length=4092)