serializers.py 26 KB

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