django-rules
django-rules copied to clipboard
Document usage of simple group membership on views
Documentation of the decorator for permissions on views is good, but focuses on views with passed-in objects and a user's permissions to access them. The simpler case, where you have set up group membership rules with django-rules and want to protect an entire view based on group membership, is not obvious.
I finally figured out that django-rules can be used in conjunction with Django's user_passes_test. I recommend adding to that section of the documentation something like this:
If you want to protect an entire view with a rules decorator, irrespective of any particular object, django-rules can be used in conjunction with Django's user_passes_test decorator. Rather than using the permission_required, use something like:
from django.contrib.auth.decorators import user_passes_test
import rules
is_participant = rules.is_group_member('Participants')
@user_passes_test(is_participant)
def participant_sample(request):
....
I think you're somewhat confused. You're not testing for permissions in your example and while what you have should work, the following might make things slightly clearer. Here's how I'd do the same thing as you're trying to do, but with Django permissions:
import rules
is_participant = rules.is_group_member('Participants')
rules.add_perm('can_access_view', is_participant)
@rules.permission_required('can_access_view')
def participant_sample(request):
....
Ah! Thanks much for clarifying. Yes that's much better. I didn't quite get that from the docs but maybe that was my own uncareful reading. Possibly worth adding that simple case to the docs as well? Cheers.
Slight change to the above (if you do want to document) - there is no @rules.permission_required. Should be:
import rules
from rules.contrib.views import permission_required
is_participant = rules.is_group_member('Participants')
rules.add_perm('can_access_view', is_participant)
@permission_required('can_access_view')
def participant_sample(request):
...