serializers.py 28 KB

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