在Django REST Framework中检查相关对象的权限 [英] Check permissions on a related object in Django REST Framework

查看:139
本文介绍了在Django REST Framework中检查相关对象的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下模型

class Flight(models.Model):
    ...

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

和以下使用REST Framework扩展中的NestedViewsetMixin的视图集

and the following viewset using the NestedViewsetMixin in the REST Framework Extensions

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'])
        ...

因此,要访问与Flight关联的FlightUpdates,URL为/flights/1/updates/.

So, to access the FlightUpdates associated with a Flight, the URL is /flights/1/updates/.

我想确保只有在有权更改FlightUpdate关联的Flight对象的人的情况下,他们才能创建 FlightUpdates.

I want to ensure that people can only create FlightUpdates if they have the permissions to change the Flight object with which the FlightUpdate is associated.

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

How would I go about performing the extra check when adding a FlightUpdate? I've tried adding something like this in the viewset, but I'm not sure if it's the best way.

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

注意:我正在使用django-rules进行对象级权限的实现.

Note: I'm using django-rules for the object-level permissions implementation.

推荐答案

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

I solved this problem by implementing a custom permissions class.

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)

这篇关于在Django REST Framework中检查相关对象的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆