Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework - Custom Permissions not Evaluating

I'm trying to set custom permissions on a class that extends viewsets.ModelViewSet and it appears that my permissions are not being evaluated. Here is my view:

from rest_framework import viewsets
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated

import models
import serializers
from permissions import IsAdminOrAuthenticatedReadOnly

class KPIViewSet(viewsets.ModelViewSet):
    '''
    API endpoint that allows KPI metadata to be viewed or edited
    '''

    authentication_classes = (BasicAuthentication,)
    permission_classes = (IsAdminOrAuthenticatedReadOnly,)

    queryset = models.KPI.objects.all()
    serializer_class = serializers.KPISerializer

And here is my permission class:

from rest_framework.permissions import BasePermission, SAFE_METHODS

class IsAdminOrAuthenticatedReadOnly(BasePermission):
    def has_permissions(self, request, view):

        if request.method in SAFE_METHODS:
            return request.user and request.user.is_authenticated()

        return request.user and request.user.is_staff()

The problem I'm running into is that IsAdminOrAuthenticatedReadOnly never seems to get evaluated. I tested this both by forcing it to always return "False" and by switching the permission_classes value to "IsAuthenticated" in the view. In the former scenario, a request to the endpoint returns as if there were no authentication requirement. In the later, authentication is enforced as expected.

Any ideas what I'm missing?

like image 922
Daniel Hostetler Avatar asked Nov 20 '25 22:11

Daniel Hostetler


1 Answers

The method name is has_permission not has_permissions (no s) ;)

like image 199
Alex T Avatar answered Nov 22 '25 17:11

Alex T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!