Home > Software engineering >  DRF - Prevent users from referencing objects that do not belong to them
DRF - Prevent users from referencing objects that do not belong to them

Time:07-17

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?

CodePudding user response:

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

    def validate_bank(self, bank_instance: Bank):
        if bank_instance.user == self.context["request"].user:
            return bank_instance
        raise serializers.ValidationError("Not belongs to you!!!")
  • Related