Skip to main content

django-guardian support for Django REST Framework

Project description

django-rest-framework-guardian

build-status codecov License Version Python

django-rest-framework-guardian provides django-guardian integrations for Django REST Framework.

Installation & Setup

To use django-rest-framework-guardian, install it into your environment.

$ pip install djangorestframework-guardian

Ensure both Django REST Framework and django-guardian are configured and added to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    'rest_framework',
    'guardian',
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
]

ObjectPermissionsFilter

The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.

If you're using ObjectPermissionsFilter, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass DjangoObjectPermissions and add 'view' permissions to the perms_map attribute.

An example using both ObjectPermissionsFilter and DjangoObjectPermissions might look like the following:

permissions.py:

from rest_framework import permissions


class CustomObjectPermissions(permissions.DjangoObjectPermissions):
    """
    Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
    """
    perms_map = {
        'GET': ['%(app_label)s.view_%(model_name)s'],
        'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
        'HEAD': ['%(app_label)s.view_%(model_name)s'],
        'POST': ['%(app_label)s.add_%(model_name)s'],
        'PUT': ['%(app_label)s.change_%(model_name)s'],
        'PATCH': ['%(app_label)s.change_%(model_name)s'],
        'DELETE': ['%(app_label)s.delete_%(model_name)s'],
    }

views.py:

from rest_framework import viewsets
from rest_framework_guardian import filters

from myapp.models import Event
from myapp.permissions import CustomObjectPermissions
from myapp.serializers import EventSerializer


class EventViewSet(viewsets.ModelViewSet):
    """
    Viewset that only lists events if user has 'view' permissions, and only
    allows operations on individual events if user has appropriate 'view', 'add',
    'change' or 'delete' permissions.
    """
    queryset = Event.objects.all()
    serializer_class = EventSerializer
    permission_classes = [CustomObjectPermissions]
    filter_backends = [filters.ObjectPermissionsFilter]

ObjectPermissionsAssignmentMixin

A serializer mixin that allows permissions to be easily assigned to users and/or groups. So each time an object is created or updated, the permissions_map returned by Serializer.get_permissions_map will be used to assign permission(s) to that object.

Please note that the existing permissions will remain intact.

A usage example might look like the following:

from rest_framework_guardian.serializers import ObjectPermissionsAssignmentMixin

from blog.models import Post


class PostSerializer(ObjectPermissionsAssignmentMixin, serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

    def get_permissions_map(self, created):
        current_user = self.context['request'].user
        readers = Group.objects.get(name='readers')
        supervisors = Group.objects.get(name='supervisors')

        return {
            'view_post': [current_user, readers],
            'change_post': [current_user],
            'delete_post': [current_user, supervisors]
        }

Release Process

  • Update changelog
  • Update package version in setup.py
  • Create git tag for version
  • Build & upload release to PyPI
    $ pip install -U setuptools build twine
    $ rm -rf dist/
    $ python -m build
    $ twine upload -r test dist/*
    $ twine upload dist/*
    

License

See: LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

djangorestframework_guardian-0.4.0.tar.gz (8.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

djangorestframework_guardian-0.4.0-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file djangorestframework_guardian-0.4.0.tar.gz.

File metadata

File hashes

Hashes for djangorestframework_guardian-0.4.0.tar.gz
Algorithm Hash digest
SHA256 a8113659e062f65b74cc31af6982420c382642e782d38581b3fdc748a179756c
MD5 3804b933b13c6516e60796073d543cf3
BLAKE2b-256 c1c467df9963395e9dddd4e16cbf75098953798e5135f73fb8f4855895505e39

See more details on using hashes here.

File details

Details for the file djangorestframework_guardian-0.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for djangorestframework_guardian-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 30c2a349318c1cd603d6953d50d58159f9a0c833f5f8f5a811407d5984a39e14
MD5 f2f0038a090cf6931eaa4079bea9f31f
BLAKE2b-256 59813d62f7ff71f7c45ec6664ebf03a4c736bf77f49481604361d40f8f4471e4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page