object level permissions, basic auth flow achvd

This commit is contained in:
Pratyush Desai 2022-01-08 05:29:03 +05:30
parent 17f5199fa1
commit eb24f56b7c
Signed by: pratyush
GPG Key ID: DBA5BB7505946FAD
2 changed files with 17 additions and 1 deletions

View File

@ -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

View File

@ -2,6 +2,7 @@ from django.contrib.auth.models import User
from .models import Snippet from .models import Snippet
from .serializers import SnippetSerializer, UserSerializer from .serializers import SnippetSerializer, UserSerializer
from .permissions import IsOwnerOrReadOnly
from rest_framework import generics, permissions from rest_framework import generics, permissions
class SnippetList(generics.ListCreateAPIView): class SnippetList(generics.ListCreateAPIView):
@ -16,7 +17,7 @@ class SnippetList(generics.ListCreateAPIView):
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly] permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
class UserList(generics.ListAPIView): class UserList(generics.ListAPIView):
queryset = User.objects.all() queryset = User.objects.all()