views.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. from django.core.exceptions import ObjectDoesNotExist
  2. from django.http import Http404
  3. from django.shortcuts import get_object_or_404
  4. from drf_yasg.utils import swagger_auto_schema
  5. from organizations.backends import invitation_backend
  6. from rest_framework import exceptions, permissions, status, views, viewsets
  7. from rest_framework.decorators import action
  8. from rest_framework.exceptions import PermissionDenied
  9. from rest_framework.filters import OrderingFilter
  10. from rest_framework.response import Response
  11. from organizations_ext.utils import is_organization_creation_open
  12. from projects.views import NestedProjectViewSet
  13. from teams.serializers import TeamSerializer
  14. from .invitation_backend import InvitationTokenGenerator
  15. from .models import Organization, OrganizationUser, OrganizationUserRole
  16. from .permissions import (
  17. OrganizationMemberPermission,
  18. OrganizationMemberTeamsPermission,
  19. OrganizationPermission,
  20. )
  21. from .serializers.serializers import (
  22. AcceptInviteSerializer,
  23. OrganizationDetailSerializer,
  24. OrganizationSerializer,
  25. OrganizationUserDetailSerializer,
  26. OrganizationUserProjectsSerializer,
  27. OrganizationUserSerializer,
  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", "organization__owner"
  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 destroy(self, request, *args, **kwargs):
  146. instance = self.get_object()
  147. if hasattr(instance, "organizationowner"):
  148. return Response(
  149. data={
  150. "message": "User is organization owner. Transfer ownership first."
  151. },
  152. status=status.HTTP_400_BAD_REQUEST,
  153. )
  154. self.perform_destroy(instance)
  155. return Response(status=status.HTTP_204_NO_CONTENT)
  156. def check_team_member_permission(self, org_user, user, team):
  157. """Check if user has permission to update team members"""
  158. open_membership = org_user.organization.open_membership
  159. is_self = org_user.user == user
  160. if open_membership and is_self:
  161. return # Ok to modify yourself in any way with open_membership
  162. in_team = team.members.filter(user=user).exists()
  163. if in_team:
  164. required_role = OrganizationUserRole.ADMIN
  165. else:
  166. required_role = OrganizationUserRole.MANAGER
  167. if not self.request.user.organizations_ext_organizationuser.filter(
  168. organization=org_user.organization, role__gte=required_role
  169. ).exists():
  170. raise exceptions.PermissionDenied("Must be admin to modify teams")
  171. @action(detail=True, methods=["post"])
  172. def set_owner(self, request, *args, **kwargs):
  173. """
  174. Set this team member as the one and only one Organization owner
  175. Only an existing Owner or user with the "org:admin" scope is able to perform this.
  176. """
  177. new_owner = self.get_object()
  178. organization = new_owner.organization
  179. user = request.user
  180. if not (
  181. organization.is_owner(user)
  182. or organization.organization_users.filter(
  183. user=user, role=OrganizationUserRole.OWNER
  184. ).exists()
  185. ):
  186. raise exceptions.PermissionDenied("Only owner may set organization owner.")
  187. organization.change_owner(new_owner)
  188. return self.retrieve(request, *args, **kwargs)
  189. @action(
  190. detail=True,
  191. methods=["post", "delete"],
  192. url_path=r"teams/(?P<members_team_slug>[-\w]+)",
  193. )
  194. def teams(self, request, pk=None, organization_slug=None, members_team_slug=None):
  195. """Add existing organization user to a team"""
  196. if not pk or not organization_slug or not members_team_slug:
  197. raise exceptions.MethodNotAllowed(request.method)
  198. pk = self.kwargs.get("pk")
  199. if pk == "me":
  200. org_user = get_object_or_404(self.get_queryset(), user=self.request.user)
  201. else:
  202. queryset = self.filter_queryset(self.get_queryset())
  203. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
  204. filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
  205. org_user = get_object_or_404(queryset, **filter_kwargs)
  206. team = org_user.organization.teams.filter(slug=members_team_slug).first()
  207. # Instead of check_object_permissions
  208. permission = OrganizationMemberTeamsPermission()
  209. if not permission.has_permission(request, self):
  210. self.permission_denied(
  211. request, message=getattr(permission, "message", None)
  212. )
  213. self.check_team_member_permission(org_user, self.request.user, team)
  214. if not team:
  215. raise exceptions.NotFound()
  216. if request.method == "POST":
  217. team.members.add(org_user)
  218. serializer = TeamSerializer(team, context={"request": request})
  219. return Response(serializer.data, status=201)
  220. elif request.method == "DELETE":
  221. team.members.remove(org_user)
  222. serializer = TeamSerializer(team, context={"request": request})
  223. return Response(serializer.data, status=200)
  224. class OrganizationUserViewSet(OrganizationMemberViewSet):
  225. """
  226. Extension of OrganizationMemberViewSet that adds projects the user has access to
  227. API compatible with [get-organization-users](https://docs.sentry.io/api/organizations/get-organization-users/)
  228. """
  229. serializer_class = OrganizationUserProjectsSerializer
  230. class AcceptInviteView(views.APIView):
  231. """Accept invite to organization"""
  232. serializer_class = AcceptInviteSerializer
  233. permission_classes = [permissions.IsAuthenticatedOrReadOnly]
  234. def validate_token(self, org_user, token):
  235. if not InvitationTokenGenerator().check_token(org_user, token):
  236. raise exceptions.PermissionDenied("Invalid invite token")
  237. @swagger_auto_schema(responses={200: AcceptInviteSerializer()})
  238. def get(self, request, org_user_id=None, token=None):
  239. org_user = get_object_or_404(OrganizationUser, pk=org_user_id)
  240. self.validate_token(org_user, token)
  241. serializer = self.serializer_class(
  242. {"accept_invite": False, "org_user": org_user}
  243. )
  244. return Response(serializer.data)
  245. @swagger_auto_schema(responses={200: AcceptInviteSerializer()})
  246. def post(self, request, org_user_id=None, token=None):
  247. org_user = get_object_or_404(OrganizationUser, pk=org_user_id)
  248. self.validate_token(org_user, token)
  249. serializer = self.serializer_class(data=request.data)
  250. serializer.is_valid(raise_exception=True)
  251. if serializer.validated_data["accept_invite"]:
  252. org_user.accept_invite(request.user)
  253. serializer = self.serializer_class(
  254. {
  255. "accept_invite": serializer.validated_data["accept_invite"],
  256. "org_user": org_user,
  257. }
  258. )
  259. return Response(serializer.data)
  260. class OrganizationProjectsViewSet(NestedProjectViewSet):
  261. def get_queryset(self, *args, **kwargs):
  262. queryset = super().get_queryset(*args, **kwargs)
  263. queries = self.request.GET.get("query")
  264. # Pretty simplistic filters that don't match how django-filter works
  265. # If this needs used more extensively, it should be abstracted more
  266. if queries:
  267. for query in queries.split():
  268. query_part = query.split(":", 1)
  269. if len(query_part) == 2:
  270. query_name, query_value = query_part
  271. if query_name == "team":
  272. queryset = queryset.filter(team__slug=query_value)
  273. if query_name == "!team":
  274. queryset = queryset.exclude(team__slug=query_value)
  275. return queryset