Permalink
Browse files

object level permission

  • Loading branch information...
junkboy0315 committed Feb 11, 2019
1 parent 0fc2009 commit 4d345d0063baa692a526ea69466b412fdf61bf08
Showing with 17 additions and 2 deletions.
  1. +12 −0 tutorial/snippets/permissions.py
  2. +5 −2 tutorial/snippets/views.py
@@ -0,0 +1,12 @@
from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
"""
オーナーのみ編集を可能にするカスタム権限
"""

def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
@@ -2,6 +2,7 @@
from rest_framework import generics, permissions
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from snippets.permissions import IsOwnerOrReadOnly


class SnippetList(generics.ListCreateAPIView):
@@ -11,7 +12,8 @@ class SnippetList(generics.ListCreateAPIView):
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly)

# 新規作成(POST)時にはユーザ情報を一緒に保存する
def perform_create(self, serializer):
@@ -24,7 +26,8 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
permission_classes = (
permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)


class UserList(generics.ListAPIView):

0 comments on commit 4d345d0

Please sign in to comment.