Skip to main content

django-rest-framework-guardian2

GitHub Actions License Version Python

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

Installation & Setup

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

$ pip install djangorestframework-guardian2

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.cfg
  • Create git tag for version
  • Build & upload release to PyPI
    $ rm -rf dist/ build/
    $ pip install -U build twine
    $ python -m build
    $ twine upload -r test dist/*
    $ 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.

Release files for djangorestframework-guardian2 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for djangorestframework-guardian2 0.7.0
File Size Uploaded
djangorestframework_guardian2-0.7.0.tar.gz 9.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for djangorestframework-guardian2 0.7.0
File Interpreter ABI Platform
djangorestframework_guardian2-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 16.2 kB

Release files / djangorestframework_guardian2-0.7.0.tar.gz

Download URL djangorestframework_guardian2-0.7.0.tar.gz
Size 9.2 kB
Tags Source
SHA-256 checksum
How to use checksums
9cb8c9cc8bd51ed2429282a21517cafbb8b815be0d0b62a163530fd113534a52
BLAKE2b-256 checksum
How to use checksums
0299a608d05ad7c4ccd197fc5ef74efd3cce85f338a65d7a84b6970813012e06
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.10.11

Release files / djangorestframework_guardian2-0.7.0-py3-none-any.whl

Download URL djangorestframework_guardian2-0.7.0-py3-none-any.whl
Size 7.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eaae5762ebdead443e64a1ea95a53243446ab51e0b96662cfe74fe3f4f140bd9
BLAKE2b-256 checksum
How to use checksums
08c6e22b0a573336d7e704867ea0fac3b2d7f76379093f0e491e3baf702cd352
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.10.11

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page