models.py 19 KB

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