serializers.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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.exceptions import ValidationError
  10. from rest_framework.serializers import ListSerializer
  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 models
  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 StringField(serializers.CharField):
  80. def to_internal_value(self, data):
  81. return data
  82. def run_validation(self, data=serializers.empty):
  83. data = super().run_validation(data)
  84. if not isinstance(data, str):
  85. raise serializers.ValidationError('Must be a string.', code='must-be-a-string')
  86. return data
  87. class RRsField(serializers.ListField):
  88. def __init__(self, **kwargs):
  89. super().__init__(child=StringField(), **kwargs)
  90. def to_representation(self, data):
  91. return [rr.content for rr in data.all()]
  92. class ConditionalExistenceModelSerializer(serializers.ModelSerializer):
  93. """
  94. Only considers data with certain condition as existing data.
  95. If the existence condition does not hold, given instances are deleted, and no new instances are created,
  96. respectively. Also, to_representation and data will return None.
  97. Contrary, if the existence condition holds, the behavior is the same as DRF's ModelSerializer.
  98. """
  99. def exists(self, arg):
  100. """
  101. Determine if arg is to be considered existing.
  102. :param arg: Either a model instance or (possibly invalid!) data object.
  103. :return: Whether we treat this as non-existing instance.
  104. """
  105. raise NotImplementedError
  106. def to_representation(self, instance):
  107. return None if not self.exists(instance) else super().to_representation(instance)
  108. @property
  109. def data(self):
  110. try:
  111. return super().data
  112. except TypeError:
  113. return None
  114. def save(self, **kwargs):
  115. validated_data = {}
  116. validated_data.update(self.validated_data)
  117. validated_data.update(kwargs)
  118. known_instance = self.instance is not None
  119. data_exists = self.exists(validated_data)
  120. if known_instance and data_exists:
  121. self.instance = self.update(self.instance, validated_data)
  122. elif known_instance and not data_exists:
  123. self.delete()
  124. elif not known_instance and data_exists:
  125. self.instance = self.create(validated_data)
  126. elif not known_instance and not data_exists:
  127. pass # nothing to do
  128. return self.instance
  129. def delete(self):
  130. self.instance.delete()
  131. class NonBulkOnlyDefault:
  132. """
  133. This class may be used to provide default values that are only used
  134. for non-bulk operations, but that do not return any value for bulk
  135. operations.
  136. Implementation inspired by CreateOnlyDefault.
  137. """
  138. def __init__(self, default):
  139. self.default = default
  140. def set_context(self, serializer_field):
  141. # noinspection PyAttributeOutsideInit
  142. self.is_many = getattr(serializer_field.root, 'many', False)
  143. if callable(self.default) and hasattr(self.default, 'set_context') and not self.is_many:
  144. # noinspection PyUnresolvedReferences
  145. self.default.set_context(serializer_field)
  146. def __call__(self):
  147. if self.is_many:
  148. raise serializers.SkipField()
  149. if callable(self.default):
  150. return self.default()
  151. return self.default
  152. def __repr__(self):
  153. return '%s(%s)' % (self.__class__.__name__, repr(self.default))
  154. class RRsetSerializer(ConditionalExistenceModelSerializer):
  155. domain = serializers.SlugRelatedField(read_only=True, slug_field='name')
  156. records = RRsField(allow_empty=True)
  157. ttl = serializers.IntegerField(max_value=604800)
  158. class Meta:
  159. model = models.RRset
  160. fields = ('created', 'domain', 'subname', 'name', 'records', 'ttl', 'type',)
  161. extra_kwargs = {
  162. 'subname': {'required': False, 'default': NonBulkOnlyDefault('')}
  163. }
  164. def __init__(self, instance=None, data=serializers.empty, domain=None, **kwargs):
  165. if domain is None:
  166. raise ValueError('RRsetSerializer() must be given a domain object (to validate uniqueness constraints).')
  167. self.domain = domain
  168. super().__init__(instance, data, **kwargs)
  169. @classmethod
  170. def many_init(cls, *args, **kwargs):
  171. domain = kwargs.pop('domain')
  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(
  189. "The %s RRset type is currently unsupported." % value)
  190. if value in models.RRset.RESTRICTED_TYPES:
  191. raise serializers.ValidationError(
  192. "You cannot tinker with the %s RRset." % value)
  193. if value.startswith('TYPE'):
  194. raise serializers.ValidationError(
  195. "Generic type format is not supported.")
  196. return value
  197. def validate_records(self, value):
  198. # `records` is usually allowed to be empty (for idempotent delete), except for POST requests which are intended
  199. # for RRset creation only. We use the fact that DRF generic views pass the request in the serializer context.
  200. request = self.context.get('request')
  201. if request and request.method == 'POST' and not value:
  202. raise serializers.ValidationError('This field must not be empty when using POST.')
  203. return value
  204. def exists(self, arg):
  205. if isinstance(arg, models.RRset):
  206. return arg.records.exists()
  207. else:
  208. return bool(arg.get('records')) if 'records' in arg.keys() else True
  209. def create(self, validated_data):
  210. rrs_data = validated_data.pop('records')
  211. rrset = models.RRset.objects.create(**validated_data)
  212. self._set_all_record_contents(rrset, rrs_data)
  213. return rrset
  214. def update(self, instance: models.RRset, validated_data):
  215. rrs_data = validated_data.pop('records', None)
  216. if rrs_data is not None:
  217. self._set_all_record_contents(instance, rrs_data)
  218. ttl = validated_data.pop('ttl', None)
  219. if ttl and instance.ttl != ttl:
  220. instance.ttl = ttl
  221. instance.save()
  222. return instance
  223. @staticmethod
  224. def _set_all_record_contents(rrset: models.RRset, record_contents):
  225. """
  226. Updates this RR set's resource records, discarding any old values.
  227. To do so, two large select queries and one query per changed (added or removed) resource record are needed.
  228. Changes are saved to the database immediately.
  229. :param rrset: the RRset at which we overwrite all RRs
  230. :param record_contents: set of strings
  231. """
  232. # Remove RRs that we didn't see in the new list
  233. removed_rrs = rrset.records.exclude(content__in=record_contents) # one SELECT
  234. for rr in removed_rrs:
  235. rr.delete() # one DELETE query
  236. # Figure out which entries in record_contents have not changed
  237. unchanged_rrs = rrset.records.filter(content__in=record_contents) # one SELECT
  238. unchanged_content = [unchanged_rr.content for unchanged_rr in unchanged_rrs]
  239. added_content = filter(lambda c: c not in unchanged_content, record_contents)
  240. rrs = [models.RR(rrset=rrset, content=content) for content in added_content]
  241. models.RR.objects.bulk_create(rrs) # One INSERT
  242. class RRsetListSerializer(ListSerializer):
  243. default_error_messages = {
  244. **serializers.Serializer.default_error_messages,
  245. **ListSerializer.default_error_messages,
  246. **{'not_a_list': 'Expected a list of items but got {input_type}.'},
  247. }
  248. @staticmethod
  249. def _key(data_item):
  250. return data_item.get('subname', None), data_item.get('type', None)
  251. def to_internal_value(self, data):
  252. if not isinstance(data, list):
  253. message = self.error_messages['not_a_list'].format(input_type=type(data).__name__)
  254. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='not_a_list')
  255. if not self.allow_empty and len(data) == 0:
  256. if self.parent and self.partial:
  257. raise serializers.SkipField()
  258. else:
  259. self.fail('empty')
  260. ret = []
  261. errors = []
  262. partial = self.partial
  263. # build look-up objects for instances and data, so we can look them up with their keys
  264. try:
  265. known_instances = {(x.subname, x.type): x for x in self.instance}
  266. except TypeError: # in case self.instance is None (as during POST)
  267. known_instances = {}
  268. indices_by_key = {}
  269. for idx, item in enumerate(data):
  270. # Validate item type before using anything from it
  271. if not isinstance(item, dict):
  272. self.fail('invalid', datatype=type(item).__name__)
  273. items = indices_by_key.setdefault(self._key(item), set())
  274. items.add(idx)
  275. # Iterate over all rows in the data given
  276. for idx, item in enumerate(data):
  277. try:
  278. # see if other rows have the same key
  279. if len(indices_by_key[self._key(item)]) > 1:
  280. raise serializers.ValidationError({
  281. 'non_field_errors': [
  282. 'Same subname and type as in position(s) %s, but must be unique.' %
  283. ', '.join(map(str, indices_by_key[self._key(item)] - {idx}))
  284. ]
  285. })
  286. # determine if this is a partial update (i.e. PATCH):
  287. # we allow partial update if a partial update method (i.e. PATCH) is used, as indicated by self.partial,
  288. # and if this is not actually a create request because it is unknown and nonempty
  289. unknown = self._key(item) not in known_instances.keys()
  290. nonempty = item.get('records', None) != []
  291. self.partial = partial and not (unknown and nonempty)
  292. self.child.instance = known_instances.get(self._key(item), None)
  293. # with partial value and instance in place, let the validation begin!
  294. validated = self.child.run_validation(item)
  295. except serializers.ValidationError as exc:
  296. errors.append(exc.detail)
  297. else:
  298. ret.append(validated)
  299. errors.append({})
  300. self.partial = partial
  301. if any(errors):
  302. raise serializers.ValidationError(errors)
  303. return ret
  304. def update(self, instance, validated_data):
  305. """
  306. Creates, updates and deletes RRsets according to the validated_data given. Relevant instances must be passed as
  307. a queryset in the `instance` argument.
  308. RRsets that appear in `instance` are considered "known", other RRsets are considered "unknown". RRsets that
  309. appear in `validated_data` with records == [] are considered empty, otherwise non-empty.
  310. The update proceeds as follows:
  311. 1. All unknown, non-empty RRsets are created.
  312. 2. All known, non-empty RRsets are updated.
  313. 3. All known, empty RRsets are deleted.
  314. 4. Unknown, empty RRsets will not cause any action.
  315. Rationale:
  316. As both "known"/"unknown" and "empty"/"non-empty" are binary partitions on `everything`, the combination of
  317. both partitions `everything` in four disjoint subsets. Hence, every RRset in `everything` is taken care of.
  318. empty | non-empty
  319. ------- | -------- | -----------
  320. known | delete | update
  321. unknown | no-op | create
  322. :param instance: QuerySet of relevant RRset objects, i.e. the Django.Model subclass instances. Relevant are all
  323. instances that are referenced in `validated_data`. If a referenced RRset is missing from instances, it will be
  324. considered unknown and hence be created. This may cause a database integrity error. If an RRset is given, but
  325. not relevant (i.e. not referred to by `validated_data`), a ValueError will be raised.
  326. :param validated_data: List of RRset data objects, i.e. dictionaries.
  327. :return: List of RRset objects (Django.Model subclass) that have been created or updated.
  328. """
  329. def is_empty(data_item):
  330. return data_item.get('records', None) == []
  331. query = Q()
  332. for item in validated_data:
  333. query |= Q(type=item['type'], subname=item['subname']) # validation has ensured these fields exist
  334. instance = instance.filter(query)
  335. instance_index = {(rrset.subname, rrset.type): rrset for rrset in instance}
  336. data_index = {self._key(data): data for data in validated_data}
  337. if data_index.keys() | instance_index.keys() != data_index.keys():
  338. raise ValueError('Given set of known RRsets (`instance`) is not a subset of RRsets referred to in'
  339. '`validated_data`. While this would produce a correct result, this is illegal due to its'
  340. ' inefficiency.')
  341. everything = instance_index.keys() | data_index.keys()
  342. known = instance_index.keys()
  343. unknown = everything - known
  344. # noinspection PyShadowingNames
  345. empty = {self._key(data) for data in validated_data if is_empty(data)}
  346. nonempty = everything - empty
  347. # noinspection PyUnusedLocal
  348. noop = unknown & empty
  349. created = unknown & nonempty
  350. updated = known & nonempty
  351. deleted = known & empty
  352. ret = []
  353. for subname, type_ in created:
  354. ret.append(self.child.create(
  355. validated_data=data_index[(subname, type_)]
  356. ))
  357. for subname, type_ in updated:
  358. ret.append(self.child.update(
  359. instance=instance_index[(subname, type_)],
  360. validated_data=data_index[(subname, type_)]
  361. ))
  362. for subname, type_ in deleted:
  363. instance_index[(subname, type_)].delete()
  364. return ret
  365. class DomainSerializer(serializers.ModelSerializer):
  366. class Meta:
  367. model = models.Domain
  368. fields = ('created', 'published', 'name', 'keys', 'minimum_ttl',)
  369. extra_kwargs = {
  370. 'name': {'trim_whitespace': False},
  371. 'published': {'read_only': True},
  372. 'minimum_ttl': {'read_only': True},
  373. }
  374. def get_fields(self):
  375. fields = super().get_fields()
  376. fields['name'].validators.append(ReadOnlyOnUpdateValidator())
  377. return fields
  378. def validate_name(self, value):
  379. self.raise_if_domain_unavailable(value, self.context['request'].user)
  380. return value
  381. @staticmethod
  382. def raise_if_domain_unavailable(domain_name: str, user: models.User):
  383. if not models.Domain.is_registrable(domain_name, user):
  384. raise serializers.ValidationError('This domain name is unavailable.', code='name_unavailable')
  385. def create(self, validated_data):
  386. if 'minimum_ttl' not in validated_data and models.Domain(name=validated_data['name']).is_locally_registrable:
  387. validated_data.update(minimum_ttl=60)
  388. return super().create(validated_data)
  389. class DonationSerializer(serializers.ModelSerializer):
  390. class Meta:
  391. model = models.Donation
  392. fields = ('name', 'iban', 'bic', 'amount', 'message', 'email')
  393. @staticmethod
  394. def validate_bic(value):
  395. return re.sub(r'[\s]', '', value)
  396. @staticmethod
  397. def validate_iban(value):
  398. return re.sub(r'[\s]', '', value)
  399. class UserSerializer(serializers.ModelSerializer):
  400. class Meta:
  401. model = models.User
  402. fields = ('created', 'email', 'id', 'limit_domains', 'password',)
  403. extra_kwargs = {
  404. 'password': {
  405. 'write_only': True, # Do not expose password field
  406. 'allow_null': True,
  407. }
  408. }
  409. def create(self, validated_data):
  410. return models.User.objects.create_user(**validated_data)
  411. class RegisterAccountSerializer(UserSerializer):
  412. domain = serializers.CharField(required=False, validators=models.validate_domain_name)
  413. captcha = CaptchaSolutionSerializer(required=True)
  414. class Meta:
  415. model = UserSerializer.Meta.model
  416. fields = ('email', 'password', 'domain', 'captcha')
  417. extra_kwargs = UserSerializer.Meta.extra_kwargs
  418. def validate_domain(self, value):
  419. DomainSerializer.raise_if_domain_unavailable(value, self.context['request'].user)
  420. return value
  421. def create(self, validated_data):
  422. validated_data.pop('domain', None)
  423. validated_data.pop('captcha', None)
  424. return super().create(validated_data)
  425. class EmailSerializer(serializers.Serializer):
  426. email = serializers.EmailField()
  427. class EmailPasswordSerializer(EmailSerializer):
  428. password = serializers.CharField()
  429. class ChangeEmailSerializer(serializers.Serializer):
  430. new_email = serializers.EmailField()
  431. def validate_new_email(self, value):
  432. if value == self.context['request'].user.email:
  433. raise serializers.ValidationError('Email address unchanged.')
  434. return value
  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):
  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 self.field_name, self.lookup): value}
  451. return qs_filter(queryset, **filter_kwargs)
  452. class AuthenticatedActionSerializer(serializers.ModelSerializer):
  453. mac = serializers.CharField() # serializer read-write, but model read-only field
  454. class Meta:
  455. model = models.AuthenticatedAction
  456. fields = ('mac', 'created')
  457. @classmethod
  458. def _pack_code(cls, unpacked_data):
  459. return urlsafe_b64encode(json.dumps(unpacked_data).encode()).decode()
  460. @classmethod
  461. def _unpack_code(cls, packed_data):
  462. try:
  463. return json.loads(urlsafe_b64decode(packed_data.encode()).decode())
  464. except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
  465. raise ValueError
  466. def to_representation(self, instance: models.AuthenticatedUserAction):
  467. # do the regular business
  468. data = super().to_representation(instance)
  469. # encode into single string
  470. return {'code': self._pack_code(data)}
  471. def to_internal_value(self, data):
  472. data = data.copy() # avoid side effect from .pop
  473. try:
  474. # decode from single string
  475. unpacked_data = self._unpack_code(data.pop('code'))
  476. except KeyError:
  477. raise ValidationError({'code': ['No verification code.']})
  478. except ValueError:
  479. raise ValidationError({'code': ['Invalid verification code.']})
  480. # add extra fields added by the user
  481. unpacked_data.update(**data)
  482. # do the regular business
  483. return super().to_internal_value(unpacked_data)
  484. def validate(self, attrs):
  485. if not self.instance:
  486. self.instance = self.Meta.model(**attrs) # TODO This creates an attribute on self. Side-effect intended?
  487. # check if expired
  488. if self.instance.is_expired():
  489. raise ValidationError(detail='Code expired, please restart the process.', code='expired')
  490. # check if MAC valid
  491. if not self.instance.validate_mac(attrs['mac']):
  492. raise ValidationError(detail='Bad signature.', code='bad_sig')
  493. return attrs
  494. def act(self):
  495. self.instance.act()
  496. return self.instance
  497. def save(self, **kwargs):
  498. raise ValueError
  499. class AuthenticatedUserActionSerializer(AuthenticatedActionSerializer):
  500. user = serializers.PrimaryKeyRelatedField(
  501. queryset=models.User.objects.all(),
  502. error_messages={'does_not_exist': 'This user does not exist.'}
  503. )
  504. class Meta:
  505. model = models.AuthenticatedUserAction
  506. fields = AuthenticatedActionSerializer.Meta.fields + ('user',)
  507. class AuthenticatedActivateUserActionSerializer(AuthenticatedUserActionSerializer):
  508. class Meta(AuthenticatedUserActionSerializer.Meta):
  509. model = models.AuthenticatedActivateUserAction
  510. fields = AuthenticatedUserActionSerializer.Meta.fields + ('domain',)
  511. extra_kwargs = {
  512. 'domain': {'default': None, 'allow_null': True}
  513. }
  514. class AuthenticatedChangeEmailUserActionSerializer(AuthenticatedUserActionSerializer):
  515. new_email = serializers.EmailField(
  516. validators=[
  517. CustomFieldNameUniqueValidator(
  518. queryset=models.User.objects.all(),
  519. lookup_field='email',
  520. message='You already have another account with this email address.',
  521. )
  522. ],
  523. required=True,
  524. )
  525. class Meta(AuthenticatedUserActionSerializer.Meta):
  526. model = models.AuthenticatedChangeEmailUserAction
  527. fields = AuthenticatedUserActionSerializer.Meta.fields + ('new_email',)
  528. class AuthenticatedResetPasswordUserActionSerializer(AuthenticatedUserActionSerializer):
  529. new_password = serializers.CharField(write_only=True)
  530. class Meta(AuthenticatedUserActionSerializer.Meta):
  531. model = models.AuthenticatedResetPasswordUserAction
  532. fields = AuthenticatedUserActionSerializer.Meta.fields + ('new_password',)
  533. class AuthenticatedDeleteUserActionSerializer(AuthenticatedUserActionSerializer):
  534. class Meta(AuthenticatedUserActionSerializer.Meta):
  535. model = models.AuthenticatedDeleteUserAction