Code Monkey home page Code Monkey logo

django-rest-framework-guardian2's Introduction

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

django-rest-framework-guardian2's People

Contributors

hemache avatar johnthagen avatar roconda avatar rpkilby avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

django-rest-framework-guardian2's Issues

`DEFAULT_AUTO_FIELD` warnings during testing

  WARNINGS:
  tests.BasicModel: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
  	HINT: Configure the DEFAULT_AUTO_FIELD setting or the AppConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
  tests.BasicPermModel: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
  	HINT: Configure the DEFAULT_AUTO_FIELD setting or the AppConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.