Skip to content

Commit

Permalink
refactor: custom permission for quiblet object
Browse files Browse the repository at this point in the history
  • Loading branch information
moonlitgrace committed Dec 6, 2024
1 parent 5d41473 commit 45f43ac
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
16 changes: 16 additions & 0 deletions backend/apps/quiblet/api/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from rest_framework.permissions import SAFE_METHODS, BasePermission


class IsRangerOrReadOnly(BasePermission):
"""
Custom permission to allow only rangers of a Quiblet to edit it.
"""

def has_object_permission(self, request, view, obj): # type: ignore
if request.method in SAFE_METHODS:
return True

if request.user and request.user.is_authenticated:
return obj.rangers.filter(id=request.user_profile.id).exists()
else:
return False
4 changes: 3 additions & 1 deletion backend/apps/quiblet/api/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

from apps.quiblet.models import Quiblet

from .permissions import IsRangerOrReadOnly
from .serializers import QuibletSerializer


class QuibletViewSet(ModelViewSet):
queryset = Quiblet.objects.all()
serializer_class = QuibletSerializer
permission_classes = (IsRangerOrReadOnly,)

def perform_create(self, serializer):
quibber = self.request.user_profile
quibber = self.request.user_profile # type: ignore
serializer.save(quibber=quibber)
13 changes: 13 additions & 0 deletions backend/shared/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from rest_framework.permissions import SAFE_METHODS, BasePermission


class IsQuibblerOrReadOnly(BasePermission):
"""
Custom permission to allow only quibbler of a feature to edit it.
"""

def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True

return obj.quibbler == request.user_profile

0 comments on commit 45f43ac

Please sign in to comment.