Fix permission

This commit is contained in:
jhyns 2023-05-17 16:10:25 +09:00
parent 75adb90d50
commit 0739171afa
3 changed files with 23 additions and 12 deletions

View File

@ -9,3 +9,12 @@ class IsAuthorOrReadOnly(BasePermission):
and request.user.is_authenticated
and obj.author == request.user
)
class IsAdminUserOrReadOnly(BasePermission):
def has_permission(self, request, view):
return bool(
request.method in SAFE_METHODS
or request.user
and request.user.is_staff
)

View File

@ -38,6 +38,14 @@ class ProductSerializer(ModelSerializer):
fields = ("id", "name", "brand", "colors", "storages")
class ProductListSerializer(ModelSerializer):
brand = serializers.CharField(source="brand.name")
class Meta:
model = Product
fields = ("id", "name", "brand")
class ImageSerializer(ModelSerializer):
class Meta:
model = Image
@ -45,8 +53,10 @@ class ImageSerializer(ModelSerializer):
class PostSerializer(ModelSerializer):
product = ProductListSerializer(read_only=True)
nickname = serializers.CharField(source="author.nickname")
images = ImageSerializer(many=True, read_only=True)
storage = serializers.CharField(source="storage.storage")
class Meta:
model = Post

View File

@ -4,7 +4,7 @@ from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from core.mixins import ActionBasedMixin
from core.permissions import IsAuthorOrReadOnly
from core.permissions import IsAuthorOrReadOnly, IsAdminUserOrReadOnly
from market.models import Brand, Product, Post
from market.serializers import (
BrandSerializer,
@ -19,15 +19,11 @@ class BrandViewset(ActionBasedMixin, ModelViewSet):
serializer_class_map = {
"products": ProductSerializer,
}
permission_classes = [IsAdminUser]
permission_classes_map = {
"list": [AllowAny],
"retrieve": [AllowAny],
}
permission_classes = [IsAdminUserOrReadOnly]
pagination_class = None
@action(detail=True, methods=["GET"])
def products(self, request, pk):
def product(self, request, pk):
brand = self.get_object()
serializer = self.get_serializer(brand.products.all(), many=True)
return Response(serializer.data)
@ -39,11 +35,7 @@ class ProductViewset(ActionBasedMixin, ModelViewSet):
serializer_class_map = {
"posts": PostSerializer,
}
permission_classes = [IsAdminUser]
permission_classes_map = {
"list": [AllowAny],
"retrieve": [AllowAny],
}
permission_classes = [IsAdminUserOrReadOnly]
@action(detail=True, methods=["GET"])
def posts(self, request, pk):