views.py 12 KB

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