[19 | カテゴリー実装] << [ホーム] >> [21 | react-icons]
登録したユーザーのみが変更できるようpermissionを追加します。
「qrmenu_server/qrmenucore」フォルダに「permissions.py」ファイルを新規作成します。
新規作成 【QRMenu/qrmenu_server/qrmenucore/permissions.py】
import json from rest_framework import permissions from . import models class IsOwnerOrReadOnly(permissions.BasePermission): 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 place. return obj.owner == request.user class PlaceOwnerOrReadOnly(permissions.BasePermission): 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 place. return obj.place.owner == request.user def has_permission(self, request, view): try: if request.method == "POST": # for create action data = json.loads(request.body) models.Place.objects.get(pk=data["place"], owner_id=request.user.id) return True except: return False
「qrmenucore/views.py」ファイルを編集します。
記述編集 【QRMenu/qrmenu_server/qrmenucore/views.py】
from rest_framework import generics from . import models, serializers, permissions # Create your views here. class PlaceList(generics.ListCreateAPIView): serializer_class = serializers.PlaceSerializer def get_queryset(self): return models.Place.objects.filter(owner_id=self.request.user.id) def perform_create(self, serializer): serializer.save(owner=self.request.user) class PlaceDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [permissions.IsOwnerOrReadOnly] serializer_class = serializers.PlaceDetailSerializer queryset = models.Place.objects.all() class CategoryList(generics.CreateAPIView): permission_classes = [permissions.PlaceOwnerOrReadOnly] serializer_class = serializers.CategorySerializer class CategoryDetail(generics.UpdateAPIView, generics.DestroyAPIView): permission_classes = [permissions.PlaceOwnerOrReadOnly] serializer_class = serializers.CategorySerializer queryset = models.Category.objects.all() class MenuItemList(generics.CreateAPIView): permission_classes = [permissions.PlaceOwnerOrReadOnly] serializer_class = serializers.MenuItemSerializer class MenuItemDetail(generics.UpdateAPIView, generics.DestroyAPIView): permission_classes = [permissions.PlaceOwnerOrReadOnly] serializer_class = serializers.MenuItemSerializer queryset = models.MenuItem.objects.all()
ブラウザで確認します。
http://127.0.0.1:8000/api/places/1
OPTIONSで何でもいいので入力してPUTしてみると、パーミッションエラーが出るようになりました。
これで登録したユーザー以外は変更できないようになりました。
↓↓クリックして頂けると励みになります。
[19 | カテゴリー実装] << [ホーム] >> [21 | react-icons]