models.py 19 KB

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