简体   繁体   中英

Django REST Framework - How to quickly checks user permissions?

I usually use the permission_required the decorator to quickly deny users from accessing the view.

from django.contrib.auth.decorators import permission_required

@permission_required('my_app.view_mymodel',login_url='/sign_in/')
def my_view(request):
    ...

Now, I'm using DRF and I'm trying to find a proper way to checks user permissions. Right now, I'm using the DjangoModelPermissions which is fine, but since it works according to the defined view's queryset, sometimes I need to checks permissions that are not the ones defined for the view's queryset.

Is there a way to quickly check permissions just by providing a list of perms' strings?

Note: I know that I can extend BasePermission and define my own logic, but would produce a lot of classes.

It works for me like this:

within your views:

from rest_framework.decorators import api_view
from .permissions import permission_required

@api_view(['GET'])
@permission_required('permission')
def do_something(request):
    pass

within permissions:

from rest_framework.permissions import BasePermission
from rest_framework.decorators import permission_classes

def permission_required(perm):
    def has_permission(self, request, view):
        return request.user.has_perm(perm)
    Can = type(
        'WrappedAPIView',
        (BasePermission,),
        {'message': 'You can not do ' + perm,
        'has_permission': has_permission}
    )
    def decorator(func):
        func.permission_classes = [Can]
        return func
    return decorator

You can achieve this by using the DRF 's decorators ( @api_view and @permission_classes ):

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
# At first, you should define your view as an API view
# by using the @api_view decorator

@permission_classes((IsAuthenticated, ))
# With the @permission_classes decorator you can provide a tuple
# with the desired permissions for this view

def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

And now your example_view can be accessed only by authenticated users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM