Django object level permissions

How do you guarantee that the User can only edit objects created by them? What is the best way to configure this?

I am using the django-rest-framework and wondering if there is a way to restrict users from viewing / editing objects that they do not have.

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

Thus, the user 'x' should be able to edit the video only in his owner_set.

+6
source share
1 answer

Presumably you have sessions and the auth model is enabled.

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

For non-REST, this is easy. You just use the basic @login-required decorator everywhere.

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

You must use the authentication method to verify that authentication has indeed occurred.

The framework supports BASIC Authentication, which requires a secure SSL connection. It is not too difficult to implement DIGEST authentication, which does not require SSL.

Avoid sessions. It violates the REST principle for logging in and logging out. The structure supports sessions, but it is less than ideal.

After all requests are authenticated, you will recognize the user.

If you know the user, then user.video_set works user.video_set fine. You can also use Video.objects.filter(...) to make sure that you are requesting a user, but it is easier to confirm that the code is correct if you are working with user.video_set.get(...) or user.video_set.filter() or any other.

All necessary authorization checks are performed in Views. You provide Views for your models.

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

The trick is to select all the right mixers and serializers.

For example, you can mix processing in this way:

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

You implement a filter in the get method

+2
source

Source: https://habr.com/ru/post/906519/


All Articles