From eb24f56b7cb8b761d7614d2194b3576668252386 Mon Sep 17 00:00:00 2001 From: Pratyush Desai Date: Sat, 8 Jan 2022 05:29:03 +0530 Subject: [PATCH] object level permissions, basic auth flow achvd --- website/snippets/permissions.py | 15 +++++++++++++++ website/snippets/views.py | 3 ++- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 website/snippets/permissions.py diff --git a/website/snippets/permissions.py b/website/snippets/permissions.py new file mode 100644 index 0000000..3188270 --- /dev/null +++ b/website/snippets/permissions.py @@ -0,0 +1,15 @@ +from rest_framework import permissions + +class IsOwnerOrReadOnly(permissions.BasePermission): + """ + Custom permission to only allow owners of an object to edit it. + """ + + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request, + # so we'll always allow GET, HEAD or OPTIONS requests. + if request.method in permissions.SAFE_METHODS: + return True + + # Write permissions are only allowed to the owner of the snippet. + return obj.owner == request.user \ No newline at end of file diff --git a/website/snippets/views.py b/website/snippets/views.py index d27c23a..a04cc15 100644 --- a/website/snippets/views.py +++ b/website/snippets/views.py @@ -2,6 +2,7 @@ from django.contrib.auth.models import User from .models import Snippet from .serializers import SnippetSerializer, UserSerializer +from .permissions import IsOwnerOrReadOnly from rest_framework import generics, permissions class SnippetList(generics.ListCreateAPIView): @@ -16,7 +17,7 @@ class SnippetList(generics.ListCreateAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer - permission_classes = [permissions.IsAuthenticatedOrReadOnly] + permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] class UserList(generics.ListAPIView): queryset = User.objects.all()