views.py 6.7 KB

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