serializers.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import binascii
  2. import json
  3. import re
  4. from base64 import urlsafe_b64decode, urlsafe_b64encode
  5. import psl_dns
  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 TokenSerializer(serializers.ModelSerializer):
  16. auth_token = serializers.ReadOnlyField(source='key')
  17. # note this overrides the original "id" field, which is the db primary key
  18. id = serializers.ReadOnlyField(source='user_specific_id')
  19. class Meta:
  20. model = models.Token
  21. fields = ('id', 'created', 'name', 'auth_token',)
  22. read_only_fields = ('created', 'auth_token', 'id')
  23. class RequiredOnPartialUpdateCharField(serializers.CharField):
  24. """
  25. This field is always required, even for partial updates (e.g. using PATCH).
  26. """
  27. def validate_empty_values(self, data):
  28. if data is serializers.empty:
  29. self.fail('required')
  30. return super().validate_empty_values(data)
  31. class Validator:
  32. message = 'This field did not pass validation.'
  33. def __init__(self, message=None):
  34. self.field_name = None
  35. self.message = message or self.message
  36. self.instance = None
  37. def __call__(self, value):
  38. raise NotImplementedError
  39. def __repr__(self):
  40. return '<%s>' % self.__class__.__name__
  41. class ReadOnlyOnUpdateValidator(Validator):
  42. message = 'Can only be written on create.'
  43. def set_context(self, serializer_field):
  44. """
  45. This hook is called by the serializer instance,
  46. prior to the validation call being made.
  47. """
  48. self.field_name = serializer_field.source_attrs[-1]
  49. self.instance = getattr(serializer_field.parent, 'instance', None)
  50. def __call__(self, value):
  51. if isinstance(self.instance, Model) and value != getattr(self.instance, self.field_name):
  52. raise serializers.ValidationError(self.message, code='read-only-on-update')
  53. class StringField(serializers.CharField):
  54. def to_internal_value(self, data):
  55. return data
  56. def run_validation(self, data=serializers.empty):
  57. data = super().run_validation(data)
  58. if not isinstance(data, str):
  59. raise serializers.ValidationError('Must be a string.', code='must-be-a-string')
  60. return data
  61. class RRsField(serializers.ListField):
  62. def __init__(self, **kwargs):
  63. super().__init__(child=StringField(), **kwargs)
  64. def to_representation(self, data):
  65. return [rr.content for rr in data.all()]
  66. class ConditionalExistenceModelSerializer(serializers.ModelSerializer):
  67. """
  68. Only considers data with certain condition as existing data.
  69. If the existence condition does not hold, given instances are deleted, and no new instances are created,
  70. respectively. Also, to_representation and data will return None.
  71. Contrary, if the existence condition holds, the behavior is the same as DRF's ModelSerializer.
  72. """
  73. def exists(self, arg):
  74. """
  75. Determine if arg is to be considered existing.
  76. :param arg: Either a model instance or (possibly invalid!) data object.
  77. :return: Whether we treat this as non-existing instance.
  78. """
  79. raise NotImplementedError
  80. def to_representation(self, instance):
  81. return None if not self.exists(instance) else super().to_representation(instance)
  82. @property
  83. def data(self):
  84. try:
  85. return super().data
  86. except TypeError:
  87. return None
  88. def save(self, **kwargs):
  89. validated_data = {}
  90. validated_data.update(self.validated_data)
  91. validated_data.update(kwargs)
  92. known_instance = self.instance is not None
  93. data_exists = self.exists(validated_data)
  94. if known_instance and data_exists:
  95. self.instance = self.update(self.instance, validated_data)
  96. elif known_instance and not data_exists:
  97. self.delete()
  98. elif not known_instance and data_exists:
  99. self.instance = self.create(validated_data)
  100. elif not known_instance and not data_exists:
  101. pass # nothing to do
  102. return self.instance
  103. def delete(self):
  104. self.instance.delete()
  105. class NonBulkOnlyDefault:
  106. """
  107. This class may be used to provide default values that are only used
  108. for non-bulk operations, but that do not return any value for bulk
  109. operations.
  110. Implementation inspired by CreateOnlyDefault.
  111. """
  112. def __init__(self, default):
  113. self.default = default
  114. def set_context(self, serializer_field):
  115. # noinspection PyAttributeOutsideInit
  116. self.is_many = getattr(serializer_field.root, 'many', False)
  117. if callable(self.default) and hasattr(self.default, 'set_context') and not self.is_many:
  118. # noinspection PyUnresolvedReferences
  119. self.default.set_context(serializer_field)
  120. def __call__(self):
  121. if self.is_many:
  122. raise serializers.SkipField()
  123. if callable(self.default):
  124. return self.default()
  125. return self.default
  126. def __repr__(self):
  127. return '%s(%s)' % (self.__class__.__name__, repr(self.default))
  128. class RRsetSerializer(ConditionalExistenceModelSerializer):
  129. domain = serializers.SlugRelatedField(read_only=True, slug_field='name')
  130. records = RRsField(allow_empty=True)
  131. ttl = serializers.IntegerField(max_value=604800)
  132. class Meta:
  133. model = models.RRset
  134. fields = ('domain', 'subname', 'name', 'records', 'ttl', 'type',)
  135. extra_kwargs = {
  136. 'subname': {'required': False, 'default': NonBulkOnlyDefault('')}
  137. }
  138. def __init__(self, instance=None, data=serializers.empty, domain=None, **kwargs):
  139. if domain is None:
  140. raise ValueError('RRsetSerializer() must be given a domain object (to validate uniqueness constraints).')
  141. self.domain = domain
  142. super().__init__(instance, data, **kwargs)
  143. @classmethod
  144. def many_init(cls, *args, **kwargs):
  145. domain = kwargs.pop('domain')
  146. kwargs['child'] = cls(domain=domain)
  147. return RRsetListSerializer(*args, **kwargs)
  148. def get_fields(self):
  149. fields = super().get_fields()
  150. fields['subname'].validators.append(ReadOnlyOnUpdateValidator())
  151. fields['type'].validators.append(ReadOnlyOnUpdateValidator())
  152. fields['ttl'].validators.append(MinValueValidator(limit_value=self.domain.minimum_ttl))
  153. return fields
  154. def get_validators(self):
  155. return [UniqueTogetherValidator(
  156. self.domain.rrset_set, ('subname', 'type'),
  157. message='Another RRset with the same subdomain and type exists for this domain.'
  158. )]
  159. @staticmethod
  160. def validate_type(value):
  161. if value in models.RRset.DEAD_TYPES:
  162. raise serializers.ValidationError(
  163. "The %s RRset type is currently unsupported." % value)
  164. if value in models.RRset.RESTRICTED_TYPES:
  165. raise serializers.ValidationError(
  166. "You cannot tinker with the %s RRset." % value)
  167. if value.startswith('TYPE'):
  168. raise serializers.ValidationError(
  169. "Generic type format is not supported.")
  170. return value
  171. def validate_records(self, value):
  172. # `records` is usually allowed to be empty (for idempotent delete), except for POST requests which are intended
  173. # for RRset creation only. We use the fact that DRF generic views pass the request in the serializer context.
  174. request = self.context.get('request')
  175. if request and request.method == 'POST' and not value:
  176. raise serializers.ValidationError('This field must not be empty when using POST.')
  177. return value
  178. def exists(self, arg):
  179. if isinstance(arg, models.RRset):
  180. return arg.records.exists()
  181. else:
  182. return bool(arg.get('records')) if 'records' in arg.keys() else True
  183. def create(self, validated_data):
  184. rrs_data = validated_data.pop('records')
  185. rrset = models.RRset.objects.create(**validated_data)
  186. self._set_all_record_contents(rrset, rrs_data)
  187. return rrset
  188. def update(self, instance: models.RRset, validated_data):
  189. rrs_data = validated_data.pop('records', None)
  190. if rrs_data is not None:
  191. self._set_all_record_contents(instance, rrs_data)
  192. ttl = validated_data.pop('ttl', None)
  193. if ttl and instance.ttl != ttl:
  194. instance.ttl = ttl
  195. instance.save()
  196. return instance
  197. @staticmethod
  198. def _set_all_record_contents(rrset: models.RRset, record_contents):
  199. """
  200. Updates this RR set's resource records, discarding any old values.
  201. To do so, two large select queries and one query per changed (added or removed) resource record are needed.
  202. Changes are saved to the database immediately.
  203. :param rrset: the RRset at which we overwrite all RRs
  204. :param record_contents: set of strings
  205. """
  206. # Remove RRs that we didn't see in the new list
  207. removed_rrs = rrset.records.exclude(content__in=record_contents) # one SELECT
  208. for rr in removed_rrs:
  209. rr.delete() # one DELETE query
  210. # Figure out which entries in record_contents have not changed
  211. unchanged_rrs = rrset.records.filter(content__in=record_contents) # one SELECT
  212. unchanged_content = [unchanged_rr.content for unchanged_rr in unchanged_rrs]
  213. added_content = filter(lambda c: c not in unchanged_content, record_contents)
  214. rrs = [models.RR(rrset=rrset, content=content) for content in added_content]
  215. models.RR.objects.bulk_create(rrs) # One INSERT
  216. class RRsetListSerializer(ListSerializer):
  217. default_error_messages = {
  218. **serializers.Serializer.default_error_messages,
  219. **ListSerializer.default_error_messages,
  220. **{'not_a_list': 'Expected a list of items but got {input_type}.'},
  221. }
  222. @staticmethod
  223. def _key(data_item):
  224. return data_item.get('subname', None), data_item.get('type', None)
  225. def to_internal_value(self, data):
  226. if not isinstance(data, list):
  227. message = self.error_messages['not_a_list'].format(input_type=type(data).__name__)
  228. raise serializers.ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='not_a_list')
  229. if not self.allow_empty and len(data) == 0:
  230. if self.parent and self.partial:
  231. raise serializers.SkipField()
  232. else:
  233. self.fail('empty')
  234. ret = []
  235. errors = []
  236. partial = self.partial
  237. # build look-up objects for instances and data, so we can look them up with their keys
  238. try:
  239. known_instances = {(x.subname, x.type): x for x in self.instance}
  240. except TypeError: # in case self.instance is None (as during POST)
  241. known_instances = {}
  242. indices_by_key = {}
  243. for idx, item in enumerate(data):
  244. # Validate item type before using anything from it
  245. if not isinstance(item, dict):
  246. self.fail('invalid', datatype=type(item).__name__)
  247. items = indices_by_key.setdefault(self._key(item), set())
  248. items.add(idx)
  249. # Iterate over all rows in the data given
  250. for idx, item in enumerate(data):
  251. try:
  252. # see if other rows have the same key
  253. if len(indices_by_key[self._key(item)]) > 1:
  254. raise serializers.ValidationError({
  255. '__all__': [
  256. 'Same subname and type as in position(s) %s, but must be unique.' %
  257. ', '.join(map(str, indices_by_key[self._key(item)] - {idx}))
  258. ]
  259. })
  260. # determine if this is a partial update (i.e. PATCH):
  261. # we allow partial update if a partial update method (i.e. PATCH) is used, as indicated by self.partial,
  262. # and if this is not actually a create request because it is unknown and nonempty
  263. unknown = self._key(item) not in known_instances.keys()
  264. nonempty = item.get('records', None) != []
  265. self.partial = partial and not (unknown and nonempty)
  266. self.child.instance = known_instances.get(self._key(item), None)
  267. # with partial value and instance in place, let the validation begin!
  268. validated = self.child.run_validation(item)
  269. except serializers.ValidationError as exc:
  270. errors.append(exc.detail)
  271. else:
  272. ret.append(validated)
  273. errors.append({})
  274. self.partial = partial
  275. if any(errors):
  276. raise serializers.ValidationError(errors)
  277. return ret
  278. def update(self, instance, validated_data):
  279. """
  280. Creates, updates and deletes RRsets according to the validated_data given. Relevant instances must be passed as
  281. a queryset in the `instance` argument.
  282. RRsets that appear in `instance` are considered "known", other RRsets are considered "unknown". RRsets that
  283. appear in `validated_data` with records == [] are considered empty, otherwise non-empty.
  284. The update proceeds as follows:
  285. 1. All unknown, non-empty RRsets are created.
  286. 2. All known, non-empty RRsets are updated.
  287. 3. All known, empty RRsets are deleted.
  288. 4. Unknown, empty RRsets will not cause any action.
  289. Rationale:
  290. As both "known"/"unknown" and "empty"/"non-empty" are binary partitions on `everything`, the combination of
  291. both partitions `everything` in four disjoint subsets. Hence, every RRset in `everything` is taken care of.
  292. empty | non-empty
  293. ------- | -------- | -----------
  294. known | delete | update
  295. unknown | no-op | create
  296. :param instance: QuerySet of relevant RRset objects, i.e. the Django.Model subclass instances. Relevant are all
  297. instances that are referenced in `validated_data`. If a referenced RRset is missing from instances, it will be
  298. considered unknown and hence be created. This may cause a database integrity error. If an RRset is given, but
  299. not relevant (i.e. not referred to by `validated_data`), a ValueError will be raised.
  300. :param validated_data: List of RRset data objects, i.e. dictionaries.
  301. :return: List of RRset objects (Django.Model subclass) that have been created or updated.
  302. """
  303. def is_empty(data_item):
  304. return data_item.get('records', None) == []
  305. query = Q()
  306. for item in validated_data:
  307. query |= Q(type=item['type'], subname=item['subname']) # validation has ensured these fields exist
  308. instance = instance.filter(query)
  309. instance_index = {(rrset.subname, rrset.type): rrset for rrset in instance}
  310. data_index = {self._key(data): data for data in validated_data}
  311. if data_index.keys() | instance_index.keys() != data_index.keys():
  312. raise ValueError('Given set of known RRsets (`instance`) is not a subset of RRsets referred to in'
  313. '`validated_data`. While this would produce a correct result, this is illegal due to its'
  314. ' inefficiency.')
  315. everything = instance_index.keys() | data_index.keys()
  316. known = instance_index.keys()
  317. unknown = everything - known
  318. # noinspection PyShadowingNames
  319. empty = {self._key(data) for data in validated_data if is_empty(data)}
  320. nonempty = everything - empty
  321. # noinspection PyUnusedLocal
  322. noop = unknown & empty
  323. created = unknown & nonempty
  324. updated = known & nonempty
  325. deleted = known & empty
  326. ret = []
  327. for subname, type_ in created:
  328. ret.append(self.child.create(
  329. validated_data=data_index[(subname, type_)]
  330. ))
  331. for subname, type_ in updated:
  332. ret.append(self.child.update(
  333. instance=instance_index[(subname, type_)],
  334. validated_data=data_index[(subname, type_)]
  335. ))
  336. for subname, type_ in deleted:
  337. instance_index[(subname, type_)].delete()
  338. return ret
  339. class DomainSerializer(serializers.ModelSerializer):
  340. psl = psl_dns.PSL(resolver=settings.PSL_RESOLVER)
  341. class Meta:
  342. model = models.Domain
  343. fields = ('created', 'published', 'name', 'keys', 'minimum_ttl',)
  344. extra_kwargs = {
  345. 'name': {'trim_whitespace': False},
  346. 'published': {'read_only': True},
  347. 'minimum_ttl': {'read_only': True},
  348. }
  349. def get_fields(self):
  350. fields = super().get_fields()
  351. fields['name'].validators.append(ReadOnlyOnUpdateValidator())
  352. return fields
  353. def validate_name(self, value):
  354. # Check if domain is a public suffix
  355. try:
  356. public_suffix = self.psl.get_public_suffix(value)
  357. is_public_suffix = self.psl.is_public_suffix(value)
  358. except psl_dns.exceptions.UnsupportedRule as e:
  359. # It would probably be fine to just create the domain (with the TLD acting as the
  360. # public suffix and setting both public_suffix and is_public_suffix accordingly).
  361. # However, in order to allow to investigate the situation, it's better not catch
  362. # this exception. Our error handler turns it into a 503 error and makes sure
  363. # admins are notified.
  364. raise e
  365. is_restricted_suffix = is_public_suffix and value not in settings.LOCAL_PUBLIC_SUFFIXES
  366. # Generate a list of all domains connecting this one and its public suffix.
  367. # If another user owns a zone with one of these names, then the requested
  368. # domain is unavailable because it is part of the other user's zone.
  369. private_components = value.rsplit(public_suffix, 1)[0].rstrip('.')
  370. private_components = private_components.split('.') if private_components else []
  371. private_components += [public_suffix]
  372. private_domains = ['.'.join(private_components[i:]) for i in range(0, len(private_components) - 1)]
  373. assert is_public_suffix or value == private_domains[0]
  374. # Deny registration for non-local public suffixes and for domains covered by other users' zones
  375. owner = self.context['request'].user
  376. queryset = models.Domain.objects.filter(Q(name__in=private_domains) & ~Q(owner=owner))
  377. if is_restricted_suffix or queryset.exists():
  378. msg = 'This domain name is unavailable.'
  379. raise serializers.ValidationError(msg, code='name_unavailable')
  380. return value
  381. def validate(self, attrs): # TODO I believe this should be a permission, not a validation
  382. # Check user's domain limit
  383. owner = self.context['request'].user
  384. if (owner.limit_domains is not None and
  385. owner.domains.count() >= owner.limit_domains):
  386. msg = 'You reached the maximum number of domains allowed for your account.'
  387. raise serializers.ValidationError(msg, code='domain_limit')
  388. return attrs
  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. }
  407. }
  408. def create(self, validated_data):
  409. return models.User.objects.create_user(**validated_data)
  410. class RegisterAccountSerializer(UserSerializer):
  411. domain = serializers.CharField(required=False) # TODO Needs more validation
  412. class Meta:
  413. model = UserSerializer.Meta.model
  414. fields = ('email', 'password', 'domain')
  415. extra_kwargs = UserSerializer.Meta.extra_kwargs
  416. def create(self, validated_data):
  417. validated_data.pop('domain', None)
  418. return super().create(validated_data)
  419. class EmailSerializer(serializers.Serializer):
  420. email = serializers.EmailField()
  421. class EmailPasswordSerializer(EmailSerializer):
  422. password = serializers.CharField()
  423. class ChangeEmailSerializer(serializers.Serializer):
  424. new_email = serializers.EmailField()
  425. def validate_new_email(self, value):
  426. if value == self.context['request'].user.email:
  427. raise serializers.ValidationError('Email address unchanged.')
  428. return value
  429. class CustomFieldNameUniqueValidator(UniqueValidator):
  430. """
  431. Does exactly what rest_framework's UniqueValidator does, however allows to further customize the
  432. query that is used to determine the uniqueness.
  433. More specifically, we allow that the field name the value is queried against is passed when initializing
  434. this validator. (At the time of writing, UniqueValidator insists that the field's name is used for the
  435. database query field; only how the lookup must match is allowed to be changed.)
  436. """
  437. def __init__(self, queryset, message=None, lookup='exact', lookup_field=None):
  438. self.lookup_field = lookup_field
  439. super().__init__(queryset, message, lookup)
  440. def filter_queryset(self, value, queryset):
  441. """
  442. Filter the queryset to all instances matching the given value on the specified lookup field.
  443. """
  444. filter_kwargs = {'%s__%s' % (self.lookup_field or self.field_name, self.lookup): value}
  445. return qs_filter(queryset, **filter_kwargs)
  446. class AuthenticatedActionSerializer(serializers.ModelSerializer):
  447. mac = serializers.CharField() # serializer read-write, but model read-only field
  448. class Meta:
  449. model = models.AuthenticatedAction
  450. fields = ('mac', 'created')
  451. @classmethod
  452. def _pack_code(cls, unpacked_data):
  453. return urlsafe_b64encode(json.dumps(unpacked_data).encode()).decode()
  454. @classmethod
  455. def _unpack_code(cls, packed_data):
  456. try:
  457. return json.loads(urlsafe_b64decode(packed_data.encode()).decode())
  458. except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
  459. raise ValueError
  460. def to_representation(self, instance: models.AuthenticatedUserAction):
  461. # do the regular business
  462. data = super().to_representation(instance)
  463. # encode into single string
  464. return {'code': self._pack_code(data)}
  465. def to_internal_value(self, data):
  466. data = data.copy() # avoid side effect from .pop
  467. try:
  468. # decode from single string
  469. unpacked_data = self._unpack_code(data.pop('code'))
  470. except KeyError:
  471. raise ValidationError({'code': ['No verification code.']})
  472. except ValueError:
  473. raise ValidationError({'code': ['Invalid verification code.']})
  474. # add extra fields added by the user
  475. unpacked_data.update(**data)
  476. # do the regular business
  477. return super().to_internal_value(unpacked_data)
  478. def validate(self, attrs):
  479. if not self.instance:
  480. self.instance = self.Meta.model(**attrs) # TODO This creates an attribute on self. Side-effect intended?
  481. # check if expired
  482. expired = not self.instance.check_expiration(settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE)
  483. if expired:
  484. raise ValidationError(detail='Code expired, please restart the process.', code='expired')
  485. # check if MAC valid
  486. mac_valid = self.instance.check_mac(attrs['mac'])
  487. if not mac_valid:
  488. raise ValidationError(detail='Bad signature.', code='bad_sig')
  489. return attrs
  490. def act(self):
  491. self.instance.act()
  492. return self.instance
  493. def save(self, **kwargs):
  494. raise ValueError
  495. class AuthenticatedUserActionSerializer(AuthenticatedActionSerializer):
  496. user = serializers.PrimaryKeyRelatedField(
  497. queryset=models.User.objects.all(),
  498. error_messages={'does_not_exist': 'This user does not exist.'}
  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