views.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 organizations_ext.utils import is_organization_creation_open
  11. from teams.serializers import TeamSerializer
  12. from .invitation_backend import InvitationTokenGenerator
  13. from .models import Organization, OrganizationUser, OrganizationUserRole
  14. from .permissions import (
  15. OrganizationMemberPermission,
  16. OrganizationMemberTeamsPermission,
  17. OrganizationPermission,
  18. )
  19. from .serializers.serializers import (
  20. AcceptInviteSerializer,
  21. OrganizationDetailSerializer,
  22. OrganizationSerializer,
  23. OrganizationUserDetailSerializer,
  24. OrganizationUserProjectsSerializer,
  25. OrganizationUserSerializer,
  26. ReinviteSerializer,
  27. )
  28. class OrganizationViewSet(viewsets.ModelViewSet):
  29. filter_backends = [OrderingFilter]
  30. ordering = ["name"]
  31. ordering_fields = ["name"]
  32. queryset = Organization.objects.all()
  33. serializer_class = OrganizationSerializer
  34. lookup_field = "slug"
  35. permission_classes = [OrganizationPermission]
  36. def get_serializer_class(self):
  37. if self.action in ["retrieve"]:
  38. return OrganizationDetailSerializer
  39. return super().get_serializer_class()
  40. def get_queryset(self):
  41. if not self.request.user.is_authenticated:
  42. return self.queryset.none()
  43. queryset = self.queryset.filter(users=self.request.user)
  44. if self.action in ["retrieve"]:
  45. queryset = queryset.prefetch_related(
  46. "projects__team_set__members",
  47. "teams__members",
  48. )
  49. return queryset
  50. def perform_create(self, serializer):
  51. """
  52. Create organization with current user as owner
  53. If registration is closed, only superusers can create new orgs.
  54. """
  55. if not is_organization_creation_open() and not self.request.user.is_superuser:
  56. raise exceptions.PermissionDenied("Organization creation is not open")
  57. organization = serializer.save()
  58. organization.add_user(self.request.user, role=OrganizationUserRole.OWNER)
  59. class OrganizationMemberViewSet(viewsets.ModelViewSet):
  60. """
  61. API compatible with undocumented Sentry endpoint `/api/organizations/<slug>/members/`
  62. """
  63. queryset = OrganizationUser.objects.all()
  64. serializer_class = OrganizationUserSerializer
  65. permission_classes = [OrganizationMemberPermission]
  66. def get_serializer_class(self):
  67. if self.action in ["retrieve"]:
  68. return OrganizationUserDetailSerializer
  69. return super().get_serializer_class()
  70. def get_queryset(self):
  71. if not self.request.user.is_authenticated:
  72. return self.queryset.none()
  73. queryset = self.queryset.filter(organization__users=self.request.user)
  74. organization_slug = self.kwargs.get("organization_slug")
  75. if organization_slug:
  76. queryset = queryset.filter(organization__slug=organization_slug)
  77. team_slug = self.kwargs.get("team_slug")
  78. if team_slug:
  79. queryset = queryset.filter(team__slug=team_slug)
  80. return queryset.select_related("organization", "user").prefetch_related(
  81. "user__socialaccount_set", "organization__owner"
  82. )
  83. def get_object(self):
  84. pk = self.kwargs.get("pk")
  85. if pk == "me":
  86. obj = get_object_or_404(self.get_queryset(), user=self.request.user)
  87. self.check_object_permissions(self.request, obj)
  88. return obj
  89. return super().get_object()
  90. def check_permissions(self, request):
  91. if self.request.user.is_authenticated and self.action in [
  92. "create",
  93. "update",
  94. "partial_update",
  95. "destroy",
  96. ]:
  97. org_slug = self.kwargs.get("organization_slug")
  98. try:
  99. user_org_user = (
  100. self.request.user.organizations_ext_organizationuser.get(
  101. organization__slug=org_slug
  102. )
  103. )
  104. except ObjectDoesNotExist:
  105. raise PermissionDenied("Not a member of this organization")
  106. if user_org_user.role < OrganizationUserRole.MANAGER:
  107. raise PermissionDenied(
  108. "Must be manager or higher to add/remove organization members"
  109. )
  110. return super().check_permissions(request)
  111. def update(self, request, *args, **kwargs):
  112. """
  113. Update can both reinvite a user or change the org user which require different request data
  114. However it always returns OrganizationUserSerializer regardless
  115. Updates are always partial. Only teams and role may be edited.
  116. """
  117. if self.action in ["update"] and self.request.data.get("reinvite"):
  118. return self.reinvite(request)
  119. kwargs["partial"] = True
  120. return super().update(request, *args, **kwargs)
  121. def reinvite(self, request):
  122. """
  123. Send additional invitation to user
  124. This works more like a rest action, but is embedded within the update view for compatibility
  125. """
  126. instance = self.get_object()
  127. serializer = ReinviteSerializer(instance, data=request.data)
  128. serializer.is_valid(raise_exception=True)
  129. self.perform_update(serializer)
  130. invitation_backend().send_invitation(instance)
  131. serializer = self.serializer_class(instance)
  132. return Response(serializer.data)
  133. def perform_create(self, serializer):
  134. try:
  135. organization = self.request.user.organizations_ext_organization.get(
  136. slug=self.kwargs.get("organization_slug")
  137. )
  138. except ObjectDoesNotExist:
  139. raise Http404
  140. org_user = serializer.save(organization=organization)
  141. invitation_backend().send_invitation(org_user)
  142. return org_user
  143. def destroy(self, request, *args, **kwargs):
  144. instance = self.get_object()
  145. if hasattr(instance, "organizationowner"):
  146. return Response(
  147. data={
  148. "message": "User is organization owner. Transfer ownership first."
  149. },
  150. status=status.HTTP_400_BAD_REQUEST,
  151. )
  152. self.perform_destroy(instance)
  153. return Response(status=status.HTTP_204_NO_CONTENT)
  154. def check_team_member_permission(self, org_user, user, team):
  155. """Check if user has permission to update team members"""
  156. open_membership = org_user.organization.open_membership
  157. is_self = org_user.user == user
  158. if open_membership and is_self:
  159. return # Ok to modify yourself in any way with open_membership
  160. in_team = team.members.filter(user=user).exists()
  161. if in_team:
  162. required_role = OrganizationUserRole.ADMIN
  163. else:
  164. required_role = OrganizationUserRole.MANAGER
  165. if not self.request.user.organizations_ext_organizationuser.filter(
  166. organization=org_user.organization, role__gte=required_role
  167. ).exists():
  168. raise exceptions.PermissionDenied("Must be admin to modify teams")
  169. @action(detail=True, methods=["post"])
  170. def set_owner(self, request, *args, **kwargs):
  171. """
  172. Set this team member as the one and only one Organization owner
  173. Only an existing Owner or user with the "org:admin" scope is able to perform this.
  174. """
  175. new_owner = self.get_object()
  176. organization = new_owner.organization
  177. user = request.user
  178. if not (
  179. organization.is_owner(user)
  180. or organization.organization_users.filter(
  181. user=user, role=OrganizationUserRole.OWNER
  182. ).exists()
  183. ):
  184. raise exceptions.PermissionDenied("Only owner may set organization owner.")
  185. organization.change_owner(new_owner)
  186. return self.retrieve(request, *args, **kwargs)
  187. @action(
  188. detail=True,
  189. methods=["post", "delete"],
  190. url_path=r"teams/(?P<members_team_slug>[-\w]+)",
  191. )
  192. def teams(self, request, pk=None, organization_slug=None, members_team_slug=None):
  193. """Add existing organization user to a team"""
  194. if not pk or not organization_slug or not members_team_slug:
  195. raise exceptions.MethodNotAllowed(request.method)
  196. pk = self.kwargs.get("pk")
  197. if pk == "me":
  198. org_user = get_object_or_404(self.get_queryset(), user=self.request.user)
  199. else:
  200. queryset = self.filter_queryset(self.get_queryset())
  201. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
  202. filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
  203. org_user = get_object_or_404(queryset, **filter_kwargs)
  204. team = org_user.organization.teams.filter(slug=members_team_slug).first()
  205. # Instead of check_object_permissions
  206. permission = OrganizationMemberTeamsPermission()
  207. if not permission.has_permission(request, self):
  208. self.permission_denied(
  209. request, message=getattr(permission, "message", None)
  210. )
  211. self.check_team_member_permission(org_user, self.request.user, team)
  212. if not team:
  213. raise exceptions.NotFound()
  214. if request.method == "POST":
  215. team.members.add(org_user)
  216. serializer = TeamSerializer(team, context={"request": request})
  217. return Response(serializer.data, status=201)
  218. elif request.method == "DELETE":
  219. team.members.remove(org_user)
  220. serializer = TeamSerializer(team, context={"request": request})
  221. return Response(serializer.data, status=200)
  222. class OrganizationUserViewSet(OrganizationMemberViewSet):
  223. """
  224. Extension of OrganizationMemberViewSet that adds projects the user has access to
  225. API compatible with [get-organization-users](https://docs.sentry.io/api/organizations/get-organization-users/)
  226. """
  227. serializer_class = OrganizationUserProjectsSerializer
  228. class AcceptInviteView(views.APIView):
  229. """Accept invite to organization"""
  230. serializer_class = AcceptInviteSerializer
  231. permission_classes = [permissions.IsAuthenticatedOrReadOnly]
  232. def validate_token(self, org_user, token):
  233. if not InvitationTokenGenerator().check_token(org_user, token):
  234. raise exceptions.PermissionDenied("Invalid invite token")
  235. def get(self, request, org_user_id=None, token=None):
  236. org_user = get_object_or_404(OrganizationUser, pk=org_user_id)
  237. self.validate_token(org_user, token)
  238. serializer = self.serializer_class(
  239. {"accept_invite": False, "org_user": org_user}
  240. )
  241. return Response(serializer.data)
  242. def post(self, request, org_user_id=None, token=None):
  243. org_user = get_object_or_404(OrganizationUser, pk=org_user_id)
  244. self.validate_token(org_user, token)
  245. serializer = self.serializer_class(data=request.data)
  246. serializer.is_valid(raise_exception=True)
  247. if serializer.validated_data["accept_invite"]:
  248. org_user.accept_invite(request.user)
  249. serializer = self.serializer_class(
  250. {
  251. "accept_invite": serializer.validated_data["accept_invite"],
  252. "org_user": org_user,
  253. }
  254. )
  255. return Response(serializer.data)