views.py 11 KB

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