serializers.py 32 KB

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