Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object-level permissions django

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.

like image 437
9-bits Avatar asked Jan 21 '12 02:01

9-bits


1 Answers

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

like image 52
S.Lott Avatar answered Sep 28 '22 02:09

S.Lott