views.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from django.shortcuts import get_object_or_404
  2. from rest_framework import exceptions, viewsets
  3. from organizations_ext.models import Organization, OrganizationUserRole
  4. from .models import Team
  5. from .permissions import TeamPermission
  6. from .serializers import TeamSerializer
  7. class NestedTeamViewSet(viewsets.ModelViewSet):
  8. """Teams for an Organization"""
  9. queryset = Team.objects.all()
  10. serializer_class = TeamSerializer
  11. permission_classes = [TeamPermission]
  12. def get_queryset(self):
  13. if self.request.user.is_authenticated:
  14. queryset = self.queryset.filter(organization__users=self.request.user)
  15. organization_slug = self.kwargs.get("organization_slug")
  16. if organization_slug:
  17. queryset = queryset.filter(organization__slug=organization_slug)
  18. return queryset.prefetch_related("members", "projects")
  19. return self.queryset.none()
  20. def perform_create(self, serializer):
  21. try:
  22. organization = Organization.objects.get(
  23. slug=self.kwargs.get("organization_slug"),
  24. users=self.request.user,
  25. organization_users__role__gte=OrganizationUserRole.ADMIN,
  26. )
  27. except Organization.DoesNotExist as org_no_exist:
  28. raise exceptions.ValidationError(
  29. "Organization does not exist"
  30. ) from org_no_exist
  31. if Team.objects.filter(
  32. organization=organization, slug=serializer.validated_data.get("slug")
  33. ).exists():
  34. raise exceptions.ValidationError("Slug must be unique for organization")
  35. team = serializer.save(organization=organization)
  36. org_user = organization.organization_users.filter(
  37. user=self.request.user
  38. ).first()
  39. team.members.add(org_user)
  40. class TeamViewSet(NestedTeamViewSet):
  41. lookup_value_regex = r"(?P<organization_slug>[^/.]+)/(?P<team_slug>[-\w]+)"
  42. def get_object(self):
  43. queryset = self.filter_queryset(self.get_queryset())
  44. obj = get_object_or_404(
  45. queryset,
  46. slug=self.kwargs["team_slug"],
  47. organization__slug=self.kwargs["organization_slug"],
  48. )
  49. # May raise a permission denied
  50. self.check_object_permissions(self.request, obj)
  51. return obj