检查Django REST Framework中相关对象的权限

时间:2016-03-08 23:08:12

标签: python django permissions django-rest-framework

我定义了以下模型

class Flight(models.Model):
    ...

class FlightUpdate(models.Model):
    flight = models.ForeignKey('Flight', related_name='updates')
    ...

以及使用REST Framework Extensions中的NestedViewsetMixin的以下视图集

class FlightUpdateViewSet(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      NestedViewSetMixin,
                      viewsets.GenericViewSet):
    """
    API Endpoint for Flight Updates
    """
    queryset = FlightUpdate.objects.all()
    serializer_class = FlightUpdateSerializer

    def create(self, request, *args, **kwargs):
        flight = Flight.objects.get(pk=self.get_parents_query_dict()['flight'])
        ...

因此,要访问与FlightUpdates相关联的Flight,网址为/flights/1/updates/

我想确保人们只有创建 FlightUpdates才有权更改 Flight FlightUpdate对象FlightUpdate 1}}是关联的。

添加if not request.user.has_perm('flights.change_flight', flight): raise PermissionError() 时如何进行额外检查?我尝试在视图集中添加这样的内容,但我不确定它是否是最佳方式。

django-rules

注意:我使用openssl进行对象级权限实现。

1 个答案:

答案 0 :(得分:1)

我通过实现自定义权限类解决了这个问题。

from django.core.exceptions import ObjectDoesNotExist

from rest_framework.permissions import BasePermission, SAFE_METHODS

from .models import Flight


class FlightPermission(BasePermission):

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

        try:
            flight = Flight.objects.get(pk=view.kwargs['parent_lookup_flight'])
        except ObjectDoesNotExist:
            return False

        return request.user.has_perm('flights.change_flight', flight)