Skip to main content

New permissions possibilities for rest-framework

Compatibility

Works with :

  • Python 3.8, 3.9, 3.10

  • Django 3.2

  • Django Rest Framework >= 3.13

https://travis-ci.org/unistra/django-rest-framework-fine-permissions.svg?branch=master https://coveralls.io/repos/github/unistra/django-rest-framework-fine-permissions/badge.svg?branch=master Code Health

Installation

Install the package from pypi :

pip install djangorestframework-fine-permissions

Configure your settings.py module :

INSTALLED_APPS = (
    ...
    'rest_framework_fine_permissions',
)

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
        # Enable the filter permission backend for all GenericAPIView
        'rest_framework_fine_permissions.filters.FilterPermissionBackend',
    ),

    'DEFAULT_PERMISSION_CLASSES': (
        # Enable the django model permissions (view,create,delete,modify)
        'rest_framework_fine_permissions.permissions.FullDjangoModelPermissions',
        # OPTIONAL if you use FilterPermissionBackend and GenericAPIView. Check filter permissions for objects.
        'rest_framework_fine_permissions.permissions.FilterPermission',
    )
}

Sync the django’s database :

python manage.py syncdb

Edit your urls.py module :

from django.conf.urls import url
from django.contrib import admin
from rest_framework_fine_permissions.urls import urlpatterns as drffp_urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
urlpatterns += drffp_urls

Usage

  • Go to the django admin page

  • Add field’s permissions to a user with the “User fields permissions” link

  • Add filter’s permissions to a user with the “User filters permissions” link

Example

models.py :

from django.db import models
from django.db.models import Sum

class PollsChoice(models.Model):
    id = models.IntegerField(primary_key=True)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField()
    question = models.ForeignKey('PollsQuestion')

    class Meta:
        permissions = (('view_pollschoice', 'Can view pollschoice'),)

class PollsQuestion(models.Model):
    id = models.IntegerField(primary_key=True)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField()

    class Meta:
        permissions = (('view_pollsquestion', 'Can view pollsquestion'),)

    @property
    def sum_votes(self):
        return self.pollschoice_set.aggregate(total=Sum('votes'))['total']

    @property
    def choices(self):
        return self.pollschoice_set.all()

serializers.py :

import datetime
from django.utils import timezone
from rest_framework import serializers
from rest_framework_fine_permissions.fields import ModelPermissionsField
from rest_framework_fine_permissions.serializers import ModelPermissionsSerializer

from . import models

class PollsChoiceSerializer(ModelPermissionsSerializer):
    class Meta:
        model = models.PollsChoice

class PollsQuestionSerializer(ModelPermissionsSerializer):
    was_published_recently = serializers.SerializerMethodField()
    votes = serializers.IntegerField(source='sum_votes')
    choices = ModelPermissionsField(PollsChoiceSerializer)

    class Meta:
        model = models.PollsQuestion

    def get_was_published_recently(self, obj):
        return obj.pub_date >= timezone.now() - datetime.timedelta(days=1)

views.py :

from . import models
from . import serializers
from rest_framework import generics

class PollsChoiceDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = models.PollsChoice.objects.all()
    serializer_class = serializers.PollsChoiceSerializer

urls.py :

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views

urlpatterns = [,
    url(r'^pollsquestion/(?P<pk>\w+)$', views.PollsQuestionDetail.as_view(), name='pollsquestion-all-detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns, suffix_required=True)

Create a user without the staff and superuser status, and add him permissions :

docs/admin1.png

Then add user field permissions :

docs/admin2.png

You can finally call your webservice :

$ curl -X GET -H "Authorization: Token TOKEN" -H "Accept: application/json; indent=4" http://127.0.0.1/webservice/pollsquestion/1.json
{
    "choices": [
        {
            "choice_text": "Yes",
            "id": 1,
            "votes": 5
        },
        {
            "choice_text": "No",
            "id": 2,
            "votes": 2
        }
    ],
    "id": 1,
    "pub_date": "2017-01-08T09:00:00",
    "question_text": "Is this a question ?",
    "votes": 7,
    "was_published_recently": false
}

Import/Export

To export field’s permissions, you can use the following command :

python manage.py fine_permissions_dump myuser > /tmp/myuserfieldsperms.json

To import field’s permissions, you can use the following command :

python manage.py fine_permissions_load -u anotheruser /tmp/myuserfieldsperms.json

Metadata

Release files for djangorestframework-fine-permissions 0.10.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-fine-permissions 0.10.0
File Size Uploaded Provenance Actions
djangorestframework-fine-permissions-0.10.0.tar.gz 103.6 kB Without provenance Details for djangorestframework-fine-permissions-0.10.0.tar.gz

Release files / djangorestframework-fine-permissions-0.10.0.tar.gz

Download URL djangorestframework-fine-permissions-0.10.0.tar.gz
Size 103.6 kB
Tags Source
SHA-256 checksum
How to use checksums
88f1e3efc65030faf394e71b30c6d97e0ce025d06bed97bedbb2a01001210c53
BLAKE2b-256 checksum
How to use checksums
47be219e3f408b9c97964d9293bbd2c40e49e77ced49e8c9c6a87087fb00ec31
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.8.0 colorama/0.4.4 importlib-metadata/4.6.4 keyring/23.5.0 pkginfo/1.8.2 readme-renderer/34.0 requests-toolbelt/0.9.1 requests/2.25.1 rfc3986/1.5.0 tqdm/4.57.0 urllib3/1.26.5 CPython/3.10.12

Security for djangorestframework-fine-permissions 0.10.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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