object-level permissions django
Asked Answered
L

1

6

How do you ensure that a User can only edit objects they've created? What's the best way to set this up?

I'm using django-rest-framework and wondering if there's a way I can restrict users from viewing/ editing objects they don't 'own'.

class Video(models.Model):
    owner = models.ForeignKey(User)
    ...

So User 'x' should only be able to edit videos in their owner_set.

Leporide answered 21/1, 2012 at 2:0 Comment(2)
How do you define user "ownership" of an object? Please include enough of your models that we can see what you're talking about.Noticeable
@Noticeable just updated to include this.Leporide
N
3

Presumably you have sessions and the auth model turned on.

You must be sure that all views (REST and non-REST) require authentication.

For non-REST, it's easy. You simply use a basic @login-required decorator everywhere.

For the Django-REST Framework, read this: http://django-rest-framework.org/library/authentication.html#module-authentication.

You have to use the authentication mixin to be sure that authentication actually happened.

The framework supports BASIC Authentication, which requires an SSL connection to be secure. It's not too difficult to implement DIGEST authentication, which doesn't require SSL.

Avoid sessions. It violates a principle of REST to login and logout. The framework supports sessions, but it's less than ideal.

Once you have all requests authenticated, you'll know the user.

If you know the user, then user.video_set works perfectly. You can also use Video.objects.filter(...) to be sure that you're querying the user, but it's easier to confirm the code is correct if you work with user.video_set.get(...) or user.video_set.filter() or whatever.

All the relevant authorization checking is done in Views. You're providing Views for your ModelResources.

These are "class-based views". Documentation is here: https://docs.djangoproject.com/en/dev/topics/class-based-views/#viewing-subsets-of-objects

The trick is to pick all the right mixing and serializers.

For example, you can mixing get processing this way:

http://django-rest-framework.org/howto/mixin.html

You'll implement the filter in the get method

Noticeable answered 21/1, 2012 at 2:17 Comment(1)
Thanks so much for the thorough answer! I'm still wondering where the appropriate place is to put the code that filters based on user? I just began using Django-REST and am having trouble figuring that out...Leporide

© 2022 - 2024 — McMap. All rights reserved.