Home > OS >  is it safe to compare owner_id to request.user.id for authentication in django?
is it safe to compare owner_id to request.user.id for authentication in django?

Time:11-19

in my app I have the model:

class Meal(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=500)
    carbohydrates = models.FloatField()
    protein = models.FloatField()
    fat = models.FloatField()
    fiber = models.FloatField()
    owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)

the following serializer:

class MealSerializer(serializers.ModelSerializer):
    class Meta:
        model = Meal
        fields = "__all__"

and this viewset:

class MealViewSet(viewsets.ModelViewSet):
    queryset = Meal.objects.all()
    serializer_class = MealSerializer
    
    def get_queryset(self):
        return Meal.objects.filter(owner_id=self.request.user.id)

And now I have a question, is it safe to compare owner_id=self.request.user.id in get_queryset method for authentication?

or is it possible somehow to specify user.id in request e.g. using postman and pull all Meal objects?

for example: Is that possible in postman or somewhere else?

I am a beginner in django and rarely used postman. Sorry if I wrote something wrong, English is not my native language.

CodePudding user response:

I'm not sure it will work. In filter, you have to write owner=self.request.user (preferred and safe). Or, if you really want to bother with IDs: owner__id=self.request.user.id.

Diving into self.request.user fields is a bit dangerous, because in case some non-authenticated user will get there — your code will crash.

CodePudding user response:

In short, in general it is safe to compare. This has been asked before: Django/Auth: Can request.user be exploited and point to other user?

  • Related