views.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. from django.core.exceptions import ObjectDoesNotExist, ValidationError
  2. from django.shortcuts import get_object_or_404
  3. from django.http import Http404
  4. from rest_framework import status, viewsets, mixins, exceptions
  5. from rest_framework.decorators import action
  6. from rest_framework.response import Response
  7. from drf_yasg.utils import swagger_auto_schema
  8. from dj_rest_auth.registration.views import (
  9. SocialAccountDisconnectView as BaseSocialAccountDisconnectView,
  10. )
  11. from allauth.account.models import EmailAddress
  12. from organizations_ext.models import Organization
  13. from .models import User, UserProjectAlert
  14. from .serializers import (
  15. UserSerializer,
  16. UserNotificationsSerializer,
  17. EmailAddressSerializer,
  18. ConfirmEmailAddressSerializer,
  19. )
  20. class UserViewSet(viewsets.ModelViewSet):
  21. queryset = User.objects.all()
  22. serializer_class = UserSerializer
  23. def get_queryset(self):
  24. queryset = super().get_queryset()
  25. organization_slug = self.kwargs.get("organization_slug")
  26. if organization_slug:
  27. queryset = queryset.filter(
  28. organizations_ext_organization__slug=organization_slug,
  29. organizations_ext_organization__users=self.request.user,
  30. )
  31. else:
  32. queryset = queryset.filter(id=self.request.user.id)
  33. return queryset
  34. def get_object(self):
  35. pk = self.kwargs.get("pk")
  36. if pk == "me":
  37. return self.request.user
  38. return super().get_object()
  39. def perform_create(self, serializer):
  40. organization_slug = self.kwargs.get("organization_slug")
  41. try:
  42. organization = Organization.objects.get(slug=organization_slug)
  43. except Organization.DoesNotExist:
  44. raise exceptions.ValidationError("Organization does not exist")
  45. # TODO deal with organization and users who aren't set up yet
  46. user = serializer.save()
  47. return user
  48. @action(detail=True, methods=["get", "post", "put"])
  49. def notifications(self, request, pk=None):
  50. user = self.get_object()
  51. if request.method == "GET":
  52. serializer = UserNotificationsSerializer(user)
  53. return Response(serializer.data)
  54. serializer = UserNotificationsSerializer(user, data=request.data)
  55. if serializer.is_valid():
  56. serializer.save()
  57. return Response(serializer.data)
  58. else:
  59. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  60. @action(
  61. detail=True, methods=["get", "post", "put"], url_path="notifications/alerts"
  62. )
  63. def alerts(self, request, pk=None):
  64. """
  65. Returns dictionary of project_id: status. Now project_id status means it's "default"
  66. To update, submit `{project_id: status}` where status is -1 (default), 0, or 1
  67. """
  68. user = self.get_object()
  69. alerts = user.userprojectalert_set.all()
  70. if request.method == "GET":
  71. data = {}
  72. for alert in alerts:
  73. data[alert.project_id] = alert.status
  74. return Response(data)
  75. data = request.data
  76. try:
  77. items = [x for x in data.items()]
  78. except AttributeError:
  79. raise exceptions.ValidationError(
  80. "Invalid alert format, expected dictionary"
  81. )
  82. if len(data) != 1:
  83. raise exceptions.ValidationError("Invalid alert format, expected one value")
  84. project_id, alert_status = items[0]
  85. if alert_status not in [1, 0, -1]:
  86. raise exceptions.ValidationError("Invalid status, must be -1, 0, or 1")
  87. alert = alerts.filter(project_id=project_id).first()
  88. if alert and alert_status == -1:
  89. alert.delete()
  90. else:
  91. UserProjectAlert.objects.update_or_create(
  92. user=user, project_id=project_id, defaults={"status": alert_status}
  93. )
  94. return Response(status=204)
  95. class EmailAddressViewSet(
  96. mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet,
  97. ):
  98. queryset = EmailAddress.objects.all()
  99. serializer_class = EmailAddressSerializer
  100. pagination_class = None
  101. def get_user(self, user_pk):
  102. if user_pk == "me":
  103. return self.request.user
  104. raise exceptions.ValidationError(
  105. "Can only change primary email address on own account"
  106. )
  107. def get_queryset(self):
  108. if getattr(self, "swagger_fake_view", False):
  109. # queryset just for schema generation metadata
  110. return EmailAddress.objects.none()
  111. user = self.get_user(self.kwargs.get("user_pk"))
  112. queryset = super().get_queryset().filter(user=user)
  113. return queryset
  114. def put(self, request, user_pk, format=None):
  115. """
  116. Set a new primary email (must be verified) this will also set the email used when a user logs in.
  117. """
  118. user = self.get_user(user_pk)
  119. try:
  120. email_address = user.emailaddress_set.get(
  121. email=request.data.get("email"), verified=True
  122. )
  123. email_address.set_as_primary()
  124. except ObjectDoesNotExist:
  125. raise Http404
  126. serializer = self.serializer_class(
  127. instance=email_address, data=request.data, context={"request": request}
  128. )
  129. if serializer.is_valid():
  130. serializer.save()
  131. return Response(serializer.data)
  132. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  133. def delete(self, request, user_pk, format=None):
  134. user = self.get_user(user_pk)
  135. try:
  136. email_address = user.emailaddress_set.get(
  137. email=request.data.get("email"), primary=False
  138. )
  139. except ObjectDoesNotExist:
  140. raise Http404
  141. email_address.delete()
  142. return Response(status=status.HTTP_204_NO_CONTENT)
  143. @swagger_auto_schema(responses={204: "No Content"})
  144. @action(detail=False, methods=["post"])
  145. def confirm(self, request, user_pk):
  146. serializer = ConfirmEmailAddressSerializer(data=request.data)
  147. serializer.is_valid(raise_exception=True)
  148. email_address = get_object_or_404(
  149. self.get_queryset(), email=serializer.validated_data.get("email")
  150. )
  151. email_address.send_confirmation(request)
  152. return Response(status=204)
  153. class SocialAccountDisconnectView(BaseSocialAccountDisconnectView):
  154. def post(self, request, *args, **kwargs):
  155. try:
  156. return super().post(request, *args, **kwargs)
  157. except ValidationError as e:
  158. raise exceptions.ValidationError(e.message)