Giter Site home page Giter Site logo

duilio / django-permission Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jazzband/django-permission

1.0 1.0 0.0 1.3 MB

An enhanced permission system which support object permission in Django

Home Page: http://pypi.python.org/pypi/django-permission/

Python 100.00%

django-permission's Introduction

djagno-permission

django-permission is an enhanced permission system which support object permission and role based permission system.

This is under development. The codes below may not works in the future

Install

django-permission is in PyPI so:

$ pip install django-permission

or

$ pip install git+git://github.com/lambdalisue/django-permission.git#egg=django-permission

Quick tutorial

  1. Add 'permission' to INSTALLED_APPS of your settings.py and confirm ''django.contrib.auth' and 'django.contrib.contenttypes' is in INSTALLED_APPS

    Note

    django-permission can use django-fenicms to improve the visual design of change_list page in django admin if available. Add 'fenicms' to your INSTALLED_APPS to enable AJAX sorting, adding, expanding features.

  2. Add 'permission.backends.PermissionBackend' to AUTHENTICATION_BACKENDS of your settings.py. If you cannot existing settings, simply add following code:

    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'permission.backends.RoleBackend',
        'permission.backends.PermissionBackend',
    )
  3. Add permissions.py to the directory which contains models.py. And write following codes for starting:

    from permission import registry
    from permission import PermissionHandler
    
    from models import YourModel
    
    class YourModelPermissionHandler(PermissionHandler):
        """Permission handler class for ``YourModel``. Similar with AdminSite"""
        def has_perm(self, user_obj, perm, obj=None):
            """this is called for checking permission of the model."""
            if user_obj.is_authenticated():
                if perm == 'yourapp.add_yourmodel':
                    # Authenticated user has add permissions of this model
                    return True
                elif obj and obj.author == user_obj:
                    # Otherwise (change/delete) user must be an author
                    return True
            # User doesn't have permission of ``perm``
            return False
    
    # register this ``YourModelPermissionHandler`` with ``YourModel``
    registry.register(YourModel, YourModelPermissionHandler)
  4. has and of keyword is added to if in template. You can check permission as:

    {% if user has 'blog.add_entry' %}
    <p>You can add entry</p>
    {% endif %}
    {% if object and user has 'blog.change_entry' of object or user has 'blog.delete_entry' of object %}
    <!-- object is exist and user can change or delete this object. -->
    <div class="control-panel">
        {% if user has 'blog.change_entry' of object %}
        <p>You can change this entry.</p>
        {% endif %}
        {% if user has 'blog.delete_entry' of object %}
        <p>You can delete this entry.</p>
        {% endif %}
    </div>
    {% endif %}

    Note

    If you don't want django-permission to replace builtin if tag, set PERMISSION_REPLATE_BUILTIN_IF to False in your settings.py. Then you have to use {% permission %} templatetag as:

    {% permission user has 'blog.add_entry' %}

    <p>You can add entry</p> {% endpermission %}

    {% permission %} tag is exactuly same as {% if %} thus you can use {% elpermission %} for {% elif %} and {% else %}.

Role?

django-permission has role based permission system. visit your django admin page to create/modify roles (See the screenshots below). The role permissions are handled with permission.backends.RoleBackend.

image

image

Note

Role based permission system does not support object permission and anonymous permission. However these permissions are handled with Individual handler based permission backend (permission.backends.PermissionBackend)

Regulate permissions treated in PermissionHandler

PermissionHandler treat all permissions related to the model registered with in default. But sometime you may want to exclude some permissions or include some permissions. To regulate permissions treated, use includes and excludes attributes.

includes attribute is set to permissions.handlers.base.get_model_permissions function in default. That's mean your newly created PermissionHandler will treat all permissions which related to the model. If you want to specify permissions, set a list/tuple or a function which have one argument. The PermissionHandler instance will be given as first argument.

excludes attribute is set to None in default. If you want to exclude some permissions from includes, set a list/tuple or a function which treated same as the function used in includes.

Example usage:

from permission import registry
from permission import PermissionHandler

from models import YourModel
from models import HisModel
from models import HerModel

class AppPermissionHandler(PermissionHandler):
    # this handler treat all permissions related to this app (myapp)
    includes = lambda self: self.get_all_permissions()

    # except permissions for adding models.
    excludes = (
        'myapp.add_yourmodel',
        'myapp.add_hismodel',
        'myapp.add_hermodel',
    )

    def has_perm(self, user_obj, perm, obj=None):
        codename = self.get_permission_codename()
        # permissions for adding models are excluded with
        # ``excludes`` attribute thus the code below never
        # fail.
        assert codename.startswith('add_')
        if perm.endswith('_yourmodel'):
            # All user has all permissions for ``YourModel``
            return True
        elif perm.endswith('_hismodel'):
            if user_obj.is_authenticated():
                # only authenticated user has all permissions for ``HisModel``
                return True
        elif perm.endswith('_hermodel'):
            if user_obj.is_staff:
                # only staff user has all permissions for ``HerModel``
                return True
        return False

# you have to register the handler with the model
# even AppPermissionHandler doesn't care about model
registry.register(YourModel, AppPermissionHandler)
# registry.register(HisModel, AppPermissionHandler) # or you can register with HisModel
# registry.register(HerModel, AppPermissionHandler) # or you can register with HerModel

Note

If you use user.has_perm() method in has_perm() method of PermissionHandler, make sure the permission is not treated with the handler.

django-permission's People

Contributors

duilio avatar lambdalisue avatar

Stargazers

 avatar

Watchers

 avatar

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.