简体   繁体   中英

Check permissions on a related object in Django REST Framework

I have defined the following models

class Flight(models.Model):
    ...

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

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

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

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.

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()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM