From 808ed5e92c9897f4bc321bdb6e0b8428b2016985 Mon Sep 17 00:00:00 2001 From: Amadeusz Date: Fri, 19 Apr 2024 12:39:03 +0200 Subject: [PATCH] Add permission check for POST method in PostViewSet --- backend/posts_comments/views.py | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/backend/posts_comments/views.py b/backend/posts_comments/views.py index 17855bf..47da87a 100644 --- a/backend/posts_comments/views.py +++ b/backend/posts_comments/views.py @@ -1,8 +1,10 @@ -from rest_framework import permissions +from rest_framework import exceptions, permissions from rest_framework import mixins, viewsets from events.permissions import IsEventModerator +from events.models import Role + from posts_comments import models, serializers from posts_comments.permissions import IsOwner @@ -14,16 +16,31 @@ def get_queryset(self): return models.Post.objects.all() def get_permissions(self): - permission_classes = [permissions.AllowAny] - if self.action in ['list', 'retrieve']: + if self.request.method in permissions.SAFE_METHODS: permission_classes = [permissions.AllowAny] - elif self.action in ['create', 'update', 'partial_update', 'destroy']: + else: permission_classes = [ permissions.IsAuthenticated, IsEventModerator ] + print(permission_classes) return [permission() for permission in permission_classes] + def perform_create(self, serializer): + event = serializer.validated_data.get('event') + + try: + role = Role.objects.get(event=event, user=self.request.user) + except Role.DoesNotExist: + msg = "You do not have permission to perform this action." + raise exceptions.PermissionDenied(msg) + + if int(role.name) >= Role.NameChoice.MODERATOR: + msg = "You do not have permission to perform this action." + raise exceptions.PermissionDenied(msg) + + return super().perform_create(serializer) + class CommentViewSet(viewsets.ModelViewSet): serializer_class = serializers.CommentSerializer @@ -32,9 +49,9 @@ def get_queryset(self): return models.Comment.objects.all() def get_permissions(self): - if self.action in ['list', 'retrieve']: + if self.request.method in permissions.SAFE_METHODS: permission_classes = [permissions.AllowAny] - elif self.action in ['create', 'update', 'partial_update', 'destroy']: + else: permission_classes = [IsOwner] return [permission() for permission in permission_classes]