简体   繁体   中英

DRF - Prevent users from referencing objects that do not belong to them

I have two models like so with a parent child relation:

models.py

class Bank(...):
    user = models.ForeignKey('User', ...)

class Account(...)
    bank = models.ForeignKey('Bank', ...)
    user = models.ForeignKey('User', ...)

I am using DRF and want to provide API access to these models. I want to ensure that Users can only access their own data. On the viewsets I can retrict the querysets to just the objects the user "owns" like so:

views.py

class BankViewSet(...):

    def get_queryset(self):
        return self.queryset.filter(
            user = request.user
        )

And I can do the same for Accounts .

However, how can I stop a user from creating an Account via POST request with a Bank that they do not own? I want to ensure that users can only create Accounts that belong to a Bank that they own.

How can I enforce/check that the Bank in the Account POST request contains the same user as the requestor?

You can create a field-level validation on the AccountSerializer class, as

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            "bank",
            "field_1",
            "field_2"
        )

    

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