Home > Mobile >  Custom permissions in django isn't working
Custom permissions in django isn't working

Time:05-09

I want to add custom permissions:

  1. Only admin and owner of the object can modify the object
  2. All registered users can view the objects

My solution:

SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')

class IsApplicationAdmin(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user.is_authenticated:
            if request.user.is_superuser or request.user.user_type == "Admin":
                return True
            if request.method in SAFE_METHODS:
                return True

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

        return obj.user_name == request.user # owner can modify the object

PROBLEM -- for PATCH request (partial update) http://127.0.0.1:8000/api/admin_panel/users/2/ I have this error

{
    "detail": "You do not have permission to perform this action."
}

I was debugging the code and see debugging log only in has_permission (no logs in has_object_permission)

What should I fix?

I was reading https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions and the table said that PATH request relates to object permissions

CodePudding user response:

Custom permissions and authentication should be checked in the below manner

from rest_framework import permissions  
from rest_framework.permissions import IsAuthenticated

class IsApplicationAdmin(IsAuthenticated):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS or request.user.is_superuser:
            return True
        return obj.user_name == request.user.username # I think you want to check usernames here because on left side its obj.user_name ?

Please try with this approach and then let me know if there is some issue.

  • Related