GithubHelp home page GithubHelp logo

chrisglass / django-rulez Goto Github PK

View Code? Open in Web Editor NEW
64.0 5.0 18.0 116 KB

A lean and mean object-level rules system for the Django framework

License: BSD 3-Clause "New" or "Revised" License

Python 97.52% Shell 2.48%

django-rulez's Introduction

travisci

django-rulez

django-rulez is a lean, fast and complete rules-based permissions system for the django framework.

Most other authentication frameworks focus on using database joins, which gets pretty slow after a while (since mostly every query generates a lot of joins). Django-rulez uses a memory-based hashmap instead.

Django-rulez also implements a role concept, allowing for very readable and maintainable code.

django-rulez was forked from django-rules, since some of the goals django-rules set themselves didn't match our current project goals. You can refer to their github project page for more information about this other cool project: https://github.com/maraujop/django-rules Kudos for the good work guys!

Generally, it is also an instance-level authorization backend, that stores the rules themselves as methods on models.

Status

Since many people asked - this project is still active and used in production systems, but its current goals have been reached and not much further development happens.

Pull requests or discussion is very welcome, especially if you have an interesting use-case we haven't thought of :)

Our test coverage is 100%, and we would like to keep it this way, so please make sure you test before you push.

Installation

From source

To install django-rulez from source:

git clone https://github.com/chrisglass/django-rulez/ django-rulez
cd django-rulez
python setup.py install

From Pypi

Simply install django-rulez like you would install any other pypi package:

pip install django-rulez

Configuration

Example

The following example should get you started:

Django-rulez requires to declare the rule as a method in the same model. This is very simple in case the rule applies to a model in our own application, but in some cases, we might need to set object permisions to models from 3rd-party applications (e.g. to the User model). Let's see an example for this case:

Another example: using roles

A little more code is needed to use roles, but it's still pretty concise:

Using your rules

Once you have created a rule or role, you can utilize them directly on an instance of your model:

Or, with the help of django-rulez's authentication backend, on a user object:

In addition, the following templatetag usage is supported:

{% load rulez_perms %}
{% rulez_perms can_edit model_instance as VARNAME %}
{% if VARNAME %}
You have permissions
{% else %}
Sorry, you don't have permission
{% endif %}

django-rulez's People

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar

django-rulez's Issues

Set rules for User model (or a model from a 3rd party app)

Hi Chris,

I am not sure if this is an issue, probably not. I wanted to add rules so that a normal user can only edit his own user. But as django-rulez expects that the rule is contained in a class method. I had to use this 'hack' http://stackoverflow.com/questions/2939941/django-user-model-adding-function to make it work.

In my opinion, the way it is now it's good, I love how simple it is, but I think it would be nice to document this case and offer a solution (e.g. to use the add_to_class method).

inactive users should never have any permissions

The default model backend from django.contrib.auth checks for this, but we dont.

Unfortunately all auth backends are iterated over and the permission is granted if one of them returns True. So even if we have both backends installed and the backend from django.contrib.auth returns False, the permission will still be granted for inactive users if they have permissions based on django-rulez.

This project needs a maintainer.

Hi,

This repository seems to lack maintenance, I propose myself as a new maintainer.

Could you give me the right to push in your repository or just transfer it on my account in github?

Thank you

Status?

Hi there,

Firstly; this project looks very interesting. Flexible and simple; thanks for making the effort.

I'm wondering what the status of the project is? It appears to not have been worked on in some time?

Best regards
Ross

Extension of existing template tag

This is a feature request and patch for a template tag which checks user permission based on a method defined on the model. This template tag will accept either a model instance, or a model form with an instance. This is not backwards compatible with the earlier template tag rulez_perm.

Example:
{% has_perm can_edit pubform as editor %}
{% if editor %}
You can edit this!
{% endif %}

The code:

class RulezPermsNode(template.Node):

def __init__(self, codename, objname, varname):
    self.codename = codename
    self.objname = objname
    self.varname = varname

def render(self, context):
    user_obj = template.resolve_variable('user', context)
    obj = template.resolve_variable(self.objname, context)
    #check if the obj is a model instance
    if not hasattr(obj, 'DoesNotExist'):
        #If obj is a form, then try to get the form instance
        if hasattr(obj.instance, 'DoesNotExist'):
            obj = obj.instance
        else:
            self.codename = 'no permission method found'
    if not user_obj.is_authenticated:
        user_obj = AnonymousUser()
    if hasattr(obj,self.codename):
        context[self.varname] = getattr(obj,self.codename)(user_obj)
    else:
        context[self.varname]=False
    return ''

No git tag for version 1.0.2

One should be added for the commit wherever the latest PyPI version was cut.

Changelog updates wouldn't hurt either.

Consider merging with shield

@chrisglass Check out https://github.com/concordusapps/python-shield

I needed something like your project (which is great by the way) in sqlalchemy so I made the above. It's missing the roles concept and some good documentation but the groundwork is done for the declarative rules functionality and is orm-agnostic.


What I am proposing is we work together to add all the features from django-rulez you'd want, closing django-rulez, and then jointly maintaining shield to be the best permission framework it can be.

What do you think?

And if role was a collection of rules?

What i'm thinking is for a user validation he must get True for all this rules.

Something like this:

models.py

from rulez.rolez.base import AbstractRole
from rulez.roles.models import ModelRoleMixin
from rulez import registry

class Editor(AbstractRole):
    """ That's a role"""
    @classmethod
    def is_member(cls, user, obj):
        """Remember, class methods take the class instead of self"""
        if user.username == 'chris':
            return True
        return False

    @classmethod
    def has_permissions(cls, user, obj):
        """ Example of user permissions on the model"""
        return user.has_perms(['can_edit', 'can_delete'], cls)

    @classmethod
    def is_owner(cls, user, obj):
        """ Example for and related object """
        return obj.owner is user

class myModel(models.Model, ModelRoleMixin): # Don't forget the mixin!

    def can_edit(self, user_obj):
        '''
        Not a very useful either but it's an example
        '''
        return self.has_role(user_obj, Editor):

    roles = [Editor, ]

registry.register('can_edit', myModel)

The Goal for this approach is use the roles for specific validations, like if i want restrict access to a view if the user match with all the rules in the role.

Something like this:

views.py

from functools import wraps
from django.shortcuts import get_object_or_404
from django.http import HttpResponse

def assert_perms_on_object(view):
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        model_instance = get_object_or_404(myModel, id=kwargs['mymodel_id'])
        if request.user.has_perm('can_edit', model_instance)
            return view(request, *args, **kwargs)
    return wrapper

@assert_perms_on_object
def myview(request, *args, **kwargs):
    # Do someting
    return HttpResponse()

What must change?

As I understand the validation occurs:
rulez / rolez / cache_helper.py: 94

for role in relevant:
    if role.is_member(user, obj):
        user_roles.append(role)

It really is this snippet of code where changes should occur to validate all methods of role?

I could do a pull request to change this behavior if it is interesting for the django-rulez.

What do you think?

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.