Skip to content

Commit

Permalink
Add permission check for POST method in PostViewSet
Browse files Browse the repository at this point in the history
  • Loading branch information
YaBoyya committed Apr 19, 2024
1 parent 52acd30 commit 808ed5e
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions backend/posts_comments/views.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand All @@ -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]

Expand Down

0 comments on commit 808ed5e

Please sign in to comment.