views.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import base64
  2. import binascii
  3. import django.core.exceptions
  4. from django.conf import settings
  5. from django.contrib.auth import user_logged_in
  6. from django.core.mail import EmailMessage
  7. from django.http import Http404
  8. from django.template.loader import get_template
  9. from rest_framework import generics
  10. from rest_framework import mixins
  11. from rest_framework import status
  12. from rest_framework.authentication import get_authorization_header, BaseAuthentication
  13. from rest_framework.exceptions import (NotFound, PermissionDenied, ValidationError)
  14. from rest_framework.permissions import IsAuthenticated
  15. from rest_framework.response import Response
  16. from rest_framework.reverse import reverse
  17. from rest_framework.views import APIView
  18. from rest_framework.viewsets import GenericViewSet
  19. import desecapi.authentication as auth
  20. from desecapi import serializers, models
  21. from desecapi.pdns_change_tracker import PDNSChangeTracker
  22. from desecapi.permissions import IsOwner, IsDomainOwner, WithinDomainLimitOnPOST
  23. from desecapi.renderers import PlainTextRenderer
  24. class IdempotentDestroy:
  25. def destroy(self, request, *args, **kwargs):
  26. try:
  27. # noinspection PyUnresolvedReferences
  28. super().destroy(request, *args, **kwargs)
  29. except Http404:
  30. pass
  31. return Response(status=status.HTTP_204_NO_CONTENT)
  32. class DomainView:
  33. def initial(self, request, *args, **kwargs):
  34. # noinspection PyUnresolvedReferences
  35. super().initial(request, *args, **kwargs)
  36. try:
  37. # noinspection PyAttributeOutsideInit, PyUnresolvedReferences
  38. self.domain = self.request.user.domains.get(name=self.kwargs['name'])
  39. except models.Domain.DoesNotExist:
  40. raise Http404
  41. class TokenViewSet(IdempotentDestroy,
  42. mixins.CreateModelMixin,
  43. mixins.DestroyModelMixin,
  44. mixins.ListModelMixin,
  45. GenericViewSet):
  46. serializer_class = serializers.TokenSerializer
  47. permission_classes = (IsAuthenticated, )
  48. lookup_field = 'user_specific_id'
  49. def get_queryset(self):
  50. return self.request.user.auth_tokens.all()
  51. def get_serializer(self, *args, **kwargs):
  52. # When creating a new token, return the plaintext representation
  53. if self.request.method == 'POST':
  54. kwargs.setdefault('include_plain', True)
  55. return super().get_serializer(*args, **kwargs)
  56. def perform_create(self, serializer):
  57. serializer.save(user=self.request.user)
  58. class DomainList(generics.ListCreateAPIView):
  59. serializer_class = serializers.DomainSerializer
  60. permission_classes = (IsAuthenticated, IsOwner, WithinDomainLimitOnPOST)
  61. def get_queryset(self):
  62. return models.Domain.objects.filter(owner=self.request.user.pk)
  63. def perform_create(self, serializer):
  64. with PDNSChangeTracker():
  65. domain = serializer.save(owner=self.request.user)
  66. # TODO this line raises if the local public suffix is not in our database!
  67. PDNSChangeTracker.track(lambda: self.auto_delegate(domain))
  68. @staticmethod
  69. def auto_delegate(domain: models.Domain):
  70. if domain.is_locally_registrable:
  71. parent_domain = models.Domain.objects.get(name=domain.parent_domain_name)
  72. parent_domain.update_delegation(domain)
  73. class DomainDetail(IdempotentDestroy, generics.RetrieveUpdateDestroyAPIView):
  74. serializer_class = serializers.DomainSerializer
  75. permission_classes = (IsAuthenticated, IsOwner,)
  76. lookup_field = 'name'
  77. def perform_destroy(self, instance: models.Domain):
  78. with PDNSChangeTracker():
  79. instance.delete()
  80. if instance.is_locally_registrable:
  81. parent_domain = models.Domain.objects.get(name=instance.parent_domain_name)
  82. with PDNSChangeTracker():
  83. parent_domain.update_delegation(instance)
  84. def get_queryset(self):
  85. return models.Domain.objects.filter(owner=self.request.user.pk)
  86. def update(self, request, *args, **kwargs):
  87. try:
  88. return super().update(request, *args, **kwargs)
  89. except django.core.exceptions.ValidationError as e:
  90. raise ValidationError(detail={"detail": e.message})
  91. class RRsetDetail(IdempotentDestroy, DomainView, generics.RetrieveUpdateDestroyAPIView):
  92. serializer_class = serializers.RRsetSerializer
  93. permission_classes = (IsAuthenticated, IsDomainOwner,)
  94. def get_queryset(self):
  95. return self.domain.rrset_set
  96. def get_object(self):
  97. queryset = self.filter_queryset(self.get_queryset())
  98. filter_kwargs = {k: self.kwargs[k] for k in ['subname', 'type']}
  99. obj = generics.get_object_or_404(queryset, **filter_kwargs)
  100. # May raise a permission denied
  101. self.check_object_permissions(self.request, obj)
  102. return obj
  103. def get_serializer(self, *args, **kwargs):
  104. kwargs['domain'] = self.domain
  105. return super().get_serializer(*args, **kwargs)
  106. def update(self, request, *args, **kwargs):
  107. response = super().update(request, *args, **kwargs)
  108. if response.data is None:
  109. response.status_code = 204
  110. return response
  111. def perform_update(self, serializer):
  112. with PDNSChangeTracker():
  113. super().perform_update(serializer)
  114. def perform_destroy(self, instance):
  115. with PDNSChangeTracker():
  116. super().perform_destroy(instance)
  117. class RRsetList(DomainView, generics.ListCreateAPIView, generics.UpdateAPIView):
  118. serializer_class = serializers.RRsetSerializer
  119. permission_classes = (IsAuthenticated, IsDomainOwner,)
  120. def get_queryset(self):
  121. rrsets = models.RRset.objects.filter(domain=self.domain)
  122. for filter_field in ('subname', 'type'):
  123. value = self.request.query_params.get(filter_field)
  124. if value is not None:
  125. # TODO consider moving this
  126. if filter_field == 'type' and value in models.RRset.RESTRICTED_TYPES:
  127. raise PermissionDenied("You cannot tinker with the %s RRset." % value)
  128. rrsets = rrsets.filter(**{'%s__exact' % filter_field: value})
  129. return rrsets
  130. def get_object(self):
  131. # For this view, the object we're operating on is the queryset that one can also GET. Serializing a queryset
  132. # is fine as per https://www.django-rest-framework.org/api-guide/serializers/#serializing-multiple-objects.
  133. # We skip checking object permissions here to avoid evaluating the queryset. The user can access all his RRsets
  134. # anyways.
  135. return self.filter_queryset(self.get_queryset())
  136. def get_serializer(self, *args, **kwargs):
  137. data = kwargs.get('data')
  138. if data and 'many' not in kwargs:
  139. if self.request.method == 'POST':
  140. kwargs['many'] = isinstance(data, list)
  141. elif self.request.method in ['PATCH', 'PUT']:
  142. kwargs['many'] = True
  143. return super().get_serializer(domain=self.domain, *args, **kwargs)
  144. def perform_create(self, serializer):
  145. with PDNSChangeTracker():
  146. serializer.save(domain=self.domain)
  147. def perform_update(self, serializer):
  148. with PDNSChangeTracker():
  149. serializer.save(domain=self.domain)
  150. class Root(APIView):
  151. def get(self, request, *_):
  152. if self.request.user.is_authenticated:
  153. routes = {
  154. 'account': {
  155. 'show': reverse('account', request=request),
  156. 'delete': reverse('account-delete', request=request),
  157. 'change-email': reverse('account-change-email', request=request),
  158. 'reset-password': reverse('account-reset-password', request=request),
  159. },
  160. 'tokens': reverse('token-list', request=request),
  161. 'domains': reverse('domain-list', request=request),
  162. }
  163. else:
  164. routes = {
  165. 'register': reverse('register', request=request),
  166. 'login': reverse('login', request=request),
  167. 'reset-password': reverse('account-reset-password', request=request),
  168. }
  169. return Response(routes)
  170. class DynDNS12Update(APIView):
  171. authentication_classes = (auth.TokenAuthentication, auth.BasicTokenAuthentication, auth.URLParamAuthentication,)
  172. renderer_classes = [PlainTextRenderer]
  173. def _find_domain(self, request):
  174. def find_domain_name(r):
  175. # 1. hostname parameter
  176. if 'hostname' in r.query_params and r.query_params['hostname'] != 'YES':
  177. return r.query_params['hostname']
  178. # 2. host_id parameter
  179. if 'host_id' in r.query_params:
  180. return r.query_params['host_id']
  181. # 3. http basic auth username
  182. try:
  183. domain_name = base64.b64decode(
  184. get_authorization_header(r).decode().split(' ')[1].encode()).decode().split(':')[0]
  185. if domain_name and '@' not in domain_name:
  186. return domain_name
  187. except IndexError:
  188. pass
  189. except UnicodeDecodeError:
  190. pass
  191. except binascii.Error:
  192. pass
  193. # 4. username parameter
  194. if 'username' in r.query_params:
  195. return r.query_params['username']
  196. # 5. only domain associated with this user account
  197. if len(r.user.domains.all()) == 1:
  198. return r.user.domains.all()[0].name
  199. if len(r.user.domains.all()) > 1:
  200. ex = ValidationError(detail={
  201. "detail": "Request does not specify domain unambiguously.",
  202. "code": "domain-ambiguous"
  203. })
  204. ex.status_code = status.HTTP_409_CONFLICT
  205. raise ex
  206. return None
  207. name = find_domain_name(request).lower()
  208. try:
  209. return self.request.user.domains.get(name=name)
  210. except models.Domain.DoesNotExist:
  211. return None
  212. @staticmethod
  213. def find_ip(request, params, version=4):
  214. if version == 4:
  215. look_for = '.'
  216. elif version == 6:
  217. look_for = ':'
  218. else:
  219. raise Exception
  220. # Check URL parameters
  221. for p in params:
  222. if p in request.query_params:
  223. if not len(request.query_params[p]):
  224. return None
  225. if look_for in request.query_params[p]:
  226. return request.query_params[p]
  227. # Check remote IP address
  228. client_ip = request.META.get('REMOTE_ADDR')
  229. if look_for in client_ip:
  230. return client_ip
  231. # give up
  232. return None
  233. def _find_ip_v4(self, request):
  234. return self.find_ip(request, ['myip', 'myipv4', 'ip'])
  235. def _find_ip_v6(self, request):
  236. return self.find_ip(request, ['myipv6', 'ipv6', 'myip', 'ip'], version=6)
  237. def get(self, request, *_):
  238. domain = self._find_domain(request)
  239. if domain is None:
  240. raise NotFound('nohost')
  241. ipv4 = self._find_ip_v4(request)
  242. ipv6 = self._find_ip_v6(request)
  243. data = [
  244. {'type': 'A', 'subname': '', 'ttl': 60, 'records': [ipv4] if ipv4 else []},
  245. {'type': 'AAAA', 'subname': '', 'ttl': 60, 'records': [ipv6] if ipv6 else []},
  246. ]
  247. instances = domain.rrset_set.filter(subname='', type__in=['A', 'AAAA']).all()
  248. serializer = serializers.RRsetSerializer(instances, domain=domain, data=data, many=True, partial=True)
  249. try:
  250. serializer.is_valid(raise_exception=True)
  251. except ValidationError as e:
  252. raise e
  253. with PDNSChangeTracker():
  254. serializer.save(domain=domain)
  255. return Response('good', content_type='text/plain')
  256. class DonationList(generics.CreateAPIView):
  257. serializer_class = serializers.DonationSerializer
  258. def perform_create(self, serializer):
  259. iban = serializer.validated_data['iban']
  260. obj = serializer.save()
  261. def send_donation_emails(donation):
  262. context = {
  263. 'donation': donation,
  264. 'creditoridentifier': settings.SEPA['CREDITOR_ID'],
  265. 'creditorname': settings.SEPA['CREDITOR_NAME'],
  266. 'complete_iban': iban
  267. }
  268. # internal desec notification
  269. content_tmpl = get_template('emails/donation/desec-content.txt')
  270. subject_tmpl = get_template('emails/donation/desec-subject.txt')
  271. attachment_tmpl = get_template('emails/donation/desec-attachment-jameica.txt')
  272. from_tmpl = get_template('emails/from.txt')
  273. email = EmailMessage(subject_tmpl.render(context),
  274. content_tmpl.render(context),
  275. from_tmpl.render(context),
  276. ['donation@desec.io'],
  277. attachments=[
  278. ('jameica-directdebit.xml',
  279. attachment_tmpl.render(context),
  280. 'text/xml')
  281. ])
  282. email.send()
  283. # donor notification
  284. if donation.email:
  285. content_tmpl = get_template('emails/donation/donor-content.txt')
  286. subject_tmpl = get_template('emails/donation/donor-subject.txt')
  287. email = EmailMessage(subject_tmpl.render(context),
  288. content_tmpl.render(context),
  289. from_tmpl.render(context),
  290. [donation.email])
  291. email.send()
  292. # send emails
  293. send_donation_emails(obj)
  294. class AccountCreateView(generics.CreateAPIView):
  295. serializer_class = serializers.RegisterAccountSerializer
  296. def create(self, request, *args, **kwargs):
  297. # Create user and send trigger email verification.
  298. # Alternative would be to create user once email is verified, but this could be abused for bulk email.
  299. serializer = self.get_serializer(data=request.data)
  300. activation_required = settings.USER_ACTIVATION_REQUIRED
  301. try:
  302. serializer.is_valid(raise_exception=True)
  303. except ValidationError as e:
  304. # Hide existing users
  305. email_detail = e.detail.pop('email', [])
  306. email_detail = [detail for detail in email_detail if detail.code != 'unique']
  307. if email_detail:
  308. e.detail['email'] = email_detail
  309. if e.detail:
  310. raise e
  311. else:
  312. # create user
  313. user = serializer.save(is_active=(not activation_required))
  314. # send email if needed
  315. domain = serializer.validated_data.get('domain')
  316. if domain or activation_required:
  317. action = models.AuthenticatedActivateUserAction(user=user, domain=domain)
  318. verification_code = serializers.AuthenticatedActivateUserActionSerializer(action).data['code']
  319. user.send_email('activate-with-domain' if domain else 'activate', context={
  320. 'confirmation_link': reverse('confirm-activate-account', request=request, args=[verification_code])
  321. })
  322. # This request is unauthenticated, so don't expose whether we did anything.
  323. message = 'Welcome! Please check your mailbox.' if activation_required else 'Welcome!'
  324. return Response(data={'detail': message}, status=status.HTTP_202_ACCEPTED)
  325. class AccountView(generics.RetrieveAPIView):
  326. permission_classes = (IsAuthenticated,)
  327. serializer_class = serializers.UserSerializer
  328. def get_object(self):
  329. return self.request.user
  330. class AccountDeleteView(generics.GenericAPIView):
  331. authentication_classes = (auth.EmailPasswordPayloadAuthentication,)
  332. permission_classes = (IsAuthenticated,)
  333. response_still_has_domains = Response(
  334. data={'detail': 'To delete your user account, first delete all of your domains.'},
  335. status=status.HTTP_409_CONFLICT,
  336. )
  337. def post(self, request, *args, **kwargs):
  338. if self.request.user.domains.exists():
  339. return self.response_still_has_domains
  340. action = models.AuthenticatedDeleteUserAction(user=self.request.user)
  341. verification_code = serializers.AuthenticatedDeleteUserActionSerializer(action).data['code']
  342. request.user.send_email('delete-user', context={
  343. 'confirmation_link': reverse('confirm-delete-account', request=request, args=[verification_code])
  344. })
  345. return Response(data={'detail': 'Please check your mailbox for further account deletion instructions.'},
  346. status=status.HTTP_202_ACCEPTED)
  347. class AccountLoginView(generics.GenericAPIView):
  348. authentication_classes = (auth.EmailPasswordPayloadAuthentication,)
  349. permission_classes = (IsAuthenticated,)
  350. def post(self, request, *args, **kwargs):
  351. user = self.request.user
  352. token = models.Token.objects.create(user=user, name="login")
  353. user_logged_in.send(sender=user.__class__, request=self.request, user=user)
  354. data = serializers.TokenSerializer(token, include_plain=True).data
  355. return Response(data)
  356. class AccountChangeEmailView(generics.GenericAPIView):
  357. authentication_classes = (auth.EmailPasswordPayloadAuthentication,)
  358. permission_classes = (IsAuthenticated,)
  359. serializer_class = serializers.ChangeEmailSerializer
  360. def post(self, request, *args, **kwargs):
  361. # Check password and extract email
  362. serializer = self.get_serializer(data=request.data)
  363. serializer.is_valid(raise_exception=True)
  364. new_email = serializer.validated_data['new_email']
  365. action = models.AuthenticatedChangeEmailUserAction(user=request.user, new_email=new_email)
  366. verification_code = serializers.AuthenticatedChangeEmailUserActionSerializer(action).data['code']
  367. request.user.send_email('change-email', recipient=new_email, context={
  368. 'confirmation_link': reverse('confirm-change-email', request=request, args=[verification_code]),
  369. 'old_email': request.user.email,
  370. 'new_email': new_email,
  371. })
  372. # At this point, we know that we are talking to the user, so we can tell that we sent an email.
  373. return Response(data={'detail': 'Please check your mailbox to confirm email address change.'},
  374. status=status.HTTP_202_ACCEPTED)
  375. class AccountResetPasswordView(generics.GenericAPIView):
  376. serializer_class = serializers.EmailSerializer
  377. def post(self, request, *args, **kwargs):
  378. serializer = self.get_serializer(data=request.data)
  379. serializer.is_valid(raise_exception=True)
  380. try:
  381. email = serializer.validated_data['email']
  382. user = models.User.objects.get(email=email, is_active=True)
  383. except models.User.DoesNotExist:
  384. pass
  385. else:
  386. action = models.AuthenticatedResetPasswordUserAction(user=user)
  387. verification_code = serializers.AuthenticatedResetPasswordUserActionSerializer(action).data['code']
  388. user.send_email('reset-password', context={
  389. 'confirmation_link': reverse('confirm-reset-password', request=request, args=[verification_code])
  390. })
  391. # This request is unauthenticated, so don't expose whether we did anything.
  392. return Response(data={'detail': 'Please check your mailbox for further password reset instructions. '
  393. 'If you did not receive an email, please contact support.'},
  394. status=status.HTTP_202_ACCEPTED)
  395. class AuthenticatedActionView(generics.GenericAPIView):
  396. """
  397. Abstract class. Deserializes the given payload according the serializers specified by the view extending
  398. this class. If the `serializer.is_valid`, `act` is called on the action object.
  399. """
  400. class AuthenticatedActionAuthenticator(BaseAuthentication):
  401. """
  402. Authenticates a request based on whether the serializer determines the validity of the given verification code
  403. and additional data (using `serializer.is_valid()`). The serializer's input data will be determined by (a) the
  404. view's 'code' kwarg and (b) the request payload for POST requests. Request methods other than GET and POST will
  405. fail authentication regardless of other conditions.
  406. If the request is valid, the AuthenticatedAction instance will be attached to the view as `authenticated_action`
  407. attribute.
  408. Note that this class will raise ValidationError instead of AuthenticationFailed, usually resulting in status
  409. 400 instead of 403.
  410. """
  411. def __init__(self, view):
  412. super().__init__()
  413. self.view = view
  414. def authenticate(self, request):
  415. data = {**request.data, 'code': self.view.kwargs['code']} # order crucial to avoid override from payload!
  416. serializer = self.view.serializer_class(data=data, context=self.view.get_serializer_context())
  417. serializer.is_valid(raise_exception=True)
  418. self.view.authenticated_action = serializer.instance
  419. return self.view.authenticated_action.user, None
  420. def __init__(self, *args, **kwargs):
  421. super().__init__(*args, **kwargs)
  422. self.authenticated_action = None
  423. def get_authenticators(self):
  424. return [self.AuthenticatedActionAuthenticator(self)]
  425. def get(self, request, *args, **kwargs):
  426. return self.take_action()
  427. def post(self, request, *args, **kwargs):
  428. return self.take_action()
  429. def finalize(self):
  430. raise NotImplementedError
  431. def take_action(self):
  432. # execute the action
  433. self.authenticated_action.act()
  434. return self.finalize()
  435. class AuthenticatedActivateUserActionView(AuthenticatedActionView):
  436. http_method_names = ['get']
  437. serializer_class = serializers.AuthenticatedActivateUserActionSerializer
  438. def finalize(self):
  439. action = self.authenticated_action
  440. if not action.domain:
  441. return Response({
  442. 'detail': 'Success! Please log in at {}.'.format(self.request.build_absolute_uri(reverse('v1:login')))
  443. })
  444. serializer = serializers.DomainSerializer(
  445. data={'name': action.domain},
  446. context=self.get_serializer_context()
  447. )
  448. try:
  449. serializer.is_valid(raise_exception=True)
  450. except ValidationError as e: # e.g. domain name unavailable
  451. action.user.delete()
  452. reasons = ', '.join([detail.code for detail in e.detail.get('name', [])])
  453. raise ValidationError(
  454. f'The requested domain {action.domain} could not be registered (reason: {reasons}). '
  455. f'Please start over and sign up again.'
  456. )
  457. domain = PDNSChangeTracker.track(lambda: serializer.save(owner=action.user))
  458. if domain.is_locally_registrable:
  459. # TODO the following line raises Domain.DoesNotExist under unknown conditions
  460. PDNSChangeTracker.track(lambda: DomainList.auto_delegate(domain))
  461. token = models.Token.objects.create(user=action.user, name='dyndns')
  462. return Response({
  463. 'detail': "Success! Here is the secret token required for updating your domain's DNS information. When "
  464. "configuring a router (or other DNS client), place it into the password field of the "
  465. "configuration. Do not confuse the secret token with your account password! Your password is "
  466. "not needed for DNS configuration, and you should not store it anywhere in plain text.",
  467. **serializers.TokenSerializer(token, include_plain=True).data,
  468. })
  469. else:
  470. return Response({
  471. 'detail': 'Success! Please check the docs for the next steps, https://desec.readthedocs.io/.'
  472. })
  473. class AuthenticatedChangeEmailUserActionView(AuthenticatedActionView):
  474. http_method_names = ['get']
  475. serializer_class = serializers.AuthenticatedChangeEmailUserActionSerializer
  476. def finalize(self):
  477. return Response({
  478. 'detail': f'Success! Your email address has been changed to {self.authenticated_action.user.email}.'
  479. })
  480. class AuthenticatedResetPasswordUserActionView(AuthenticatedActionView):
  481. http_method_names = ['post']
  482. serializer_class = serializers.AuthenticatedResetPasswordUserActionSerializer
  483. def finalize(self):
  484. return Response({'detail': 'Success! Your password has been changed.'})
  485. class AuthenticatedDeleteUserActionView(AuthenticatedActionView):
  486. http_method_names = ['get']
  487. serializer_class = serializers.AuthenticatedDeleteUserActionSerializer
  488. def take_action(self):
  489. if self.request.user.domains.exists():
  490. return AccountDeleteView.response_still_has_domains
  491. return super().take_action()
  492. def finalize(self):
  493. return Response({'detail': 'All your data has been deleted. Bye bye, see you soon! <3'})
  494. class CaptchaView(generics.CreateAPIView):
  495. serializer_class = serializers.CaptchaSerializer