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

2024-04-28

我定义了以下模型

class Flight(models.Model):
    ...

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

以及使用以下视图集NestedViewsetMixin在 REST 框架扩展中

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/.

我想确保人们只能create FlightUpdates如果他们有权限change the Flight对象与FlightUpdate已关联的。

添加时我将如何执行额外检查FlightUpdate?我尝试在视图集中添加类似的内容,但我不确定这是否是最好的方法。

if not request.user.has_perm('flights.change_flight', flight):
    raise PermissionError()

注意:我正在使用django-rules用于对象级别的权限实现。


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

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐