serializers.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. import binascii
  2. import copy
  3. import json
  4. import re
  5. from base64 import urlsafe_b64decode, urlsafe_b64encode, b64encode
  6. from captcha.image import ImageCaptcha
  7. from django.contrib.auth.models import AnonymousUser
  8. from django.contrib.auth.password_validation import validate_password
  9. import django.core.exceptions
  10. from django.core.validators import MinValueValidator
  11. from django.db.models import Model, Q
  12. from django.utils import timezone
  13. from rest_framework import serializers
  14. from rest_framework.settings import api_settings
  15. from rest_framework.validators import UniqueTogetherValidator, UniqueValidator, qs_filter
  16. from api import settings
  17. from desecapi import crypto, metrics, models, validators
  18. class CaptchaSerializer(serializers.ModelSerializer):
  19. challenge = serializers.SerializerMethodField()
  20. class Meta:
  21. model = models.Captcha
  22. fields = ('id', 'challenge') if not settings.DEBUG else ('id', 'challenge', 'content')
  23. def get_challenge(self, obj: models.Captcha):
  24. # TODO Does this need to be stored in the object instance, in case this method gets called twice?
  25. challenge = ImageCaptcha().generate(obj.content).getvalue()
  26. return b64encode(challenge)
  27. class CaptchaSolutionSerializer(serializers.Serializer):
  28. id = serializers.PrimaryKeyRelatedField(
  29. queryset=models.Captcha.objects.all(),
  30. error_messages={'does_not_exist': 'CAPTCHA does not exist.'}
  31. )
  32. solution = serializers.CharField(write_only=True, required=True)
  33. def validate(self, attrs):
  34. captcha = attrs['id'] # Note that this already is the Captcha object
  35. if not captcha.verify(attrs['solution']):
  36. raise serializers.ValidationError('CAPTCHA could not be validated. Please obtain a new one and try again.')
  37. return attrs
  38. class TokenSerializer(serializers.ModelSerializer):
  39. token = serializers.ReadOnlyField(source='plain')
  40. class Meta:
  41. model = models.Token
  42. fields = ('id', 'created', 'last_used', 'name', 'token',)
  43. read_only_fields = ('id', 'created', 'last_used', 'token')
  44. def __init__(self, *args, include_plain=False, **kwargs):
  45. self.include_plain = include_plain
  46. return super().__init__(*args, **kwargs)
  47. def get_fields(self):
  48. fields = super().get_fields()
  49. if not self.include_plain:
  50. fields.pop('token')
  51. return fields
  52. class RequiredOnPartialUpdateCharField(serializers.CharField):
  53. """
  54. This field is always required, even for partial updates (e.g. using PATCH).
  55. """
  56. def validate_empty_values(self, data):
  57. if data is serializers.empty:
  58. self.fail('required')
  59. return super().validate_empty_values(data)
  60. class Validator:
  61. message = 'This field did not pass validation.'
  62. def __init__(self, message=None):
  63. self.field_name = None
  64. self.message = message or self.message
  65. self.instance = None
  66. def __call__(self, value):
  67. raise NotImplementedError
  68. def __repr__(self):
  69. return '<%s>' % self.__class__.__name__
  70. class ReadOnlyOnUpdateValidator(Validator):
  71. message = 'Can only be written on create.'
  72. requires_context = True
  73. def __call__(self, value, serializer_field):
  74. field_name = serializer_field.source_attrs[-1]
  75. instance = getattr(serializer_field.parent, 'instance', None)
  76. if isinstance(instance, Model) and value != getattr(instance, field_name):
  77. raise serializers.ValidationError(self.message, code='read-only-on-update')
  78. class ConditionalExistenceModelSerializer(serializers.ModelSerializer):
  79. """
  80. Only considers data with certain condition as existing data.
  81. If the existence condition does not hold, given instances are deleted, and no new instances are created,
  82. respectively. Also, to_representation and data will return None.
  83. Contrary, if the existence condition holds, the behavior is the same as DRF's ModelSerializer.
  84. """
  85. def exists(self, arg):
  86. """
  87. Determine if arg is to be considered existing.
  88. :param arg: Either a model instance or (possibly invalid!) data object.
  89. :return: Whether we treat this as non-existing instance.
  90. """
  91. raise NotImplementedError
  92. def to_representation(self, instance):
  93. return None if not self.exists(instance) else super().to_representation(instance)
  94. @property
  95. def data(self):
  96. try:
  97. return super().data
  98. except TypeError:
  99. return None
  100. def save(self, **kwargs):
  101. validated_data = {}
  102. validated_data.update(self.validated_data)
  103. validated_data.update(kwargs)
  104. known_instance = self.instance is not None
  105. data_exists = self.exists(validated_data)
  106. if known_instance and data_exists:
  107. self.instance = self.update(self.instance, validated_data)
  108. elif known_instance and not data_exists:
  109. self.delete()
  110. elif not known_instance and data_exists:
  111. self.instance = self.create(validated_data)
  112. elif not known_instance and not data_exists:
  113. pass # nothing to do
  114. return self.instance
  115. def delete(self):
  116. self.instance.delete()
  117. class NonBulkOnlyDefault:
  118. """
  119. This class may be used to provide default values that are only used
  120. for non-bulk operations, but that do not return any value for bulk
  121. operations.
  122. Implementation inspired by CreateOnlyDefault.
  123. """
  124. requires_context = True
  125. def __init__(self, default):
  126. self.default = default
  127. def __call__(self, serializer_field):
  128. is_many = getattr(serializer_field.root, 'many', False)
  129. if is_many:
  130. raise serializers.SkipField()
  131. if callable(self.default):
  132. if getattr(self.default, 'requires_context', False):
  133. return self.default(serializer_field)
  134. else:
  135. return self.default()
  136. return self.default
  137. def __repr__(self):
  138. return '%s(%s)' % (self.__class__.__name__, repr(self.default))
  139. class RRSerializer(serializers.ModelSerializer):
  140. class Meta:
  141. model = models.RR
  142. fields = ('content',)
  143. def to_internal_value(self, data):
  144. if not isinstance(data, str):
  145. raise serializers.ValidationError('Must be a string.', code='must-be-a-string')
  146. return super().to_internal_value({'content': data})
  147. def to_representation(self, instance):
  148. return instance.content
  149. class RRsetSerializer(ConditionalExistenceModelSerializer):
  150. domain = serializers.SlugRelatedField(read_only=True, slug_field='name')
  151. records = RRSerializer(many=True)
  152. ttl = serializers.IntegerField(max_value=604800)
  153. class Meta:
  154. model = models.RRset
  155. fields = ('created', 'domain', 'subname', 'name', 'records', 'ttl', 'type', 'touched',)
  156. extra_kwargs = {
  157. 'subname': {'required': False, 'default': NonBulkOnlyDefault('')}
  158. }
  159. def __init__(self, instance=None, data=serializers.empty, domain=None, **kwargs):
  160. if domain is None:
  161. raise ValueError('RRsetSerializer() must be given a domain object (to validate uniqueness constraints).')
  162. self.domain = domain
  163. super().__init__(instance, data, **kwargs)
  164. @classmethod
  165. def many_init(cls, *args, **kwargs):
  166. domain = kwargs.pop('domain')
  167. # Note: We are not yet deciding the value of the child's "partial" attribute, as its value depends on whether
  168. # the RRSet is created (never partial) or not (partial if PATCH), for each given item (RRset) individually.
  169. kwargs['child'] = cls(domain=domain)
  170. serializer = RRsetListSerializer(*args, **kwargs)
  171. metrics.get('desecapi_rrset_list_serializer').inc()
  172. return serializer
  173. def get_fields(self):
  174. fields = super().get_fields()
  175. fields['subname'].validators.append(ReadOnlyOnUpdateValidator())
  176. fields['type'].validators.append(ReadOnlyOnUpdateValidator())
  177. fields['ttl'].validators.append(MinValueValidator(limit_value=self.domain.minimum_ttl))
  178. return fields
  179. def get_validators(self):
  180. return [
  181. UniqueTogetherValidator(
  182. self.domain.rrset_set,
  183. ('subname', 'type'),
  184. message='Another RRset with the same subdomain and type exists for this domain.',
  185. ),
  186. validators.ExclusionConstraintValidator(
  187. self.domain.rrset_set,
  188. ('subname',),
  189. exclusion_condition=('type', 'CNAME',),
  190. message='RRset with conflicting type present: database ({types}).'
  191. ' (No other RRsets are allowed alongside CNAME.)',
  192. ),
  193. ]
  194. @staticmethod
  195. def validate_type(value):
  196. if value not in models.RR_SET_TYPES_MANAGEABLE:
  197. # user cannot manage this type, let's try to tell her the reason
  198. if value in models.RR_SET_TYPES_AUTOMATIC:
  199. raise serializers.ValidationError(f'You cannot tinker with the {value} RR set. It is managed '
  200. f'automatically.')
  201. elif value.startswith('TYPE'):
  202. raise serializers.ValidationError('Generic type format is not supported.')
  203. else:
  204. raise serializers.ValidationError(f'The {value} RR set type is currently unsupported.')
  205. return value
  206. def validate_records(self, value):
  207. # `records` is usually allowed to be empty (for idempotent delete), except for POST requests which are intended
  208. # for RRset creation only. We use the fact that DRF generic views pass the request in the serializer context.
  209. request = self.context.get('request')
  210. if request and request.method == 'POST' and not value:
  211. raise serializers.ValidationError('This field must not be empty when using POST.')
  212. return value
  213. def validate(self, attrs):
  214. if 'records' in attrs:
  215. # There is a 12 byte baseline requirement per record, c.f.
  216. # https://lists.isc.org/pipermail/bind-users/2008-April/070137.html
  217. # There also seems to be a 32 byte (?) baseline requirement per RRset, plus the qname length, see
  218. # https://lists.isc.org/pipermail/bind-users/2008-April/070148.html
  219. # The binary length of the record depends actually on the type, but it's never longer than vanilla len()
  220. qname = models.RRset.construct_name(attrs.get('subname', ''), self.domain.name)
  221. conservative_total_length = 32 + len(qname) + sum(12 + len(rr['content']) for rr in attrs['records'])
  222. # Add some leeway for RRSIG record (really ~110 bytes) and other data we have not thought of
  223. conservative_total_length += 256
  224. excess_length = conservative_total_length - 65535 # max response size
  225. if excess_length > 0:
  226. raise serializers.ValidationError(f'Total length of RRset exceeds limit by {excess_length} bytes.',
  227. code='max_length')
  228. return attrs
  229. def exists(self, arg):
  230. if isinstance(arg, models.RRset):
  231. return arg.records.exists()
  232. else:
  233. return bool(arg.get('records')) if 'records' in arg.keys() else True
  234. def create(self, validated_data):
  235. rrs_data = validated_data.pop('records')
  236. rrset = models.RRset.objects.create(**validated_data)
  237. self._set_all_record_contents(rrset, rrs_data)
  238. return rrset
  239. def update(self, instance: models.RRset, validated_data):
  240. rrs_data = validated_data.pop('records', None)
  241. if rrs_data is not None:
  242. self._set_all_record_contents(instance, rrs_data)
  243. ttl = validated_data.pop('ttl', None)
  244. if ttl and instance.ttl != ttl:
  245. instance.ttl = ttl
  246. instance.save() # also updates instance.touched
  247. else:
  248. # Update instance.touched without triggering post-save signal (no pdns action required)
  249. models.RRset.objects.filter(pk=instance.pk).update(touched=timezone.now())
  250. return instance
  251. def save(self, **kwargs):
  252. kwargs.setdefault('domain', self.domain)
  253. return super().save(**kwargs)
  254. @staticmethod
  255. def _set_all_record_contents(rrset: models.RRset, rrs):
  256. """
  257. Updates this RR set's resource records, discarding any old values.
  258. :param rrset: the RRset at which we overwrite all RRs
  259. :param rrs: list of RR representations
  260. """
  261. record_contents = [rr['content'] for rr in rrs]
  262. try:
  263. rrset.save_records(record_contents)
  264. except django.core.exceptions.ValidationError as e:
  265. raise serializers.ValidationError(e.messages, code='record-content')
  266. class RRsetListSerializer(serializers.ListSerializer):
  267. default_error_messages = {
  268. **serializers.Serializer.default_error_messages,
  269. **serializers.ListSerializer.default_error_messages,
  270. **{'not_a_list': 'Expected a list of items but got {input_type}.'},
  271. }
  272. @staticmethod
  273. def _key(data_item):
  274. return data_item.get('subname'), data_item.get('type')
  275. @staticmethod
  276. def _types_by_position_string(conflicting_indices_by_type):
  277. types_by_position = {}
  278. for type_, conflict_positions in conflicting_indices_by_type.items():
  279. for position in conflict_positions:
  280. types_by_position.setdefault(position, []).append(type_)
  281. # Sort by position, None at the end
  282. types_by_position = dict(sorted(types_by_position.items(), key=lambda x: (x[0] is None, x)))
  283. db_conflicts = types_by_position.pop(None, None)
  284. if db_conflicts: types_by_position['database'] = db_conflicts
  285. for position, types in types_by_position.items():
  286. types_by_position[position] = ', '.join(sorted(types))
  287. types_by_position = [f'{position} ({types})' for position, types in types_by_position.items()]
  288. return ', '.join(types_by_position)
  289. def to_internal_value(self, data):
  290. if not isinstance(data, list):
  291. message = self.error_messages['not_a_list'].format(input_type=type(data).__name__)
  292. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='not_a_list')
  293. if not self.allow_empty and len(data) == 0:
  294. if self.parent and self.partial:
  295. raise serializers.SkipField()
  296. else:
  297. self.fail('empty')
  298. ret = []
  299. errors = []
  300. partial = self.partial
  301. # build look-up objects for instances and data, so we can look them up with their keys
  302. try:
  303. known_instances = {(x.subname, x.type): x for x in self.instance}
  304. except TypeError: # in case self.instance is None (as during POST)
  305. known_instances = {}
  306. indices = {}
  307. for idx, item in enumerate(data):
  308. # Validate item type before using anything from it
  309. if not isinstance(item, dict):
  310. self.fail('invalid', datatype=type(item).__name__)
  311. s, t = self._key(item) # subname, type
  312. # Construct an index of the RRsets in `data` by `s` and `t`. As (subname, type) may be given multiple times
  313. # (although invalid), we make indices[s][t] a set to properly keep track. We also check and record RRsets
  314. # which are known in the database (once per subname), using index `None` (for checking CNAME exclusivity).
  315. if s not in indices:
  316. types = self.child.domain.rrset_set.filter(subname=s).values_list('type', flat=True)
  317. indices[s] = {type_: {None} for type_ in types}
  318. items = indices[s].setdefault(t, set())
  319. items.add(idx)
  320. collapsed_indices = copy.deepcopy(indices)
  321. for idx, item in enumerate(data):
  322. if item.get('records') == []:
  323. s, t = self._key(item)
  324. collapsed_indices[s][t] -= {idx, None}
  325. # Iterate over all rows in the data given
  326. for idx, item in enumerate(data):
  327. try:
  328. # see if other rows have the same key
  329. s, t = self._key(item)
  330. data_indices = indices[s][t] - {None}
  331. if len(data_indices) > 1:
  332. raise serializers.ValidationError({
  333. 'non_field_errors': [
  334. 'Same subname and type as in position(s) %s, but must be unique.' %
  335. ', '.join(map(str, data_indices - {idx}))
  336. ]
  337. })
  338. # see if other rows violate CNAME exclusivity
  339. if item.get('records') != []:
  340. conflicting_indices_by_type = {k: v for k, v in collapsed_indices[s].items()
  341. if (k == 'CNAME') != (t == 'CNAME')}
  342. if any(conflicting_indices_by_type.values()):
  343. types_by_position = self._types_by_position_string(conflicting_indices_by_type)
  344. raise serializers.ValidationError({
  345. 'non_field_errors': [
  346. f'RRset with conflicting type present: {types_by_position}.'
  347. ' (No other RRsets are allowed alongside CNAME.)'
  348. ]
  349. })
  350. # determine if this is a partial update (i.e. PATCH):
  351. # we allow partial update if a partial update method (i.e. PATCH) is used, as indicated by self.partial,
  352. # and if this is not actually a create request because it is unknown and nonempty
  353. unknown = self._key(item) not in known_instances.keys()
  354. nonempty = item.get('records', None) != []
  355. self.partial = partial and not (unknown and nonempty)
  356. self.child.instance = known_instances.get(self._key(item), None)
  357. # with partial value and instance in place, let the validation begin!
  358. validated = self.child.run_validation(item)
  359. except serializers.ValidationError as exc:
  360. errors.append(exc.detail)
  361. else:
  362. ret.append(validated)
  363. errors.append({})
  364. self.partial = partial
  365. if any(errors):
  366. raise serializers.ValidationError(errors)
  367. return ret
  368. def update(self, instance, validated_data):
  369. """
  370. Creates, updates and deletes RRsets according to the validated_data given. Relevant instances must be passed as
  371. a queryset in the `instance` argument.
  372. RRsets that appear in `instance` are considered "known", other RRsets are considered "unknown". RRsets that
  373. appear in `validated_data` with records == [] are considered empty, otherwise non-empty.
  374. The update proceeds as follows:
  375. 1. All unknown, non-empty RRsets are created.
  376. 2. All known, non-empty RRsets are updated.
  377. 3. All known, empty RRsets are deleted.
  378. 4. Unknown, empty RRsets will not cause any action.
  379. Rationale:
  380. As both "known"/"unknown" and "empty"/"non-empty" are binary partitions on `everything`, the combination of
  381. both partitions `everything` in four disjoint subsets. Hence, every RRset in `everything` is taken care of.
  382. empty | non-empty
  383. ------- | -------- | -----------
  384. known | delete | update
  385. unknown | no-op | create
  386. :param instance: QuerySet of relevant RRset objects, i.e. the Django.Model subclass instances. Relevant are all
  387. instances that are referenced in `validated_data`. If a referenced RRset is missing from instances, it will be
  388. considered unknown and hence be created. This may cause a database integrity error. If an RRset is given, but
  389. not relevant (i.e. not referred to by `validated_data`), a ValueError will be raised.
  390. :param validated_data: List of RRset data objects, i.e. dictionaries.
  391. :return: List of RRset objects (Django.Model subclass) that have been created or updated.
  392. """
  393. def is_empty(data_item):
  394. return data_item.get('records', None) == []
  395. query = Q(pk__in=[]) # start out with an always empty query, see https://stackoverflow.com/q/35893867/6867099
  396. for item in validated_data:
  397. query |= Q(type=item['type'], subname=item['subname']) # validation has ensured these fields exist
  398. instance = instance.filter(query)
  399. instance_index = {(rrset.subname, rrset.type): rrset for rrset in instance}
  400. data_index = {self._key(data): data for data in validated_data}
  401. if data_index.keys() | instance_index.keys() != data_index.keys():
  402. raise ValueError('Given set of known RRsets (`instance`) is not a subset of RRsets referred to in'
  403. ' `validated_data`. While this would produce a correct result, this is illegal due to its'
  404. ' inefficiency.')
  405. everything = instance_index.keys() | data_index.keys()
  406. known = instance_index.keys()
  407. unknown = everything - known
  408. # noinspection PyShadowingNames
  409. empty = {self._key(data) for data in validated_data if is_empty(data)}
  410. nonempty = everything - empty
  411. # noinspection PyUnusedLocal
  412. noop = unknown & empty
  413. created = unknown & nonempty
  414. updated = known & nonempty
  415. deleted = known & empty
  416. ret = []
  417. # The above algorithm makes sure that created, updated, and deleted are disjoint. Thus, no "override cases"
  418. # (such as: an RRset should be updated and delete, what should be applied last?) need to be considered.
  419. # We apply deletion first to get any possible CNAME exclusivity collisions out of the way.
  420. for subname, type_ in deleted:
  421. instance_index[(subname, type_)].delete()
  422. for subname, type_ in created:
  423. ret.append(self.child.create(
  424. validated_data=data_index[(subname, type_)]
  425. ))
  426. for subname, type_ in updated:
  427. ret.append(self.child.update(
  428. instance=instance_index[(subname, type_)],
  429. validated_data=data_index[(subname, type_)]
  430. ))
  431. return ret
  432. def save(self, **kwargs):
  433. kwargs.setdefault('domain', self.child.domain)
  434. return super().save(**kwargs)
  435. class DomainSerializer(serializers.ModelSerializer):
  436. class Meta:
  437. model = models.Domain
  438. fields = ('created', 'published', 'name', 'keys', 'minimum_ttl', 'touched',)
  439. read_only_fields = ('published', 'minimum_ttl',)
  440. extra_kwargs = {
  441. 'name': {'trim_whitespace': False},
  442. }
  443. def __init__(self, *args, include_keys=False, **kwargs):
  444. self.include_keys = include_keys
  445. return super().__init__(*args, **kwargs)
  446. def get_fields(self):
  447. fields = super().get_fields()
  448. if not self.include_keys:
  449. fields.pop('keys')
  450. fields['name'].validators.append(ReadOnlyOnUpdateValidator())
  451. return fields
  452. def validate_name(self, value):
  453. self.raise_if_domain_unavailable(value, self.context['request'].user)
  454. return value
  455. @staticmethod
  456. def raise_if_domain_unavailable(domain_name: str, user: models.User):
  457. user = user if not isinstance(user, AnonymousUser) else None
  458. if not models.Domain(name=domain_name, owner=user).is_registrable():
  459. raise serializers.ValidationError(
  460. 'This domain name conflicts with an existing zone, or is disallowed by policy.',
  461. code='name_unavailable'
  462. )
  463. def create(self, validated_data):
  464. if 'minimum_ttl' not in validated_data and models.Domain(name=validated_data['name']).is_locally_registrable:
  465. validated_data.update(minimum_ttl=60)
  466. return super().create(validated_data)
  467. class DonationSerializer(serializers.ModelSerializer):
  468. class Meta:
  469. model = models.Donation
  470. fields = ('name', 'iban', 'bic', 'amount', 'message', 'email', 'mref')
  471. read_only_fields = ('mref',)
  472. @staticmethod
  473. def validate_bic(value):
  474. return re.sub(r'[\s]', '', value)
  475. @staticmethod
  476. def validate_iban(value):
  477. return re.sub(r'[\s]', '', value)
  478. class UserSerializer(serializers.ModelSerializer):
  479. class Meta:
  480. model = models.User
  481. fields = ('created', 'email', 'id', 'limit_domains', 'password',)
  482. extra_kwargs = {
  483. 'password': {
  484. 'write_only': True, # Do not expose password field
  485. 'allow_null': True,
  486. }
  487. }
  488. def validate_password(self, value):
  489. if value is not None:
  490. validate_password(value)
  491. return value
  492. def create(self, validated_data):
  493. return models.User.objects.create_user(**validated_data)
  494. class RegisterAccountSerializer(UserSerializer):
  495. domain = serializers.CharField(required=False, validators=models.validate_domain_name)
  496. captcha = CaptchaSolutionSerializer(required=True)
  497. class Meta:
  498. model = UserSerializer.Meta.model
  499. fields = ('email', 'password', 'domain', 'captcha')
  500. extra_kwargs = UserSerializer.Meta.extra_kwargs
  501. def validate_domain(self, value):
  502. DomainSerializer.raise_if_domain_unavailable(value, self.context['request'].user)
  503. return value
  504. def create(self, validated_data):
  505. validated_data.pop('domain', None)
  506. validated_data.pop('captcha', None)
  507. return super().create(validated_data)
  508. class EmailSerializer(serializers.Serializer):
  509. email = serializers.EmailField()
  510. class EmailPasswordSerializer(EmailSerializer):
  511. password = serializers.CharField()
  512. class ChangeEmailSerializer(serializers.Serializer):
  513. new_email = serializers.EmailField()
  514. def validate_new_email(self, value):
  515. if value == self.context['request'].user.email:
  516. raise serializers.ValidationError('Email address unchanged.')
  517. return value
  518. class ResetPasswordSerializer(EmailSerializer):
  519. captcha = CaptchaSolutionSerializer(required=True)
  520. class CustomFieldNameUniqueValidator(UniqueValidator):
  521. """
  522. Does exactly what rest_framework's UniqueValidator does, however allows to further customize the
  523. query that is used to determine the uniqueness.
  524. More specifically, we allow that the field name the value is queried against is passed when initializing
  525. this validator. (At the time of writing, UniqueValidator insists that the field's name is used for the
  526. database query field; only how the lookup must match is allowed to be changed.)
  527. """
  528. def __init__(self, queryset, message=None, lookup='exact', lookup_field=None):
  529. self.lookup_field = lookup_field
  530. super().__init__(queryset, message, lookup)
  531. def filter_queryset(self, value, queryset, field_name):
  532. """
  533. Filter the queryset to all instances matching the given value on the specified lookup field.
  534. """
  535. filter_kwargs = {'%s__%s' % (self.lookup_field or field_name, self.lookup): value}
  536. return qs_filter(queryset, **filter_kwargs)
  537. class AuthenticatedActionSerializer(serializers.ModelSerializer):
  538. state = serializers.CharField() # serializer read-write, but model read-only field
  539. validity_period = settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE
  540. class Meta:
  541. model = models.AuthenticatedAction
  542. fields = ('state',)
  543. @classmethod
  544. def _pack_code(cls, data):
  545. payload = json.dumps(data).encode()
  546. payload_enc = crypto.encrypt(payload, context='desecapi.serializers.AuthenticatedActionSerializer')
  547. return urlsafe_b64encode(payload_enc).decode()
  548. @classmethod
  549. def _unpack_code(cls, code, *, ttl):
  550. try:
  551. payload_enc = urlsafe_b64decode(code.encode())
  552. payload = crypto.decrypt(payload_enc, context='desecapi.serializers.AuthenticatedActionSerializer', ttl=ttl)
  553. return json.loads(payload.decode())
  554. except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
  555. raise ValueError
  556. def to_representation(self, instance: models.AuthenticatedUserAction):
  557. # do the regular business
  558. data = super().to_representation(instance)
  559. # encode into single string
  560. return {'code': self._pack_code(data)}
  561. def to_internal_value(self, data):
  562. data = data.copy() # avoid side effect from .pop
  563. # calculate code TTL
  564. validity_period = self.context.get('validity_period', self.validity_period)
  565. try:
  566. ttl = validity_period.total_seconds()
  567. except AttributeError:
  568. ttl = None # infinite
  569. # decode from single string
  570. try:
  571. unpacked_data = self._unpack_code(self.context['code'], ttl=ttl)
  572. except KeyError:
  573. raise serializers.ValidationError({'code': ['This field is required.']})
  574. except ValueError:
  575. if ttl is None:
  576. msg = 'This code is invalid.'
  577. else:
  578. msg = f'This code is invalid, possibly because it expired (validity: {validity_period}).'
  579. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: msg, 'code': 'invalid_code'})
  580. # add extra fields added by the user
  581. unpacked_data.update(**data)
  582. # do the regular business
  583. return super().to_internal_value(unpacked_data)
  584. def act(self):
  585. self.instance.act()
  586. return self.instance
  587. def save(self, **kwargs):
  588. raise ValueError
  589. class AuthenticatedBasicUserActionSerializer(AuthenticatedActionSerializer):
  590. user = serializers.PrimaryKeyRelatedField(
  591. queryset=models.User.objects.all(),
  592. error_messages={'does_not_exist': 'This user does not exist.'},
  593. pk_field=serializers.UUIDField()
  594. )
  595. class Meta:
  596. model = models.AuthenticatedBasicUserAction
  597. fields = AuthenticatedActionSerializer.Meta.fields + ('user',)
  598. class AuthenticatedActivateUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  599. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  600. model = models.AuthenticatedActivateUserAction
  601. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('domain',)
  602. extra_kwargs = {
  603. 'domain': {'default': None, 'allow_null': True}
  604. }
  605. class AuthenticatedChangeEmailUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  606. new_email = serializers.EmailField(
  607. validators=[
  608. CustomFieldNameUniqueValidator(
  609. queryset=models.User.objects.all(),
  610. lookup_field='email',
  611. message='You already have another account with this email address.',
  612. )
  613. ],
  614. required=True,
  615. )
  616. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  617. model = models.AuthenticatedChangeEmailUserAction
  618. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('new_email',)
  619. class AuthenticatedResetPasswordUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  620. new_password = serializers.CharField(write_only=True)
  621. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  622. model = models.AuthenticatedResetPasswordUserAction
  623. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('new_password',)
  624. class AuthenticatedDeleteUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  625. class Meta(AuthenticatedBasicUserActionSerializer.Meta):
  626. model = models.AuthenticatedDeleteUserAction
  627. class AuthenticatedDomainBasicUserActionSerializer(AuthenticatedBasicUserActionSerializer):
  628. domain = serializers.PrimaryKeyRelatedField(
  629. queryset=models.Domain.objects.all(),
  630. error_messages={'does_not_exist': 'This domain does not exist.'},
  631. )
  632. class Meta:
  633. model = models.AuthenticatedDomainBasicUserAction
  634. fields = AuthenticatedBasicUserActionSerializer.Meta.fields + ('domain',)
  635. class AuthenticatedRenewDomainBasicUserActionSerializer(AuthenticatedDomainBasicUserActionSerializer):
  636. validity_period = None
  637. class Meta(AuthenticatedDomainBasicUserActionSerializer.Meta):
  638. model = models.AuthenticatedRenewDomainBasicUserAction