1

The problem

I am using Django REST Framework - and so far I have been using the DjangoObjectPermissions permissions class. I use django-rules to determine which users have permissions for objects.

However, this permissions class seems to deny read access to anonymous users.

I need to find the best way to allow read-only access to all users (authenticated or not). For additions, modifications and deletions - the object permissions should be applied as normal.

What is the best approach to solving this problem? Django does not seem to provide a can_view permission by default.

Perhaps this will involve manually adding a can_view permission for each model. Or maybe it's better to somehow implement a DjangoObjectPermissionsOrAnonReadOnly permissions class?

Kieran
  • 2,554
  • 3
  • 26
  • 38

2 Answers2

4

The fix was actually really simple. It's possible to create a custom permissions class extending DjangoObjectPermissions, and to override the authenticated_users_only variable.

class DjangoObjectPermissionsOrAnonReadOnly(DjangoObjectPermissions):
    authenticated_users_only = False
Kieran
  • 2,554
  • 3
  • 26
  • 38
1
from rest_framework import permissions

and Just give

 permission_classes = [permissions.IsAuthenticatedOrReadOnly, YourPermissionshere, ]

in your viewset. That will do the job. if not authenticated, Anonymous users will be getting a read-only permission

you can control when the permissions are checked and not checked by handling the function

self.check_object_permissions(self.request, obj)
Vipul Vishnu av
  • 486
  • 1
  • 5
  • 15
  • permission_classes = [permissions.IsAuthenticatedOrReadOnly, YourPermissionsHere ] – Vipul Vishnu av Aug 24 '16 at 03:04
  • From the DRF Permissions documentation, it sounds like the user has to have permissions in ALL of the permissions classes in order for the check to pass? So, in this case `IsAuthenticatedOrReadOnly` would pass but `YourPermissionsHere` = `DjangoObjectPermissions` would fail? Is this correct? – Kieran Aug 24 '16 at 08:31
  • Yes. All permissions classes should satisfy. you can try the same. It should work. – Vipul Vishnu av Aug 24 '16 at 10:06
  • Sorry but I've tried this and it doesn't work. Anonymous users are refused permission due to the other permissions classes. – Kieran Sep 04 '16 at 15:59