def delete(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) access = UserAccess(request.user) if access.can_edit(post.project): post.delete() return Response(status=status.HTTP_204_NO_CONTENT) else: return Response(status=status.HTTP_404_NOT_FOUND)
def to_representation(self, project): d = super().to_representation(project) try: user = self.context['user'] user_proxy = UserAccess(user) if user_proxy.can_edit(project): d['can_edit'] = True else: d['can_edit'] = False except KeyError: pass return d
def update(self, request, pk=None): tag = get_object_or_404(self.queryset, pk=pk) access = UserAccess(request.user) request.data.pop('project', None) # not allowed to change project if access.can_edit(tag.project): serializer = self.serializer_class(tag, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_404_NOT_FOUND)
def test_create_project_access_owner(self): path = self.access_url.format(self.owned_project.id) data = {'user': self.other_user.id, 'can_edit': True} resp = self.client.post(path, data=data) self.assertEqual(resp.status_code, 201) self.assertIn('can_edit', resp.data) self.assertTrue(resp.data['can_edit']) user = UserAccess(self.other_user) self.assertTrue(user.can_edit(self.owned_project)) self.assertTrue(user.can_view(self.owned_project)) ProjectAccess.objects.get( user=self.other_user, project=self.owned_project, ).delete()
def create(self, request): if 'project' not in request.data: return Response(status=status.HTTP_400_BAD_REQUEST) project = get_object_or_404(Project, pk=request.data['project']) access = UserAccess(request.user) if access.can_edit(project): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_404_NOT_FOUND)
def update(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) access = UserAccess(request.user) # Not allowed to change project or date_created # date_updated is managed automatically request.data.pop('project', None) request.data.pop('date_created', None) request.data.update({'date_updated': timezone.now()}) if access.can_edit(post.project): serializer = self.serializer_class(post, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_404_NOT_FOUND)