views.py 11 KB

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