views.py 2.2 KB

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