DRF自定义权限

时间:2015-12-22 19:57:18

标签: django django-rest-framework

我试图在Django休息框架中构建自定义权限 -

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"

这是我的观点

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

当我使用用户(GROUP-- HR ADMIN)调用此API时,即使我在权限异常中看到print msg,它也不会抛出403 forbidden错误。

如何解决此问题?

2 个答案:

答案 0 :(得分:2)

如果授予了权限,则必须返回True,否则将在您的has_permission方法中返回False

答案 1 :(得分:2)

类似这样的东西

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