Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF Custom permission

Im trying to build a custom permission in Django rest framework -

class GroupBasePermission(permissions.BasePermission):

    group_name = ""

    def has_permission(self, request, view):
        """
        Should simply return, or raise a 403 response.
        """
        print 'self.group_name == ', self.group_name
        try:
            request.user.groups.get(name=self.group_name)    
        except Group.DoesNotExist:
            print 'group does not exist'
            msg = ('Permission denied.')
            data = {'detail': six.text_type(msg)}
            #return Response(data, status=status.HTTP_403_FORBIDDEN)
            return HttpResponseForbidden()

class HRAdminGroupPermission(GroupBasePermission):
    """
        Checks to see if a user is in a particular group
    """

    group_name = "HR Admin1"

and here is my view

class CompanyCreateApiView(LoginRequiredMixin,OTPRequiredMixin,GroupRequiredMixin,CreateAPIView):

    permission_classes = (IsAuthenticated, HRAdminGroupPermission,)
    authentication_classes = (SessionAuthentication,)
    group_required = 'HR Admin1'


    def post(self, request, *args, **kwargs):
        for each in self.request.user.groups.all():
            print 'self.request.user.group == ', each.name

When I call this API using a user(GROUP-- HR ADMIN) it does not throws me 403 forbidden error even though I see the print msg in the permission exception.

How can I fix this issue?

like image 852
user1050619 Avatar asked Dec 22 '15 19:12

user1050619


2 Answers

You must return True if permission is granted, False otherwise in your has_permission method.

like image 186
Aram Avatar answered Oct 13 '22 03:10

Aram


Something like this

class APIPermission(permissions.BasePermission):

    message = 'Only API user can access APIs'

    group_name = "api"

    def has_permission(self, request, view):
        try:
            group = request.user.groups.get(name=self.group_name)
        except Group.DoesNotExist:
            self.message = "Permission denied, user group '{}' does not exists".format(self.group_name)
            return False
        return group.name == self.group_name
like image 33
javed Avatar answered Oct 13 '22 02:10

javed