views.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. from django.core.exceptions import ObjectDoesNotExist
  2. from django.http import Http404
  3. from django.shortcuts import get_object_or_404
  4. from organizations.backends import invitation_backend
  5. from rest_framework import exceptions, permissions, status, views, viewsets
  6. from rest_framework.decorators import action
  7. from rest_framework.exceptions import PermissionDenied
  8. from rest_framework.filters import OrderingFilter
  9. from rest_framework.response import Response
  10. from apps.organizations_ext.utils import is_organization_creation_open
  11. from .invitation_backend import InvitationTokenGenerator
  12. from .models import Organization, OrganizationUser, OrganizationUserRole
  13. from .permissions import (
  14. OrganizationMemberPermission,
  15. OrganizationPermission,
  16. )
  17. from .serializers.serializers import (
  18. AcceptInviteSerializer,
  19. OrganizationDetailSerializer,
  20. OrganizationSerializer,
  21. OrganizationUserDetailSerializer,
  22. OrganizationUserProjectsSerializer,
  23. OrganizationUserSerializer,
  24. ReinviteSerializer,
  25. )
  26. class OrganizationViewSet(viewsets.ModelViewSet):
  27. filter_backends = [OrderingFilter]
  28. ordering = ["name"]
  29. ordering_fields = ["name"]
  30. queryset = Organization.objects.all()
  31. serializer_class = OrganizationSerializer
  32. lookup_field = "slug"
  33. permission_classes = [OrganizationPermission]
  34. def get_serializer_class(self):
  35. if self.action in ["retrieve"]:
  36. return OrganizationDetailSerializer
  37. return super().get_serializer_class()
  38. def get_queryset(self):
  39. if not self.request.user.is_authenticated:
  40. return self.queryset.none()
  41. queryset = self.queryset.filter(users=self.request.user)
  42. if self.action in ["retrieve"]:
  43. queryset = queryset.prefetch_related(
  44. "projects__team_set__members",
  45. "teams__members",
  46. )
  47. return queryset
  48. def perform_create(self, serializer):
  49. """
  50. Create organization with current user as owner
  51. If registration is closed, only superusers can create new orgs.
  52. """
  53. if not is_organization_creation_open() and not self.request.user.is_superuser:
  54. raise exceptions.PermissionDenied("Organization creation is not open")
  55. organization = serializer.save()
  56. organization.add_user(self.request.user, role=OrganizationUserRole.OWNER)
  57. class OrganizationMemberViewSet(viewsets.ModelViewSet):
  58. """
  59. API compatible with undocumented Sentry endpoint `/api/organizations/<slug>/members/`
  60. """
  61. queryset = OrganizationUser.objects.all()
  62. serializer_class = OrganizationUserSerializer
  63. permission_classes = [OrganizationMemberPermission]
  64. def get_serializer_class(self):
  65. if self.action in ["retrieve"]:
  66. return OrganizationUserDetailSerializer
  67. return super().get_serializer_class()
  68. def get_queryset(self):
  69. if not self.request.user.is_authenticated:
  70. return self.queryset.none()
  71. queryset = self.queryset.filter(organization__users=self.request.user)
  72. organization_slug = self.kwargs.get("organization_slug")
  73. if organization_slug:
  74. queryset = queryset.filter(organization__slug=organization_slug)
  75. team_slug = self.kwargs.get("team_slug")
  76. if team_slug:
  77. queryset = queryset.filter(team__slug=team_slug)
  78. return queryset.select_related("organization", "user").prefetch_related(
  79. "user__socialaccount_set", "organization__owner"
  80. )
  81. def get_object(self):
  82. pk = self.kwargs.get("pk")
  83. if pk == "me":
  84. obj = get_object_or_404(self.get_queryset(), user=self.request.user)
  85. self.check_object_permissions(self.request, obj)
  86. return obj
  87. return super().get_object()
  88. def check_permissions(self, request):
  89. if self.request.user.is_authenticated and self.action in [
  90. "create",
  91. "update",
  92. "partial_update",
  93. "destroy",
  94. ]:
  95. org_slug = self.kwargs.get("organization_slug")
  96. try:
  97. user_org_user = (
  98. self.request.user.organizations_ext_organizationuser.get(
  99. organization__slug=org_slug
  100. )
  101. )
  102. except ObjectDoesNotExist:
  103. raise PermissionDenied("Not a member of this organization")
  104. if user_org_user.role < OrganizationUserRole.MANAGER:
  105. raise PermissionDenied(
  106. "Must be manager or higher to add/remove organization members"
  107. )
  108. return super().check_permissions(request)
  109. def update(self, request, *args, **kwargs):
  110. """
  111. Update can both reinvite a user or change the org user which require different request data
  112. However it always returns OrganizationUserSerializer regardless
  113. Updates are always partial. Only teams and role may be edited.
  114. """
  115. if self.action in ["update"] and self.request.data.get("reinvite"):
  116. return self.reinvite(request)
  117. kwargs["partial"] = True
  118. return super().update(request, *args, **kwargs)
  119. def reinvite(self, request):
  120. """
  121. Send additional invitation to user
  122. This works more like a rest action, but is embedded within the update view for compatibility
  123. """
  124. instance = self.get_object()
  125. serializer = ReinviteSerializer(instance, data=request.data)
  126. serializer.is_valid(raise_exception=True)
  127. self.perform_update(serializer)
  128. invitation_backend().send_invitation(instance)
  129. serializer = self.serializer_class(instance)
  130. return Response(serializer.data)
  131. def perform_create(self, serializer):
  132. try:
  133. organization = self.request.user.organizations_ext_organization.get(
  134. slug=self.kwargs.get("organization_slug")
  135. )
  136. except ObjectDoesNotExist:
  137. raise Http404
  138. org_user = serializer.save(organization=organization)
  139. invitation_backend().send_invitation(org_user)
  140. return org_user
  141. def destroy(self, request, *args, **kwargs):
  142. instance = self.get_object()
  143. if hasattr(instance, "organizationowner"):
  144. return Response(
  145. data={
  146. "message": "User is organization owner. Transfer ownership first."
  147. },
  148. status=status.HTTP_400_BAD_REQUEST,
  149. )
  150. self.perform_destroy(instance)
  151. return Response(status=status.HTTP_204_NO_CONTENT)
  152. @action(detail=True, methods=["post"])
  153. def set_owner(self, request, *args, **kwargs):
  154. """
  155. Set this team member as the one and only one Organization owner
  156. Only an existing Owner or user with the "org:admin" scope is able to perform this.
  157. """
  158. new_owner = self.get_object()
  159. organization = new_owner.organization
  160. user = request.user
  161. if not (
  162. organization.is_owner(user)
  163. or organization.organization_users.filter(
  164. user=user, role=OrganizationUserRole.OWNER
  165. ).exists()
  166. ):
  167. raise exceptions.PermissionDenied("Only owner may set organization owner.")
  168. organization.change_owner(new_owner)
  169. return self.retrieve(request, *args, **kwargs)
  170. class OrganizationUserViewSet(OrganizationMemberViewSet):
  171. """
  172. Extension of OrganizationMemberViewSet that adds projects the user has access to
  173. API compatible with [get-organization-users](https://docs.sentry.io/api/organizations/get-organization-users/)
  174. """
  175. serializer_class = OrganizationUserProjectsSerializer
  176. class AcceptInviteView(views.APIView):
  177. """Accept invite to organization"""
  178. serializer_class = AcceptInviteSerializer
  179. permission_classes = [permissions.IsAuthenticatedOrReadOnly]
  180. def validate_token(self, org_user, token):
  181. if not InvitationTokenGenerator().check_token(org_user, token):
  182. raise exceptions.PermissionDenied("Invalid invite token")
  183. def get(self, request, org_user_id=None, token=None):
  184. org_user = get_object_or_404(OrganizationUser, pk=org_user_id)
  185. self.validate_token(org_user, token)
  186. serializer = self.serializer_class(
  187. {"accept_invite": False, "org_user": org_user}
  188. )
  189. return Response(serializer.data)
  190. def post(self, request, org_user_id=None, token=None):
  191. org_user = get_object_or_404(OrganizationUser, pk=org_user_id)
  192. self.validate_token(org_user, token)
  193. serializer = self.serializer_class(data=request.data)
  194. serializer.is_valid(raise_exception=True)
  195. if serializer.validated_data["accept_invite"]:
  196. org_user.accept_invite(request.user)
  197. serializer = self.serializer_class(
  198. {
  199. "accept_invite": serializer.validated_data["accept_invite"],
  200. "org_user": org_user,
  201. }
  202. )
  203. return Response(serializer.data)