views.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. import base64
  2. import binascii
  3. from datetime import timedelta
  4. from functools import cached_property
  5. import django.core.exceptions
  6. from django.conf import settings
  7. from django.contrib.auth import user_logged_in
  8. from django.contrib.auth.hashers import is_password_usable
  9. from django.core.cache import cache
  10. from django.core.mail import EmailMessage
  11. from django.http import Http404
  12. from django.shortcuts import redirect
  13. from django.template.loader import get_template
  14. from rest_framework import generics, mixins, status, viewsets
  15. from rest_framework.authentication import get_authorization_header
  16. from rest_framework.exceptions import (NotAcceptable, NotFound, PermissionDenied, ValidationError)
  17. from rest_framework.permissions import IsAuthenticated, SAFE_METHODS
  18. from rest_framework.renderers import JSONRenderer, StaticHTMLRenderer
  19. from rest_framework.response import Response
  20. from rest_framework.reverse import reverse
  21. from rest_framework.settings import api_settings
  22. from rest_framework.views import APIView
  23. import desecapi.authentication as auth
  24. from desecapi import metrics, models, permissions, serializers
  25. from desecapi.exceptions import ConcurrencyException
  26. from desecapi.pdns import get_serials
  27. from desecapi.pdns_change_tracker import PDNSChangeTracker
  28. from desecapi.renderers import PlainTextRenderer
  29. class EmptyPayloadMixin:
  30. def initialize_request(self, request, *args, **kwargs):
  31. # noinspection PyUnresolvedReferences
  32. request = super().initialize_request(request, *args, **kwargs)
  33. try:
  34. no_data = request.stream is None
  35. except:
  36. no_data = True
  37. if no_data:
  38. # In this case, data and files are both empty, so we can set request.data=None (instead of the default {}).
  39. # This allows distinguishing missing payload from empty dict payload.
  40. # See https://github.com/encode/django-rest-framework/pull/7195
  41. request._full_data = None
  42. return request
  43. class IdempotentDestroyMixin:
  44. def destroy(self, request, *args, **kwargs):
  45. try:
  46. # noinspection PyUnresolvedReferences
  47. super().destroy(request, *args, **kwargs)
  48. except Http404:
  49. pass
  50. return Response(status=status.HTTP_204_NO_CONTENT)
  51. class TokenViewSet(IdempotentDestroyMixin, viewsets.ModelViewSet):
  52. serializer_class = serializers.TokenSerializer
  53. permission_classes = (IsAuthenticated, permissions.HasManageTokensPermission,)
  54. throttle_scope = 'account_management_passive'
  55. def get_queryset(self):
  56. return self.request.user.token_set.all()
  57. def get_serializer(self, *args, **kwargs):
  58. # When creating a new token, return the plaintext representation
  59. if self.action == 'create':
  60. kwargs.setdefault('include_plain', True)
  61. return super().get_serializer(*args, **kwargs)
  62. def perform_create(self, serializer):
  63. serializer.save(user=self.request.user)
  64. class DomainViewSet(IdempotentDestroyMixin,
  65. mixins.CreateModelMixin,
  66. mixins.RetrieveModelMixin,
  67. mixins.DestroyModelMixin,
  68. mixins.ListModelMixin,
  69. viewsets.GenericViewSet):
  70. serializer_class = serializers.DomainSerializer
  71. lookup_field = 'name'
  72. lookup_value_regex = r'[^/]+'
  73. @property
  74. def permission_classes(self):
  75. ret = [IsAuthenticated, permissions.IsOwner]
  76. if self.action == 'create':
  77. ret.append(permissions.WithinDomainLimit)
  78. if self.request.method not in SAFE_METHODS:
  79. ret.append(permissions.TokenNoDomainPolicy)
  80. return ret
  81. @property
  82. def throttle_scope(self):
  83. return 'dns_api_read' if self.request.method in SAFE_METHODS else 'dns_api_write_domains'
  84. @property
  85. def pagination_class(self):
  86. # Turn off pagination when filtering for covered qname, as pagination would re-order by `created` (not what we
  87. # want here) after taking a slice (that's forbidden anyway). But, we don't need pagination in this case anyways.
  88. if 'owns_qname' in self.request.query_params:
  89. return None
  90. else:
  91. return api_settings.DEFAULT_PAGINATION_CLASS
  92. def get_queryset(self):
  93. qs = self.request.user.domains
  94. owns_qname = self.request.query_params.get('owns_qname')
  95. if owns_qname is not None:
  96. qs = qs.filter_qname(owns_qname).order_by('-name_length')[:1]
  97. return qs
  98. def get_serializer(self, *args, **kwargs):
  99. include_keys = (self.action in ['create', 'retrieve'])
  100. return super().get_serializer(*args, include_keys=include_keys, **kwargs)
  101. def perform_create(self, serializer):
  102. with PDNSChangeTracker():
  103. domain = serializer.save(owner=self.request.user)
  104. # TODO this line raises if the local public suffix is not in our database!
  105. PDNSChangeTracker.track(lambda: self.auto_delegate(domain))
  106. @staticmethod
  107. def auto_delegate(domain: models.Domain):
  108. if domain.is_locally_registrable:
  109. parent_domain = models.Domain.objects.get(name=domain.parent_domain_name)
  110. parent_domain.update_delegation(domain)
  111. def perform_destroy(self, instance: models.Domain):
  112. with PDNSChangeTracker():
  113. instance.delete()
  114. if instance.is_locally_registrable:
  115. parent_domain = models.Domain.objects.get(name=instance.parent_domain_name)
  116. with PDNSChangeTracker():
  117. parent_domain.update_delegation(instance)
  118. class TokenPoliciesRoot(APIView):
  119. permission_classes = [
  120. IsAuthenticated,
  121. permissions.HasManageTokensPermission | permissions.AuthTokenCorrespondsToViewToken,
  122. ]
  123. def get(self, request, *args, **kwargs):
  124. return Response({'domain': reverse('token_domain_policies-list', request=request, kwargs=kwargs)})
  125. class TokenDomainPolicyViewSet(IdempotentDestroyMixin, viewsets.ModelViewSet):
  126. lookup_field = 'domain__name'
  127. lookup_value_regex = DomainViewSet.lookup_value_regex
  128. pagination_class = None
  129. serializer_class = serializers.TokenDomainPolicySerializer
  130. throttle_scope = 'account_management_passive'
  131. @property
  132. def permission_classes(self):
  133. ret = [IsAuthenticated]
  134. if self.request.method in SAFE_METHODS:
  135. ret.append(permissions.HasManageTokensPermission | permissions.AuthTokenCorrespondsToViewToken)
  136. else:
  137. ret.append(permissions.HasManageTokensPermission)
  138. return ret
  139. def dispatch(self, request, *args, **kwargs):
  140. # map default policy onto domain_id IS NULL
  141. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
  142. try:
  143. if kwargs[lookup_url_kwarg] == 'default':
  144. kwargs[lookup_url_kwarg] = None
  145. except KeyError:
  146. pass
  147. return super().dispatch(request, *args, **kwargs)
  148. def get_queryset(self):
  149. return models.TokenDomainPolicy.objects.filter(token_id=self.kwargs['token_id'], token__user=self.request.user)
  150. def perform_destroy(self, instance):
  151. try:
  152. super().perform_destroy(instance)
  153. except django.core.exceptions.ValidationError as exc:
  154. raise ValidationError(exc.message_dict, code='precedence')
  155. class SerialListView(APIView):
  156. permission_classes = (permissions.IsVPNClient,)
  157. throttle_classes = [] # don't break slaves when they ask too often (our cached responses are cheap)
  158. def get(self, request, *args, **kwargs):
  159. key = 'desecapi.views.serials'
  160. serials = cache.get(key)
  161. if serials is None:
  162. serials = get_serials()
  163. cache.get_or_set(key, serials, timeout=15)
  164. return Response(serials)
  165. class RRsetView:
  166. serializer_class = serializers.RRsetSerializer
  167. permission_classes = (IsAuthenticated, permissions.IsDomainOwner, permissions.TokenHasDomainRRsetsPermission,)
  168. @property
  169. def domain(self):
  170. try:
  171. return self.request.user.domains.get(name=self.kwargs['name'])
  172. except models.Domain.DoesNotExist:
  173. raise Http404
  174. @property
  175. def throttle_scope(self):
  176. return 'dns_api_read' if self.request.method in SAFE_METHODS else 'dns_api_write_rrsets'
  177. @property
  178. def throttle_scope_bucket(self):
  179. # Note: bucket should remain constant even when domain is recreated
  180. return None if self.request.method in SAFE_METHODS else self.kwargs['name']
  181. def get_queryset(self):
  182. return self.domain.rrset_set
  183. def get_serializer_context(self):
  184. # noinspection PyUnresolvedReferences
  185. return {**super().get_serializer_context(), 'domain': self.domain}
  186. def perform_update(self, serializer):
  187. with PDNSChangeTracker():
  188. super().perform_update(serializer)
  189. class RRsetDetail(RRsetView, IdempotentDestroyMixin, generics.RetrieveUpdateDestroyAPIView):
  190. def get_object(self):
  191. queryset = self.filter_queryset(self.get_queryset())
  192. filter_kwargs = {k: self.kwargs[k] for k in ['subname', 'type']}
  193. obj = generics.get_object_or_404(queryset, **filter_kwargs)
  194. # May raise a permission denied
  195. self.check_object_permissions(self.request, obj)
  196. return obj
  197. def update(self, request, *args, **kwargs):
  198. response = super().update(request, *args, **kwargs)
  199. if response.data is None:
  200. response.status_code = 204
  201. return response
  202. def perform_destroy(self, instance):
  203. with PDNSChangeTracker():
  204. super().perform_destroy(instance)
  205. class RRsetList(RRsetView, EmptyPayloadMixin, generics.ListCreateAPIView, generics.UpdateAPIView):
  206. def get_queryset(self):
  207. rrsets = super().get_queryset()
  208. for filter_field in ('subname', 'type'):
  209. value = self.request.query_params.get(filter_field)
  210. if value is not None:
  211. # TODO consider moving this
  212. if filter_field == 'type' and value in models.RR_SET_TYPES_AUTOMATIC:
  213. raise PermissionDenied("You cannot tinker with the %s RRset." % value)
  214. rrsets = rrsets.filter(**{'%s__exact' % filter_field: value})
  215. return rrsets.all() # without .all(), cache is sometimes inconsistent with actual state in bulk tests. (Why?)
  216. def get_object(self):
  217. # For this view, the object we're operating on is the queryset that one can also GET. Serializing a queryset
  218. # is fine as per https://www.django-rest-framework.org/api-guide/serializers/#serializing-multiple-objects.
  219. # We skip checking object permissions here to avoid evaluating the queryset. The user can access all his RRsets
  220. # anyways.
  221. return self.filter_queryset(self.get_queryset())
  222. def get_serializer(self, *args, **kwargs):
  223. kwargs = kwargs.copy()
  224. if 'many' not in kwargs:
  225. if self.request.method in ['POST']:
  226. kwargs['many'] = isinstance(kwargs.get('data'), list)
  227. elif self.request.method in ['PATCH', 'PUT']:
  228. kwargs['many'] = True
  229. return super().get_serializer(*args, **kwargs)
  230. def perform_create(self, serializer):
  231. with PDNSChangeTracker():
  232. super().perform_create(serializer)
  233. class Root(APIView):
  234. def get(self, request, *args, **kwargs):
  235. if self.request.user.is_authenticated:
  236. routes = {
  237. 'account': {
  238. 'show': reverse('account', request=request),
  239. 'delete': reverse('account-delete', request=request),
  240. 'change-email': reverse('account-change-email', request=request),
  241. 'reset-password': reverse('account-reset-password', request=request),
  242. },
  243. 'logout': reverse('logout', request=request),
  244. 'tokens': reverse('token-list', request=request),
  245. 'domains': reverse('domain-list', request=request),
  246. }
  247. else:
  248. routes = {
  249. 'register': reverse('register', request=request),
  250. 'login': reverse('login', request=request),
  251. 'reset-password': reverse('account-reset-password', request=request),
  252. }
  253. return Response(routes)
  254. class DynDNS12UpdateView(generics.GenericAPIView):
  255. authentication_classes = (auth.TokenAuthentication, auth.BasicTokenAuthentication, auth.URLParamAuthentication,)
  256. permission_classes = (permissions.TokenHasDomainDynDNSPermission,)
  257. renderer_classes = [PlainTextRenderer]
  258. serializer_class = serializers.RRsetSerializer
  259. throttle_scope = 'dyndns'
  260. @property
  261. def throttle_scope_bucket(self):
  262. return self.domain.name
  263. def _find_ip(self, params, version):
  264. if version == 4:
  265. look_for = '.'
  266. elif version == 6:
  267. look_for = ':'
  268. else:
  269. raise Exception
  270. # Check URL parameters
  271. for p in params:
  272. if p in self.request.query_params:
  273. if not len(self.request.query_params[p]):
  274. return None
  275. if look_for in self.request.query_params[p]:
  276. return self.request.query_params[p]
  277. # Check remote IP address
  278. client_ip = self.request.META.get('REMOTE_ADDR')
  279. if look_for in client_ip:
  280. return client_ip
  281. # give up
  282. return None
  283. @cached_property
  284. def qname(self):
  285. # hostname parameter
  286. try:
  287. if self.request.query_params['hostname'] != 'YES':
  288. return self.request.query_params['hostname'].lower()
  289. except KeyError:
  290. pass
  291. # host_id parameter
  292. try:
  293. return self.request.query_params['host_id'].lower()
  294. except KeyError:
  295. pass
  296. # http basic auth username
  297. try:
  298. domain_name = base64.b64decode(
  299. get_authorization_header(self.request).decode().split(' ')[1].encode()).decode().split(':')[0]
  300. if domain_name and '@' not in domain_name:
  301. return domain_name.lower()
  302. except (binascii.Error, IndexError, UnicodeDecodeError):
  303. pass
  304. # username parameter
  305. try:
  306. return self.request.query_params['username'].lower()
  307. except KeyError:
  308. pass
  309. # only domain associated with this user account
  310. try:
  311. return self.request.user.domains.get().name
  312. except models.Domain.MultipleObjectsReturned:
  313. raise ValidationError(detail={
  314. "detail": "Request does not properly specify domain for update.",
  315. "code": "domain-unspecified"
  316. })
  317. except models.Domain.DoesNotExist:
  318. metrics.get('desecapi_dynDNS12_domain_not_found').inc()
  319. raise NotFound('nohost')
  320. @cached_property
  321. def domain(self):
  322. try:
  323. return models.Domain.objects.filter_qname(self.qname, owner=self.request.user).order_by('-name_length')[0]
  324. except (IndexError, ValueError):
  325. raise NotFound('nohost')
  326. @property
  327. def subname(self):
  328. return self.qname.rpartition(f'.{self.domain.name}')[0]
  329. def get_serializer_context(self):
  330. return {**super().get_serializer_context(), 'domain': self.domain, 'minimum_ttl': 60}
  331. def get_queryset(self):
  332. return self.domain.rrset_set.filter(subname=self.subname, type__in=['A', 'AAAA'])
  333. def get(self, request, *args, **kwargs):
  334. instances = self.get_queryset().all()
  335. ipv4 = self._find_ip(['myip', 'myipv4', 'ip'], version=4)
  336. ipv6 = self._find_ip(['myipv6', 'ipv6', 'myip', 'ip'], version=6)
  337. data = [
  338. {'type': 'A', 'subname': self.subname, 'ttl': 60, 'records': [ipv4] if ipv4 else []},
  339. {'type': 'AAAA', 'subname': self.subname, 'ttl': 60, 'records': [ipv6] if ipv6 else []},
  340. ]
  341. serializer = self.get_serializer(instances, data=data, many=True, partial=True)
  342. try:
  343. serializer.is_valid(raise_exception=True)
  344. except ValidationError as e:
  345. if any(
  346. any(
  347. getattr(non_field_error, 'code', '') == 'unique'
  348. for non_field_error
  349. in err.get('non_field_errors', [])
  350. )
  351. for err in e.detail
  352. ):
  353. raise ConcurrencyException from e
  354. raise e
  355. with PDNSChangeTracker():
  356. serializer.save()
  357. return Response('good', content_type='text/plain')
  358. class DonationList(generics.CreateAPIView):
  359. serializer_class = serializers.DonationSerializer
  360. def perform_create(self, serializer):
  361. instance = serializer.save()
  362. context = {
  363. 'donation': instance,
  364. 'creditoridentifier': settings.SEPA['CREDITOR_ID'],
  365. 'creditorname': settings.SEPA['CREDITOR_NAME'],
  366. }
  367. # internal desec notification
  368. content_tmpl = get_template('emails/donation/desec-content.txt')
  369. subject_tmpl = get_template('emails/donation/desec-subject.txt')
  370. attachment_tmpl = get_template('emails/donation/desec-attachment-jameica.txt')
  371. from_tmpl = get_template('emails/from.txt')
  372. email = EmailMessage(subject_tmpl.render(context),
  373. content_tmpl.render(context),
  374. from_tmpl.render(context),
  375. [settings.DEFAULT_FROM_EMAIL],
  376. attachments=[('jameica-directdebit.xml', attachment_tmpl.render(context), 'text/xml')],
  377. reply_to=[instance.email] if instance.email else None
  378. )
  379. email.send()
  380. # donor notification
  381. if instance.email:
  382. content_tmpl = get_template('emails/donation/donor-content.txt')
  383. subject_tmpl = get_template('emails/donation/donor-subject.txt')
  384. email = EmailMessage(subject_tmpl.render(context),
  385. content_tmpl.render(context),
  386. from_tmpl.render(context),
  387. [instance.email])
  388. email.send()
  389. class AccountCreateView(generics.CreateAPIView):
  390. serializer_class = serializers.RegisterAccountSerializer
  391. throttle_scope = 'account_management_active'
  392. def create(self, request, *args, **kwargs):
  393. # Create user and send trigger email verification.
  394. # Alternative would be to create user once email is verified, but this could be abused for bulk email.
  395. serializer = self.get_serializer(data=request.data)
  396. activation_required = settings.USER_ACTIVATION_REQUIRED
  397. try:
  398. serializer.is_valid(raise_exception=True)
  399. except ValidationError as e:
  400. # Hide existing users
  401. email_detail = e.detail.pop('email', [])
  402. email_detail = [detail for detail in email_detail if detail.code != 'unique']
  403. if email_detail:
  404. e.detail['email'] = email_detail
  405. if e.detail:
  406. raise e
  407. else:
  408. # create user
  409. user = serializer.save(is_active=None if activation_required else True)
  410. # send email if needed
  411. domain = serializer.validated_data.get('domain')
  412. if domain or activation_required:
  413. serializers.AuthenticatedActivateUserActionSerializer.build_and_save(user=user, domain=domain)
  414. # This request is unauthenticated, so don't expose whether we did anything.
  415. message = 'Welcome! Please check your mailbox.' if activation_required else 'Welcome!'
  416. return Response(data={'detail': message}, status=status.HTTP_202_ACCEPTED)
  417. class AccountView(generics.RetrieveUpdateAPIView):
  418. permission_classes = (IsAuthenticated, permissions.TokenNoDomainPolicy,)
  419. serializer_class = serializers.UserSerializer
  420. throttle_scope = 'account_management_passive'
  421. def get_object(self):
  422. return self.request.user
  423. class AccountDeleteView(APIView):
  424. authentication_classes = (auth.EmailPasswordPayloadAuthentication,)
  425. permission_classes = (IsAuthenticated,)
  426. response_still_has_domains = Response(
  427. data={'detail': 'To delete your user account, first delete all of your domains.'},
  428. status=status.HTTP_409_CONFLICT,
  429. )
  430. throttle_scope = 'account_management_active'
  431. def post(self, request, *args, **kwargs):
  432. if request.user.domains.exists():
  433. return self.response_still_has_domains
  434. serializers.AuthenticatedDeleteUserActionSerializer.build_and_save(user=request.user)
  435. return Response(data={'detail': 'Please check your mailbox for further account deletion instructions.'},
  436. status=status.HTTP_202_ACCEPTED)
  437. class AccountLoginView(generics.GenericAPIView):
  438. authentication_classes = (auth.EmailPasswordPayloadAuthentication,)
  439. permission_classes = (IsAuthenticated,)
  440. serializer_class = serializers.TokenSerializer
  441. throttle_scope = 'account_management_passive'
  442. def post(self, request, *args, **kwargs):
  443. user = self.request.user
  444. token = models.Token.objects.create(user=user, name="login", perm_manage_tokens=True,
  445. max_age=timedelta(days=7), max_unused_period=timedelta(hours=1))
  446. user_logged_in.send(sender=user.__class__, request=self.request, user=user)
  447. data = self.get_serializer(token, include_plain=True).data
  448. return Response(data)
  449. class AccountLogoutView(APIView, mixins.DestroyModelMixin):
  450. authentication_classes = (auth.TokenAuthentication,)
  451. permission_classes = (IsAuthenticated,)
  452. throttle_classes = [] # always allow people to log out
  453. def get_object(self):
  454. # self.request.auth contains the hashed key as it is stored in the database
  455. return models.Token.objects.get(key=self.request.auth)
  456. def post(self, request, *args, **kwargs):
  457. return self.destroy(request, *args, **kwargs)
  458. class AccountChangeEmailView(generics.GenericAPIView):
  459. authentication_classes = (auth.EmailPasswordPayloadAuthentication,)
  460. permission_classes = (IsAuthenticated,)
  461. serializer_class = serializers.ChangeEmailSerializer
  462. throttle_scope = 'account_management_active'
  463. def post(self, request, *args, **kwargs):
  464. # Check password and extract `new_email` field
  465. serializer = self.get_serializer(data=request.data)
  466. serializer.is_valid(raise_exception=True)
  467. new_email = serializer.validated_data['new_email']
  468. serializers.AuthenticatedChangeEmailUserActionSerializer.build_and_save(user=request.user, new_email=new_email)
  469. # At this point, we know that we are talking to the user, so we can tell that we sent an email.
  470. return Response(data={'detail': 'Please check your mailbox to confirm email address change.'},
  471. status=status.HTTP_202_ACCEPTED)
  472. class AccountResetPasswordView(generics.GenericAPIView):
  473. serializer_class = serializers.ResetPasswordSerializer
  474. throttle_scope = 'account_management_active'
  475. def post(self, request, *args, **kwargs):
  476. serializer = self.get_serializer(data=request.data)
  477. serializer.is_valid(raise_exception=True)
  478. try:
  479. email = serializer.validated_data['email']
  480. user = models.User.objects.get(email=email, is_active=True)
  481. except models.User.DoesNotExist:
  482. pass
  483. else:
  484. serializers.AuthenticatedResetPasswordUserActionSerializer.build_and_save(user=user)
  485. # This request is unauthenticated, so don't expose whether we did anything.
  486. return Response(data={'detail': 'Please check your mailbox for further password reset instructions. '
  487. 'If you did not receive an email, please contact support.'},
  488. status=status.HTTP_202_ACCEPTED)
  489. class AuthenticatedActionView(generics.GenericAPIView):
  490. """
  491. Abstract class. Deserializes the given payload according the serializers specified by the view extending
  492. this class. If the `serializer.is_valid`, `act` is called on the action object.
  493. Summary of the behavior depending on HTTP method and Accept: header:
  494. GET POST other method
  495. Accept: text/html forward to `self.html_url` if any perform action 405 Method Not Allowed
  496. else HTTP 406 Not Acceptable perform action 405 Method Not Allowed
  497. """
  498. authenticated_action = None
  499. html_url = None # Redirect GET requests to this webapp GUI URL
  500. http_method_names = ['get', 'post'] # GET is for redirect only
  501. renderer_classes = [JSONRenderer, StaticHTMLRenderer]
  502. _authenticated_action = None
  503. @property
  504. def authenticated_action(self):
  505. if self._authenticated_action is None:
  506. serializer = self.get_serializer(data=self.request.data)
  507. serializer.is_valid(raise_exception=True)
  508. try:
  509. self._authenticated_action = serializer.Meta.model(**serializer.validated_data)
  510. except ValueError: # this happens when state cannot be verified
  511. ex = ValidationError('This action cannot be carried out because another operation has been performed, '
  512. 'invalidating this one. (Are you trying to perform this action twice?)')
  513. ex.status_code = status.HTTP_409_CONFLICT
  514. raise ex
  515. return self._authenticated_action
  516. @property
  517. def authentication_classes(self):
  518. # This prevents both auth action code evaluation and user-specific throttling when we only want a redirect
  519. return () if self.request.method in SAFE_METHODS else (auth.AuthenticatedBasicUserActionAuthentication,)
  520. @property
  521. def permission_classes(self):
  522. return () if self.request.method in SAFE_METHODS else (permissions.IsActiveUser,)
  523. @property
  524. def throttle_scope(self):
  525. return 'account_management_passive' if self.request.method in SAFE_METHODS else 'account_management_active'
  526. def get_serializer_context(self):
  527. return {
  528. **super().get_serializer_context(),
  529. 'code': self.kwargs['code'],
  530. 'validity_period': self.get_serializer_class().validity_period,
  531. }
  532. def get(self, request, *args, **kwargs):
  533. # Redirect browsers to frontend if available
  534. is_redirect = (request.accepted_renderer.format == 'html') and self.html_url is not None
  535. if is_redirect:
  536. # Careful: This can generally lead to an open redirect if values contain slashes!
  537. # However, it cannot happen for Django view kwargs.
  538. return redirect(self.html_url.format(**kwargs))
  539. else:
  540. raise NotAcceptable
  541. def post(self, request, *args, **kwargs):
  542. self.authenticated_action.act()
  543. return Response(status=status.HTTP_202_ACCEPTED)
  544. class AuthenticatedChangeOutreachPreferenceUserActionView(AuthenticatedActionView):
  545. html_url = '/confirm/change-outreach-preference/{code}/'
  546. serializer_class = serializers.AuthenticatedChangeOutreachPreferenceUserActionSerializer
  547. def post(self, request, *args, **kwargs):
  548. super().post(request, *args, **kwargs)
  549. return Response({'detail': 'Thank you! We have recorded that you would not like to receive outreach messages.'})
  550. class AuthenticatedActivateUserActionView(AuthenticatedActionView):
  551. html_url = '/confirm/activate-account/{code}/'
  552. permission_classes = () # don't require that user is activated already
  553. serializer_class = serializers.AuthenticatedActivateUserActionSerializer
  554. def post(self, request, *args, **kwargs):
  555. super().post(request, *args, **kwargs)
  556. if not self.authenticated_action.domain:
  557. return self._finalize_without_domain()
  558. else:
  559. domain = self._create_domain()
  560. return self._finalize_with_domain(domain)
  561. def _create_domain(self):
  562. serializer = serializers.DomainSerializer(
  563. data={'name': self.authenticated_action.domain},
  564. context=self.get_serializer_context()
  565. )
  566. try:
  567. serializer.is_valid(raise_exception=True)
  568. except ValidationError as e: # e.g. domain name unavailable
  569. self.request.user.delete()
  570. reasons = ', '.join([detail.code for detail in e.detail.get('name', [])])
  571. raise ValidationError(
  572. f'The requested domain {self.authenticated_action.domain} could not be registered (reason: {reasons}). '
  573. f'Please start over and sign up again.'
  574. )
  575. # TODO the following line is subject to race condition and can fail, as for the domain name, we have that
  576. # time-of-check != time-of-action
  577. return PDNSChangeTracker.track(lambda: serializer.save(owner=self.request.user))
  578. def _finalize_without_domain(self):
  579. if not is_password_usable(self.request.user.password):
  580. serializers.AuthenticatedResetPasswordUserActionSerializer.build_and_save(user=self.request.user)
  581. return Response({'detail': 'Success! We sent you instructions on how to set your password.'})
  582. return Response({'detail': 'Success! Your account has been activated, and you can now log in.'})
  583. def _finalize_with_domain(self, domain):
  584. if domain.is_locally_registrable:
  585. # TODO the following line raises Domain.DoesNotExist under unknown conditions
  586. PDNSChangeTracker.track(lambda: DomainViewSet.auto_delegate(domain))
  587. token = models.Token.objects.create(user=domain.owner, name='dyndns')
  588. return Response({
  589. 'detail': 'Success! Here is the password ("token") to configure your router (or any other dynDNS '
  590. 'client). This password is different from your account password for security reasons.',
  591. 'domain': serializers.DomainSerializer(domain).data,
  592. **serializers.TokenSerializer(token, include_plain=True).data,
  593. })
  594. else:
  595. return Response({
  596. 'detail': 'Success! Please check the docs for the next steps, https://desec.readthedocs.io/.',
  597. 'domain': serializers.DomainSerializer(domain, include_keys=True).data,
  598. })
  599. class AuthenticatedChangeEmailUserActionView(AuthenticatedActionView):
  600. html_url = '/confirm/change-email/{code}/'
  601. serializer_class = serializers.AuthenticatedChangeEmailUserActionSerializer
  602. def post(self, request, *args, **kwargs):
  603. super().post(request, *args, **kwargs)
  604. return Response({
  605. 'detail': f'Success! Your email address has been changed to {self.authenticated_action.user.email}.'
  606. })
  607. class AuthenticatedConfirmAccountUserActionView(AuthenticatedActionView):
  608. html_url = '/confirm/confirm-account/{code}'
  609. serializer_class = serializers.AuthenticatedConfirmAccountUserActionSerializer
  610. def post(self, request, *args, **kwargs):
  611. super().post(request, *args, **kwargs)
  612. return Response({'detail': 'Success! Your account status has been confirmed.'})
  613. class AuthenticatedResetPasswordUserActionView(AuthenticatedActionView):
  614. html_url = '/confirm/reset-password/{code}/'
  615. serializer_class = serializers.AuthenticatedResetPasswordUserActionSerializer
  616. def post(self, request, *args, **kwargs):
  617. super().post(request, *args, **kwargs)
  618. return Response({'detail': 'Success! Your password has been changed.'})
  619. class AuthenticatedDeleteUserActionView(AuthenticatedActionView):
  620. html_url = '/confirm/delete-account/{code}/'
  621. serializer_class = serializers.AuthenticatedDeleteUserActionSerializer
  622. def post(self, request, *args, **kwargs):
  623. if self.request.user.domains.exists():
  624. return AccountDeleteView.response_still_has_domains
  625. super().post(request, *args, **kwargs)
  626. return Response({'detail': 'All your data has been deleted. Bye bye, see you soon! <3'})
  627. class AuthenticatedRenewDomainBasicUserActionView(AuthenticatedActionView):
  628. html_url = '/confirm/renew-domain/{code}/'
  629. serializer_class = serializers.AuthenticatedRenewDomainBasicUserActionSerializer
  630. def post(self, request, *args, **kwargs):
  631. super().post(request, *args, **kwargs)
  632. return Response({'detail': f'We recorded that your domain {self.authenticated_action.domain} is still in use.'})
  633. class CaptchaView(generics.CreateAPIView):
  634. serializer_class = serializers.CaptchaSerializer
  635. throttle_scope = 'account_management_passive'