Skip to main content

django-guardian support for Django REST Framework

Project description

django-rest-framework-guardian

CircleCI Codecov License Version Python

django-rest-framework-guardian provides django-guardian integrations for Django REST Framework. Currently, this only includes the ObjectPermissionsFilter.

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 pip setuptools wheel twine
    $ rm -rf dist/ build/
    $ python setup.py bdist_wheel
    $ twine upload dist/*
    

License

See: LICENSE

BSD 3-Clause License

Copyright (c) 2018, Ryan P Kilby All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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.3.0.tar.gz (8.6 kB view details)

Uploaded Source

Built Distribution

djangorestframework_guardian-0.3.0-py2.py3-none-any.whl (6.9 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file djangorestframework-guardian-0.3.0.tar.gz.

File metadata

  • Download URL: djangorestframework-guardian-0.3.0.tar.gz
  • Upload date:
  • Size: 8.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.3

File hashes

Hashes for djangorestframework-guardian-0.3.0.tar.gz
Algorithm Hash digest
SHA256 1883756452d9bfcc2a51fb4e039a6837a8f6697c756447aa83af085749b59330
MD5 094e87bbeb9c28878636f5452980fd1e
BLAKE2b-256 e5800f2190bacfe7c7b2e22d0e1e695882ec3123f9e58817c8392a258cd46442

See more details on using hashes here.

File details

Details for the file djangorestframework_guardian-0.3.0-py2.py3-none-any.whl.

File metadata

  • Download URL: djangorestframework_guardian-0.3.0-py2.py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.3

File hashes

Hashes for djangorestframework_guardian-0.3.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 3bd3dd6ea58e1bceca5048faf6f8b1a93bb5dcff30ba5eb91b9a0e190a48a0c7
MD5 e6c1c3eee9218838aa754b22527e2d65
BLAKE2b-256 9bcc35c1d8fb99172b2646f29e270e9ec443ffe09e0b63e61cd528d4fb4b8b07

See more details on using hashes here.

Supported by

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