serializers.py 33 KB

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