serializers.py 33 KB

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