serializers.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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 exists(self, arg):
  201. if isinstance(arg, models.RRset):
  202. return arg.records.exists()
  203. else:
  204. return bool(arg.get('records')) if 'records' in arg.keys() else True
  205. def create(self, validated_data):
  206. rrs_data = validated_data.pop('records')
  207. rrset = models.RRset.objects.create(**validated_data)
  208. self._set_all_record_contents(rrset, rrs_data)
  209. return rrset
  210. def update(self, instance: models.RRset, validated_data):
  211. rrs_data = validated_data.pop('records', None)
  212. if rrs_data is not None:
  213. self._set_all_record_contents(instance, rrs_data)
  214. ttl = validated_data.pop('ttl', None)
  215. if ttl and instance.ttl != ttl:
  216. instance.ttl = ttl
  217. instance.save()
  218. return instance
  219. @staticmethod
  220. def _set_all_record_contents(rrset: models.RRset, rrs):
  221. """
  222. Updates this RR set's resource records, discarding any old values.
  223. To do so, two large select queries and one query per changed (added or removed) resource record are needed.
  224. Changes are saved to the database immediately.
  225. :param rrset: the RRset at which we overwrite all RRs
  226. :param rrs: list of RR representations
  227. """
  228. record_contents = [rr['content'] for rr in rrs]
  229. # Remove RRs that we didn't see in the new list
  230. removed_rrs = rrset.records.exclude(content__in=record_contents) # one SELECT
  231. for rr in removed_rrs:
  232. rr.delete() # one DELETE query
  233. # Figure out which entries in record_contents have not changed
  234. unchanged_rrs = rrset.records.filter(content__in=record_contents) # one SELECT
  235. unchanged_content = [unchanged_rr.content for unchanged_rr in unchanged_rrs]
  236. added_content = filter(lambda c: c not in unchanged_content, record_contents)
  237. rrs = [models.RR(rrset=rrset, content=content) for content in added_content]
  238. models.RR.objects.bulk_create(rrs) # One INSERT
  239. class RRsetListSerializer(serializers.ListSerializer):
  240. default_error_messages = {
  241. **serializers.Serializer.default_error_messages,
  242. **serializers.ListSerializer.default_error_messages,
  243. **{'not_a_list': 'Expected a list of items but got {input_type}.'},
  244. }
  245. @staticmethod
  246. def _key(data_item):
  247. return data_item.get('subname', None), data_item.get('type', None)
  248. def to_internal_value(self, data):
  249. if not isinstance(data, list):
  250. message = self.error_messages['not_a_list'].format(input_type=type(data).__name__)
  251. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='not_a_list')
  252. if not self.allow_empty and len(data) == 0:
  253. if self.parent and self.partial:
  254. raise serializers.SkipField()
  255. else:
  256. self.fail('empty')
  257. ret = []
  258. errors = []
  259. partial = self.partial
  260. # build look-up objects for instances and data, so we can look them up with their keys
  261. try:
  262. known_instances = {(x.subname, x.type): x for x in self.instance}
  263. except TypeError: # in case self.instance is None (as during POST)
  264. known_instances = {}
  265. indices_by_key = {}
  266. for idx, item in enumerate(data):
  267. # Validate item type before using anything from it
  268. if not isinstance(item, dict):
  269. self.fail('invalid', datatype=type(item).__name__)
  270. items = indices_by_key.setdefault(self._key(item), set())
  271. items.add(idx)
  272. # Iterate over all rows in the data given
  273. for idx, item in enumerate(data):
  274. try:
  275. # see if other rows have the same key
  276. if len(indices_by_key[self._key(item)]) > 1:
  277. raise serializers.ValidationError({
  278. 'non_field_errors': [
  279. 'Same subname and type as in position(s) %s, but must be unique.' %
  280. ', '.join(map(str, indices_by_key[self._key(item)] - {idx}))
  281. ]
  282. })
  283. # determine if this is a partial update (i.e. PATCH):
  284. # we allow partial update if a partial update method (i.e. PATCH) is used, as indicated by self.partial,
  285. # and if this is not actually a create request because it is unknown and nonempty
  286. unknown = self._key(item) not in known_instances.keys()
  287. nonempty = item.get('records', None) != []
  288. self.partial = partial and not (unknown and nonempty)
  289. self.child.instance = known_instances.get(self._key(item), None)
  290. # with partial value and instance in place, let the validation begin!
  291. validated = self.child.run_validation(item)
  292. except serializers.ValidationError as exc:
  293. errors.append(exc.detail)
  294. else:
  295. ret.append(validated)
  296. errors.append({})
  297. self.partial = partial
  298. if any(errors):
  299. raise serializers.ValidationError(errors)
  300. return ret
  301. def update(self, instance, validated_data):
  302. """
  303. Creates, updates and deletes RRsets according to the validated_data given. Relevant instances must be passed as
  304. a queryset in the `instance` argument.
  305. RRsets that appear in `instance` are considered "known", other RRsets are considered "unknown". RRsets that
  306. appear in `validated_data` with records == [] are considered empty, otherwise non-empty.
  307. The update proceeds as follows:
  308. 1. All unknown, non-empty RRsets are created.
  309. 2. All known, non-empty RRsets are updated.
  310. 3. All known, empty RRsets are deleted.
  311. 4. Unknown, empty RRsets will not cause any action.
  312. Rationale:
  313. As both "known"/"unknown" and "empty"/"non-empty" are binary partitions on `everything`, the combination of
  314. both partitions `everything` in four disjoint subsets. Hence, every RRset in `everything` is taken care of.
  315. empty | non-empty
  316. ------- | -------- | -----------
  317. known | delete | update
  318. unknown | no-op | create
  319. :param instance: QuerySet of relevant RRset objects, i.e. the Django.Model subclass instances. Relevant are all
  320. instances that are referenced in `validated_data`. If a referenced RRset is missing from instances, it will be
  321. considered unknown and hence be created. This may cause a database integrity error. If an RRset is given, but
  322. not relevant (i.e. not referred to by `validated_data`), a ValueError will be raised.
  323. :param validated_data: List of RRset data objects, i.e. dictionaries.
  324. :return: List of RRset objects (Django.Model subclass) that have been created or updated.
  325. """
  326. def is_empty(data_item):
  327. return data_item.get('records', None) == []
  328. query = Q()
  329. for item in validated_data:
  330. query |= Q(type=item['type'], subname=item['subname']) # validation has ensured these fields exist
  331. instance = instance.filter(query)
  332. instance_index = {(rrset.subname, rrset.type): rrset for rrset in instance}
  333. data_index = {self._key(data): data for data in validated_data}
  334. if data_index.keys() | instance_index.keys() != data_index.keys():
  335. raise ValueError('Given set of known RRsets (`instance`) is not a subset of RRsets referred to in'
  336. '`validated_data`. While this would produce a correct result, this is illegal due to its'
  337. ' inefficiency.')
  338. everything = instance_index.keys() | data_index.keys()
  339. known = instance_index.keys()
  340. unknown = everything - known
  341. # noinspection PyShadowingNames
  342. empty = {self._key(data) for data in validated_data if is_empty(data)}
  343. nonempty = everything - empty
  344. # noinspection PyUnusedLocal
  345. noop = unknown & empty
  346. created = unknown & nonempty
  347. updated = known & nonempty
  348. deleted = known & empty
  349. ret = []
  350. try:
  351. for subname, type_ in created:
  352. ret.append(self.child.create(
  353. validated_data=data_index[(subname, type_)]
  354. ))
  355. for subname, type_ in updated:
  356. ret.append(self.child.update(
  357. instance=instance_index[(subname, type_)],
  358. validated_data=data_index[(subname, type_)]
  359. ))
  360. for subname, type_ in deleted:
  361. instance_index[(subname, type_)].delete()
  362. # time of check (does it exist?) and time of action (create vs update) are different,
  363. # so for parallel requests, we can get integrity errors due to duplicate keys.
  364. # This will be considered a 429-error, even though re-sending the request will be successful.
  365. except OperationalError as e:
  366. try:
  367. if e.args[0] == 1213:
  368. # 1213 is mysql for deadlock, other OperationalErrors are treated elsewhere or not treated at all
  369. raise ConcurrencyException from e
  370. except (AttributeError, KeyError):
  371. pass
  372. raise e
  373. except (IntegrityError, models.RRset.DoesNotExist) as e:
  374. raise ConcurrencyException from e
  375. return ret
  376. class DomainSerializer(serializers.ModelSerializer):
  377. class Meta:
  378. model = models.Domain
  379. fields = ('created', 'published', 'name', 'keys', 'minimum_ttl',)
  380. read_only_fields = ('published', 'minimum_ttl',)
  381. extra_kwargs = {
  382. 'name': {'trim_whitespace': False},
  383. }
  384. def __init__(self, *args, include_keys=False, **kwargs):
  385. self.include_keys = include_keys
  386. return super().__init__(*args, **kwargs)
  387. def get_fields(self):
  388. fields = super().get_fields()
  389. if not self.include_keys:
  390. fields.pop('keys')
  391. fields['name'].validators.append(ReadOnlyOnUpdateValidator())
  392. return fields
  393. def validate_name(self, value):
  394. self.raise_if_domain_unavailable(value, self.context['request'].user)
  395. return value
  396. @staticmethod
  397. def raise_if_domain_unavailable(domain_name: str, user: models.User):
  398. if not models.Domain.is_registrable(domain_name, user):
  399. raise serializers.ValidationError(
  400. 'This domain name is unavailable because it is already taken, or disallowed by policy.',
  401. code='name_unavailable'
  402. )
  403. def create(self, validated_data):
  404. if 'minimum_ttl' not in validated_data and models.Domain(name=validated_data['name']).is_locally_registrable:
  405. validated_data.update(minimum_ttl=60)
  406. return super().create(validated_data)
  407. class DonationSerializer(serializers.ModelSerializer):
  408. class Meta:
  409. model = models.Donation
  410. fields = ('name', 'iban', 'bic', 'amount', 'message', 'email', 'mref')
  411. read_only_fields = ('mref',)
  412. @staticmethod
  413. def validate_bic(value):
  414. return re.sub(r'[\s]', '', value)
  415. @staticmethod
  416. def validate_iban(value):
  417. return re.sub(r'[\s]', '', value)
  418. class UserSerializer(serializers.ModelSerializer):
  419. class Meta:
  420. model = models.User
  421. fields = ('created', 'email', 'id', 'limit_domains', 'password',)
  422. extra_kwargs = {
  423. 'password': {
  424. 'write_only': True, # Do not expose password field
  425. 'allow_null': True,
  426. }
  427. }
  428. def create(self, validated_data):
  429. return models.User.objects.create_user(**validated_data)
  430. class RegisterAccountSerializer(UserSerializer):
  431. domain = serializers.CharField(required=False, validators=models.validate_domain_name)
  432. captcha = CaptchaSolutionSerializer(required=True)
  433. class Meta:
  434. model = UserSerializer.Meta.model
  435. fields = ('email', 'password', 'domain', 'captcha')
  436. extra_kwargs = UserSerializer.Meta.extra_kwargs
  437. def validate_domain(self, value):
  438. DomainSerializer.raise_if_domain_unavailable(value, self.context['request'].user)
  439. return value
  440. def create(self, validated_data):
  441. validated_data.pop('domain', None)
  442. validated_data.pop('captcha', None)
  443. return super().create(validated_data)
  444. class EmailSerializer(serializers.Serializer):
  445. email = serializers.EmailField()
  446. class EmailPasswordSerializer(EmailSerializer):
  447. password = serializers.CharField()
  448. class ChangeEmailSerializer(serializers.Serializer):
  449. new_email = serializers.EmailField()
  450. def validate_new_email(self, value):
  451. if value == self.context['request'].user.email:
  452. raise serializers.ValidationError('Email address unchanged.')
  453. return value
  454. class ResetPasswordSerializer(EmailSerializer):
  455. captcha = CaptchaSolutionSerializer(required=True)
  456. class CustomFieldNameUniqueValidator(UniqueValidator):
  457. """
  458. Does exactly what rest_framework's UniqueValidator does, however allows to further customize the
  459. query that is used to determine the uniqueness.
  460. More specifically, we allow that the field name the value is queried against is passed when initializing
  461. this validator. (At the time of writing, UniqueValidator insists that the field's name is used for the
  462. database query field; only how the lookup must match is allowed to be changed.)
  463. """
  464. def __init__(self, queryset, message=None, lookup='exact', lookup_field=None):
  465. self.lookup_field = lookup_field
  466. super().__init__(queryset, message, lookup)
  467. def filter_queryset(self, value, queryset, field_name):
  468. """
  469. Filter the queryset to all instances matching the given value on the specified lookup field.
  470. """
  471. filter_kwargs = {'%s__%s' % (self.lookup_field or field_name, self.lookup): value}
  472. return qs_filter(queryset, **filter_kwargs)
  473. class AuthenticatedActionSerializer(serializers.ModelSerializer):
  474. state = serializers.CharField() # serializer read-write, but model read-only field
  475. class Meta:
  476. model = models.AuthenticatedAction
  477. fields = ('state',)
  478. @classmethod
  479. def _pack_code(cls, data):
  480. payload = json.dumps(data).encode()
  481. payload_enc = crypto.encrypt(payload, context='desecapi.serializers.AuthenticatedActionSerializer')
  482. return urlsafe_b64encode(payload_enc).decode()
  483. @classmethod
  484. def _unpack_code(cls, code):
  485. try:
  486. payload_enc = urlsafe_b64decode(code.encode())
  487. payload = crypto.decrypt(payload_enc, context='desecapi.serializers.AuthenticatedActionSerializer',
  488. ttl=settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE.total_seconds())
  489. return json.loads(payload.decode())
  490. except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
  491. raise ValueError
  492. def to_representation(self, instance: models.AuthenticatedUserAction):
  493. # do the regular business
  494. data = super().to_representation(instance)
  495. # encode into single string
  496. return {'code': self._pack_code(data)}
  497. def to_internal_value(self, data):
  498. data = data.copy() # avoid side effect from .pop
  499. try:
  500. # decode from single string
  501. unpacked_data = self._unpack_code(self.context['code'])
  502. except KeyError:
  503. raise serializers.ValidationError({'code': ['This field is required.']})
  504. except ValueError:
  505. raise serializers.ValidationError({'code': ['Invalid code.']})
  506. # add extra fields added by the user
  507. unpacked_data.update(**data)
  508. # do the regular business
  509. return super().to_internal_value(unpacked_data)
  510. def act(self):
  511. self.instance.act()
  512. return self.instance
  513. def save(self, **kwargs):
  514. raise ValueError
  515. class AuthenticatedUserActionSerializer(AuthenticatedActionSerializer):
  516. user = serializers.PrimaryKeyRelatedField(
  517. queryset=models.User.objects.all(),
  518. error_messages={'does_not_exist': 'This user does not exist.'},
  519. pk_field=serializers.UUIDField()
  520. )
  521. class Meta:
  522. model = models.AuthenticatedUserAction
  523. fields = AuthenticatedActionSerializer.Meta.fields + ('user',)
  524. class AuthenticatedActivateUserActionSerializer(AuthenticatedUserActionSerializer):
  525. class Meta(AuthenticatedUserActionSerializer.Meta):
  526. model = models.AuthenticatedActivateUserAction
  527. fields = AuthenticatedUserActionSerializer.Meta.fields + ('domain',)
  528. extra_kwargs = {
  529. 'domain': {'default': None, 'allow_null': True}
  530. }
  531. class AuthenticatedChangeEmailUserActionSerializer(AuthenticatedUserActionSerializer):
  532. new_email = serializers.EmailField(
  533. validators=[
  534. CustomFieldNameUniqueValidator(
  535. queryset=models.User.objects.all(),
  536. lookup_field='email',
  537. message='You already have another account with this email address.',
  538. )
  539. ],
  540. required=True,
  541. )
  542. class Meta(AuthenticatedUserActionSerializer.Meta):
  543. model = models.AuthenticatedChangeEmailUserAction
  544. fields = AuthenticatedUserActionSerializer.Meta.fields + ('new_email',)
  545. class AuthenticatedResetPasswordUserActionSerializer(AuthenticatedUserActionSerializer):
  546. new_password = serializers.CharField(write_only=True)
  547. class Meta(AuthenticatedUserActionSerializer.Meta):
  548. model = models.AuthenticatedResetPasswordUserAction
  549. fields = AuthenticatedUserActionSerializer.Meta.fields + ('new_password',)
  550. class AuthenticatedDeleteUserActionSerializer(AuthenticatedUserActionSerializer):
  551. class Meta(AuthenticatedUserActionSerializer.Meta):
  552. model = models.AuthenticatedDeleteUserAction