serializers.py 28 KB

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