serializers.py 29 KB

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