Skip to main content

Manage object permissions by defining methods in Django Model

Project description

django-reinhardt

https://img.shields.io/pypi/v/django-reinhardt.svg https://img.shields.io/travis/momamene/django-reinhardt.svg Documentation Status Updates

There are many object permission backends like django-guardian or django-permission.

But some time, it is needed to define permissions as not just object-user relationship.

django-reinhardt make you handle object permissions by defining methods in your django model

Installation

Use pip like:

$ pip install django-reinhardt

Usage

Add extra authorization backends in your settings.py:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', # default
    'reinhardt.backends.PermissionBackend',
)

It’s done. you don’t need to add any app or migrate anything.

Assume that Inquiry model needs to have two permission: change_inqury, view_inquiry

class Inquiry(models.Model):

    writer = models.ForeignKey(settings.AUTH_USER_MODEL)
    text = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)

    def can_change_inquiry(self, user):
        return self.writer == user

    def can_view_inquiry(self, user):
        return self.writer == user or user.is_staff

Then you can just define can_change_inquiry and can_view_inquiry ( can_ is prefix to distinguish permission-related method from others ), which have user instance parameter.

Now the following codes will work as expected:

user1 = get_user_model().objects.create(
    username='nanase'
)
user2 = get_user_model().objects.create(
    username='maiyan'
)
user3 = get_user_model().objects.create(
    username='ikuta'
)
inquiry = Inquiry.objects.create(
    writer=self.user1,
    text='How can I delete my account?'
)

assert user1.has_perm('yourapp.change_inquiry', obj=inquiry) == True
assert user2.has_perm('yourapp.view_inquiry', obj=inquiry) == False
assert user3.has_perm('yourapp.change_inquiry', obj=inquiry) == False
assert user3.has_perm('yourapp.view_inquiry', obj=inquiry) == True

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

History

0.1.0 (2016-07-19)

  • First release on PyPI.

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

django-reinhardt-0.1.0.tar.gz (12.2 kB view hashes)

Uploaded Source

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