views.py 7.3 KB

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