DRF

Introduction Of Permission IN DRF

blog image

 

In this tutorial we will learn about the permission in django rest framework.

Permission are used to grant or deny access for different classes of of the users to different parts of API.

permission checks are always run at tha very start of the view, before any other code is allowed to proceed.

permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted.

permission classes

permission in REST Framework are always defined as a list of permisssion classes

.AllowAny                                                               .DjangoModelPermission

.IsAuthenticated                                                   .DjangoObjectPermission

.IsAdminUser                                                          .DjangoModelPermissionOrAnonReadOnly

.IsAuthenticatedOrReadOnly                          .CustomPermission

AllowAny

Allow unrestricted access.

IsAuthenticated

Deny permission to any unauthenticated user

IsAdminUser

Deny permission to any user, unless user.is_staff is True

IsAuthenticatedOrReadOnly

Allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; GETHEAD or OPTIONS.

DjangoModelPermissions

DjangoModelPermissionOrAnonReadonly

CustomPermission

This permission is suitable , if you want your API to only be accessibke to a subset of trusted administrators.

Define Permission Policy

the default permission policy may be set globally in setting.

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

If not defined then it allows unrestricted access

'DEFAULT_PERMISSION_CLASSES': [
   'rest_framework.permissions.AllowAny',
]

You can also set the authentication policy on a per-view, or per-viewset basis.

from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAuthenticated

class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = (IsAuthenticated,)
    http_method_names = ['post', ]

 

Custom Permission

To implement a custom permission , override BasePermission and implemente either or both following methods.

.has_permission(self,request,view)

.has_object_permission(self,request,view,obj)

this method should return True , if the request should be granted access , and False otherwise.

simple example:

class ReadPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user.is_authenticated:
            if request.user.user_type.value == "Super User":
                return True

            test = UserRole.objects.filter(user=request.user.id, user__user_type__value="Staff User", role__value="Read").first()

            if test is None:
                return False

            return True
        return False

 

In above custom permisssion we give only the permission to the user who have the read permission .Similary we can make the Create ,update,delete and other many permission as we want.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


About author

author image

Amrit Panta

Python developer, content writer



3 Comments

Amanda Martines 5 days ago

Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.

Reply

Baltej Singh 5 days ago

Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Marie Johnson 5 days ago

Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Leave a Reply

Scroll to Top