Name | rules JSON |
Version |
3.4
JSON |
| download |
home_page | http://github.com/dfunckt/django-rules |
Summary | Awesome Django authorization, without the database |
upload_time | 2024-05-18 10:40:59 |
maintainer | Akis Kesoglou |
docs_url | None |
author | Akis Kesoglou |
requires_python | None |
license | MIT |
keywords |
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
rules
^^^^^
``rules`` is a tiny but powerful app providing object-level permissions to
Django, without requiring a database. At its core, it is a generic framework
for building rule-based systems, similar to `decision trees`_. It can also be
used as a standalone library in other contexts and frameworks.
.. image:: https://img.shields.io/github/workflow/status/dfunckt/django-rules/CI/master
:target: https://github.com/dfunckt/django-rules/actions
.. image:: https://coveralls.io/repos/dfunckt/django-rules/badge.svg
:target: https://coveralls.io/r/dfunckt/django-rules
.. image:: https://img.shields.io/pypi/v/rules.svg
:target: https://pypi.org/project/rules/
.. image:: https://img.shields.io/pypi/pyversions/rules.svg
:target: https://pypi.org/project/rules/
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
.. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white
:target: https://github.com/pre-commit/pre-commit
.. _decision trees: http://wikipedia.org/wiki/Decision_tree
Features
========
``rules`` has got you covered. ``rules`` is:
- **Documented**, **tested**, **reliable** and **easy to use**.
- **Versatile**. Decorate callables to build complex graphs of predicates.
Predicates can be any type of callable -- simple functions, lambdas,
methods, callable class objects, partial functions, decorated functions,
anything really.
- **A good Django citizen**. Seamless integration with Django views,
templates and the Admin for testing for object-level permissions.
- **Efficient** and **smart**. No need to mess around with a database to figure
out whether John really wrote that book.
- **Simple**. Dive in the code. You'll need 10 minutes to figure out how it
works.
- **Powerful**. ``rules`` comes complete with advanced features, such as
invocation context and storage for arbitrary data, skipping evaluation of
predicates under specific conditions, logging of evaluated predicates and more!
Table of Contents
=================
- `Requirements`_
- `Upgrading from 2.x`_
- `Upgrading from 1.x`_
- `How to install`_
- `Configuring Django`_
- `Using Rules`_
- `Creating predicates`_
- `Dynamic predicates`_
- `Setting up rules`_
- `Combining predicates`_
- `Using Rules with Django`_
- `Permissions`_
- `Permissions in models`_
- `Permissions in views`_
- `Permissions and rules in templates`_
- `Permissions in the Admin`_
- `Permissions in Django Rest Framework`_
- `Advanced features`_
- `Custom rule sets`_
- `Invocation context`_
- `Binding "self"`_
- `Skipping predicates`_
- `Logging predicate evaluation`_
- `Best practices`_
- `API Reference`_
- `Licence`_
Requirements
============
``rules`` requires Python 3.8 or newer. The last version to support Python 2.7
is ``rules`` 2.2. It can optionally integrate with Django, in which case
requires Django 3.2 or newer.
*Note*: At any given moment in time, ``rules`` will maintain support for all
currently supported Django versions, while dropping support for those versions
that reached end-of-life in minor releases. See the `Supported Versions`_
section on Django Project website for the current state and timeline.
.. _Supported Versions: https://www.djangoproject.com/download/#supported-versions
Upgrading from 2.x
==================
The are no significant changes between ``rules`` 2.x and 3.x except dropping
support for Python 2, so before upgrading to 3.x you just need to make sure
you're running a supported Python 3 version.
Upgrading from 1.x
==================
* Support for Python 2.6 and 3.3, and Django versions before 1.11 has been
dropped.
* The ``SkipPredicate`` exception and ``skip()`` method of ``Predicate``,
that were used to signify that a predicate should be skipped, have been
removed. You may return ``None`` from your predicate to achieve this.
* The APIs to replace a rule's predicate have been renamed and their
behaviour changed. ``replace_rule`` and ``replace_perm`` functions and
``replace_rule`` method of ``RuleSet`` have been renamed to ``set_rule``,
``set_perm`` and ``RuleSet.set_perm`` respectively. The old behaviour was
to raise a ``KeyError`` if a rule by the given name did not exist. Since
version 2.0 this has changed and you can safely use ``set_*`` to set a
rule's predicate without having to ensure the rule exists first.
How to install
==============
Using pip:
.. code:: bash
$ pip install rules
Manually:
.. code:: bash
$ git clone https://github.com/dfunckt/django-rules.git
$ cd django-rules
$ python setup.py install
Run tests with:
.. code:: bash
$ ./runtests.sh
You may also want to read `Best practices`_ for general advice on how to
use ``rules``.
Configuring Django
------------------
Add ``rules`` to ``INSTALLED_APPS``:
.. code:: python
INSTALLED_APPS = (
# ...
'rules',
)
Add the authentication backend:
.. code:: python
AUTHENTICATION_BACKENDS = (
'rules.permissions.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
Using Rules
===========
``rules`` is based on the idea that you maintain a dict-like object that maps
string keys used as identifiers of some kind, to callables, called
*predicates*. This dict-like object is actually an instance of ``RuleSet`` and
the predicates are instances of ``Predicate``.
Creating predicates
-------------------
Let's ignore rule sets for a moment and go ahead and define a predicate. The
easiest way is with the ``@predicate`` decorator:
.. code:: python
>>> @rules.predicate
>>> def is_book_author(user, book):
... return book.author == user
...
>>> is_book_author
<Predicate:is_book_author object at 0x10eeaa490>
This predicate will return ``True`` if the book's author is the given user,
``False`` otherwise.
Predicates can be created from any callable that accepts anything from zero to
two positional arguments:
* ``fn(obj, target)``
* ``fn(obj)``
* ``fn()``
This is their generic form. If seen from the perspective of authorization in
Django, the equivalent signatures are:
* ``fn(user, obj)``
* ``fn(user)``
* ``fn()``
Predicates can do pretty much anything with the given arguments, but must
always return ``True`` if the condition they check is true, ``False``
otherwise. ``rules`` comes with several predefined predicates that you may
read about later on in `API Reference`_, that are mostly useful when dealing
with `authorization in Django`_.
Dynamic predicates
-------------------
If needed predicates can be created dynamically depending on parameters:
.. code:: python
import rules
def role_is(role_id):
@rules.predicate
def user_has_role(user):
return user.role.id == role_id
return user_has_role
rules.add_perm("reports.view_report_abc", role_is(12))
rules.add_perm("reports.view_report_xyz", role_is(13))
Setting up rules
----------------
Let's pretend that we want to let authors edit or delete their books, but not
books written by other authors. So, essentially, what determines whether an
author *can edit* or *can delete* a given book is *whether they are its
author*.
In ``rules``, such requirements are modelled as *rules*. A *rule* is a map of
a unique identifier (eg. "can edit") to a predicate. Rules are grouped
together into a *rule set*. ``rules`` has two predefined rule sets:
* A default rule set storing shared rules.
* Another rule set storing rules that serve as permissions in a Django
context.
So, let's define our first couple of rules, adding them to the shared rule
set. We can use the ``is_book_author`` predicate we defined earlier:
.. code:: python
>>> rules.add_rule('can_edit_book', is_book_author)
>>> rules.add_rule('can_delete_book', is_book_author)
Assuming we've got some data, we can now test our rules:
.. code:: python
>>> from django.contrib.auth.models import User
>>> from books.models import Book
>>> guidetodjango = Book.objects.get(isbn='978-1-4302-1936-1')
>>> guidetodjango.author
<User: adrian>
>>> adrian = User.objects.get(username='adrian')
>>> rules.test_rule('can_edit_book', adrian, guidetodjango)
True
>>> rules.test_rule('can_delete_book', adrian, guidetodjango)
True
Nice... but not awesome.
Combining predicates
--------------------
Predicates by themselves are not so useful -- not more useful than any other
function would be. Predicates, however, can be combined using binary operators
to create more complex ones. Predicates support the following operators:
* ``P1 & P2``: Returns a new predicate that returns ``True`` if *both*
predicates return ``True``, otherwise ``False``. If P1 returns ``False``,
P2 will not be evaluated.
* ``P1 | P2``: Returns a new predicate that returns ``True`` if *any* of the
predicates returns ``True``, otherwise ``False``. If P1 returns ``True``,
P2 will not be evaluated.
* ``P1 ^ P2``: Returns a new predicate that returns ``True`` if one of the
predicates returns ``True`` and the other returns ``False``, otherwise
``False``.
* ``~P``: Returns a new predicate that returns the negated result of the
original predicate.
Suppose the requirement for allowing a user to edit a given book was for them
to be either the book's author, or a member of the "editors" group. Allowing
users to delete a book should still be determined by whether the user is the
book's author.
With ``rules`` that's easy to implement. We'd have to define another
predicate, that would return ``True`` if the given user is a member of the
"editors" group, ``False`` otherwise. The built-in ``is_group_member`` factory
will come in handy:
.. code:: python
>>> is_editor = rules.is_group_member('editors')
>>> is_editor
<Predicate:is_group_member:editors object at 0x10eee1350>
We could combine it with the ``is_book_author`` predicate to create a new one
that checks for either condition:
.. code:: python
>>> is_book_author_or_editor = is_book_author | is_editor
>>> is_book_author_or_editor
<Predicate:(is_book_author | is_group_member:editors) object at 0x10eee1390>
We can now update our ``can_edit_book`` rule:
.. code:: python
>>> rules.set_rule('can_edit_book', is_book_author_or_editor)
>>> rules.test_rule('can_edit_book', adrian, guidetodjango)
True
>>> rules.test_rule('can_delete_book', adrian, guidetodjango)
True
Let's see what happens with another user:
.. code:: python
>>> martin = User.objects.get(username='martin')
>>> list(martin.groups.values_list('name', flat=True))
['editors']
>>> rules.test_rule('can_edit_book', martin, guidetodjango)
True
>>> rules.test_rule('can_delete_book', martin, guidetodjango)
False
Awesome.
So far, we've only used the underlying, generic framework for defining and
testing rules. This layer is not at all specific to Django; it may be used in
any context. There's actually no import of anything Django-related in the
whole app (except in the ``rules.templatetags`` module). ``rules`` however can
integrate tightly with Django to provide authorization.
.. _authorization in Django:
Using Rules with Django
=======================
``rules`` is able to provide object-level permissions in Django. It comes
with an authorization backend and a couple template tags for use in your
templates.
Permissions
-----------
In ``rules``, permissions are a specialised type of rules. You still define
rules by creating and combining predicates. These rules however, must be added
to a permissions-specific rule set that comes with ``rules`` so that they can
be picked up by the ``rules`` authorization backend.
Creating permissions
++++++++++++++++++++
The convention for naming permissions in Django is ``app_label.action_object``,
and we like to adhere to that. Let's add rules for the ``books.change_book``
and ``books.delete_book`` permissions:
.. code:: python
>>> rules.add_perm('books.change_book', is_book_author | is_editor)
>>> rules.add_perm('books.delete_book', is_book_author)
See the difference in the API? ``add_perm`` adds to a permissions-specific
rule set, whereas ``add_rule`` adds to a default shared rule set. It's
important to know however, that these two rule sets are separate, meaning that
adding a rule in one does not make it available to the other.
Checking for permission
+++++++++++++++++++++++
Let's go ahead and check whether ``adrian`` has change permission to the
``guidetodjango`` book:
.. code:: python
>>> adrian.has_perm('books.change_book', guidetodjango)
False
When you call the ``User.has_perm`` method, Django asks each backend in
``settings.AUTHENTICATION_BACKENDS`` whether a user has the given permission
for the object. When queried for object permissions, Django's default
authentication backend always returns ``False``. ``rules`` comes with an
authorization backend, that is able to provide object-level permissions by
looking into the permissions-specific rule set.
Let's add the ``rules`` authorization backend in settings:
.. code:: python
AUTHENTICATION_BACKENDS = (
'rules.permissions.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
Now, checking again gives ``adrian`` the required permissions:
.. code:: python
>>> adrian.has_perm('books.change_book', guidetodjango)
True
>>> adrian.has_perm('books.delete_book', guidetodjango)
True
>>> martin.has_perm('books.change_book', guidetodjango)
True
>>> martin.has_perm('books.delete_book', guidetodjango)
False
**NOTE:** Calling `has_perm` on a superuser will ALWAYS return `True`.
Permissions in models
---------------------
**NOTE:** The features described in this section work on Python 3+ only.
It is common to have a set of permissions for a model, like what Django offers with
its default model permissions (such as *add*, *change* etc.). When using ``rules``
as the permission checking backend, you can declare object-level permissions for
any model in a similar way, using a new ``Meta`` option.
First, you need to switch your model's base and metaclass to the slightly extended
versions provided in ``rules.contrib.models``. There are several classes and mixins
you can use, depending on whether you're already using a custom base and/or metaclass
for your models or not. The extensions are very slim and don't affect the models'
behavior in any way other than making it register permissions.
* If you're using the stock ``django.db.models.Model`` as base for your models,
simply switch over to ``RulesModel`` and you're good to go.
* If you already have a custom base class adding common functionality to your models,
add ``RulesModelMixin`` to the classes it inherits from and set ``RulesModelBase``
as its metaclass, like so::
from django.db.models import Model
from rules.contrib.models import RulesModelBase, RulesModelMixin
class MyModel(RulesModelMixin, Model, metaclass=RulesModelBase):
...
* If you're using a custom metaclass for your models, you'll already know how to
make it inherit from ``RulesModelBaseMixin`` yourself.
Then, create your models like so, assuming you're using ``RulesModel`` as base
directly::
import rules
from rules.contrib.models import RulesModel
class Book(RulesModel):
class Meta:
rules_permissions = {
"add": rules.is_staff,
"read": rules.is_authenticated,
}
This would be equivalent to the following calls::
rules.add_perm("app_label.add_book", rules.is_staff)
rules.add_perm("app_label.read_book", rules.is_authenticated)
There are methods in ``RulesModelMixin`` that you can overwrite in order to customize
how a model's permissions are registered. See the documented source code for details
if you need this.
Of special interest is the ``get_perm`` classmethod of ``RulesModelMixin``, which can
be used to convert a permission type to the corresponding full permission name. If
you need to query for some type of permission on a given model programmatically,
this is handy::
if user.has_perm(Book.get_perm("read")):
...
Permissions in views
--------------------
``rules`` comes with a set of view decorators to help you enforce
authorization in your views.
Using the function-based view decorator
+++++++++++++++++++++++++++++++++++++++
For function-based views you can use the ``permission_required`` decorator:
.. code:: python
from django.shortcuts import get_object_or_404
from rules.contrib.views import permission_required
from posts.models import Post
def get_post_by_pk(request, post_id):
return get_object_or_404(Post, pk=post_id)
@permission_required('posts.change_post', fn=get_post_by_pk)
def post_update(request, post_id):
# ...
Usage is straight-forward, but there's one thing in the example above that
stands out and this is the ``get_post_by_pk`` function. This function, given
the current request and all arguments passed to the view, is responsible for
fetching and returning the object to check permissions against -- i.e. the
``Post`` instance with PK equal to the given ``post_id`` in the example.
This specific use-case is quite common so, to save you some typing, ``rules``
comes with a generic helper function that you can use to do this declaratively.
The example below is equivalent to the one above:
.. code:: python
from rules.contrib.views import permission_required, objectgetter
from posts.models import Post
@permission_required('posts.change_post', fn=objectgetter(Post, 'post_id'))
def post_update(request, post_id):
# ...
For more information on the decorator and helper function, refer to the
``rules.contrib.views`` module.
Using the class-based view mixin
++++++++++++++++++++++++++++++++
Django includes a set of access mixins that you can use in your class-based
views to enforce authorization. ``rules`` extends this framework to provide
object-level permissions via a mixin, ``PermissionRequiredMixin``.
The following example will automatically test for permission against the
instance returned by the view's ``get_object`` method:
.. code:: python
from django.views.generic.edit import UpdateView
from rules.contrib.views import PermissionRequiredMixin
from posts.models import Post
class PostUpdate(PermissionRequiredMixin, UpdateView):
model = Post
permission_required = 'posts.change_post'
You can customise the object either by overriding ``get_object`` or
``get_permission_object``.
For more information refer to the `Django documentation`_ and the
``rules.contrib.views`` module.
.. _Django documentation: https://docs.djangoproject.com/en/1.9/topics/auth/default/#limiting-access-to-logged-in-users
Checking permission automatically based on view type
++++++++++++++++++++++++++++++++++++++++++++++++++++
If you use the mechanisms provided by ``rules.contrib.models`` to register permissions
for your models as described in `Permissions in models`_, there's another convenient
mixin for class-based views available for you.
``rules.contrib.views.AutoPermissionRequiredMixin`` can recognize the type of view
it's used with and check for the corresponding permission automatically.
This example view would, without any further configuration, automatically check for
the ``"posts.change_post"`` permission, given that the app label is ``"posts"``::
from django.views.generic import UpdateView
from rules.contrib.views import AutoPermissionRequiredMixin
from posts.models import Post
class UpdatePostView(AutoPermissionRequiredMixin, UpdateView):
model = Post
By default, the generic CRUD views from ``django.views.generic`` are mapped to the
native Django permission types (*add*, *change*, *delete* and *view*). However,
the pre-defined mappings can be extended, changed or replaced altogether when
subclassing ``AutoPermissionRequiredMixin``. See the fully documented source code
for details on how to do that properly.
Permissions and rules in templates
----------------------------------
``rules`` comes with two template tags to allow you to test for rules and
permissions in templates.
Add ``rules`` to your ``INSTALLED_APPS``:
.. code:: python
INSTALLED_APPS = (
# ...
'rules',
)
Then, in your template::
{% load rules %}
{% has_perm 'books.change_book' author book as can_edit_book %}
{% if can_edit_book %}
...
{% endif %}
{% test_rule 'has_super_feature' user as has_super_feature %}
{% if has_super_feature %}
...
{% endif %}
Permissions in the Admin
------------------------
If you've setup ``rules`` to be used with permissions in Django, you're almost
set to also use ``rules`` to authorize any add/change/delete actions in the
Admin. The Admin asks for *four* different permissions, depending on action:
- ``<app_label>.add_<modelname>``
- ``<app_label>.view_<modelname>``
- ``<app_label>.change_<modelname>``
- ``<app_label>.delete_<modelname>``
- ``<app_label>``
*Note:* view permission is new in Django v2.1 and should not be added in versions before that.
The first four are obvious. The fifth is the required permission for an app
to be displayed in the Admin's "dashboard". Overriding it does not restrict access to the add,
change or delete views. Here's some rules for our imaginary ``books`` app as an example:
.. code:: python
>>> rules.add_perm('books', rules.always_allow)
>>> rules.add_perm('books.add_book', is_staff)
>>> rules.add_perm('books.view_book', is_staff | has_secret_access_code)
>>> rules.add_perm('books.change_book', is_staff)
>>> rules.add_perm('books.delete_book', is_staff)
Django Admin does not support object-permissions, in the sense that it will
never ask for permission to perform an action *on an object*, only whether a
user is allowed to act on (*any*) instances of a model.
If you'd like to tell Django whether a user has permissions on a specific
object, you'd have to override the following methods of a model's
``ModelAdmin``:
- ``has_view_permission(user, obj=None)``
- ``has_change_permission(user, obj=None)``
- ``has_delete_permission(user, obj=None)``
``rules`` comes with a custom ``ModelAdmin`` subclass,
``rules.contrib.admin.ObjectPermissionsModelAdmin``, that overrides these
methods to pass on the edited model instance to the authorization backends,
thus enabling permissions per object in the Admin:
.. code:: python
# books/admin.py
from django.contrib import admin
from rules.contrib.admin import ObjectPermissionsModelAdmin
from .models import Book
class BookAdmin(ObjectPermissionsModelAdmin):
pass
admin.site.register(Book, BookAdmin)
Now this allows you to specify permissions like this:
.. code:: python
>>> rules.add_perm('books', rules.always_allow)
>>> rules.add_perm('books.add_book', has_author_profile)
>>> rules.add_perm('books.change_book', is_book_author_or_editor)
>>> rules.add_perm('books.delete_book', is_book_author)
To preserve backwards compatibility, Django will ask for either *view* or
*change* permission. For maximum flexibility, ``rules`` behaves subtly
different: ``rules`` will ask for the change permission if and only if no rule
exists for the view permission.
Permissions in Django Rest Framework
------------------------------------
Similar to ``rules.contrib.views.AutoPermissionRequiredMixin``, there is a
``rules.contrib.rest_framework.AutoPermissionViewSetMixin`` for viewsets in Django
Rest Framework. The difference is that it doesn't derive permission from the type
of view but from the API action (*create*, *retrieve* etc.) that's tried to be
performed. Of course, it also requires you to declare your models as described in
`Permissions in models`_.
Here is a possible ``ModelViewSet`` for the ``Post`` model with fully automated CRUD
permission checking::
from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet
from rules.contrib.rest_framework import AutoPermissionViewSetMixin
from posts.models import Post
class PostSerializer(ModelSerializer):
class Meta:
model = Post
fields = "__all__"
class PostViewSet(AutoPermissionViewSetMixin, ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
By default, the CRUD actions of ``ModelViewSet`` are mapped to the native
Django permission types (*add*, *change*, *delete* and *view*). The ``list``
action has no permission checking enabled. However, the pre-defined mappings
can be extended, changed or replaced altogether when using (or subclassing)
``AutoPermissionViewSetMixin``. Custom API actions defined via the ``@action``
decorator may then be mapped as well. See the fully documented source code for
details on how to properly customize the default behavior.
Advanced features
=================
Custom rule sets
----------------
You may create as many rule sets as you need:
.. code:: python
>>> features = rules.RuleSet()
And manipulate them by adding, removing, querying and testing rules:
.. code:: python
>>> features.rule_exists('has_super_feature')
False
>>> is_special_user = rules.is_group_member('special')
>>> features.add_rule('has_super_feature', is_special_user)
>>> 'has_super_feature' in features
True
>>> features['has_super_feature']
<Predicate:is_group_member:special object at 0x10eeaa500>
>>> features.test_rule('has_super_feature', adrian)
True
>>> features.remove_rule('has_super_feature')
Note however that custom rule sets are *not available* in Django templates --
you need to provide integration yourself.
Invocation context
------------------
A new context is created as a result of invoking ``Predicate.test()`` and is
only valid for the duration of the invocation. A context is a simple ``dict``
that you can use to store arbitrary data, (eg. caching computed values,
setting flags, etc.), that can be used by predicates later on in the chain.
Inside a predicate function it can be used like so:
.. code:: python
>>> @predicate
... def mypred(a, b):
... value = compute_expensive_value(a)
... mypred.context['value'] = value
... return True
Other predicates can later use stored values:
.. code:: python
>>> @predicate
... def myotherpred(a, b):
... value = myotherpred.context.get('value')
... if value is not None:
... return do_something_with_value(value)
... else:
... return do_something_without_value()
``Predicate.context`` provides a single ``args`` attribute that contains the
arguments as given to ``test()`` at the beginning of the invocation.
Binding "self"
--------------
In a predicate's function body, you can refer to the predicate instance itself
by its name, eg. ``is_book_author``. Passing ``bind=True`` as a keyword
argument to the ``predicate`` decorator will let you refer to the predicate
with ``self``, which is more convenient. Binding ``self`` is just syntactic
sugar. As a matter of fact, the following two are equivalent:
.. code:: python
>>> @predicate
... def is_book_author(user, book):
... if is_book_author.context.args:
... return user == book.author
... return False
>>> @predicate(bind=True)
... def is_book_author(self, user, book):
... if self.context.args:
... return user == book.author
... return False
Skipping predicates
-------------------
You may skip evaluation by returning ``None`` from your predicate:
.. code:: python
>>> @predicate(bind=True)
... def is_book_author(self, user, book):
... if len(self.context.args) > 1:
... return user == book.author
... else:
... return None
Returning ``None`` signifies that the predicate need not be evaluated, thus
leaving the predicate result up to that point unchanged.
Logging predicate evaluation
----------------------------
``rules`` can optionally be configured to log debug information as rules are
evaluated to help with debugging your predicates. Messages are sent at the
DEBUG level to the ``'rules'`` logger. The following `dictConfig`_ configures
a console logger (place this in your project's `settings.py` if you're using
`rules` with Django):
.. code:: python
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'rules': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}
When this logger is active each individual predicate will have a log message
printed when it is evaluated.
.. _dictConfig: https://docs.python.org/3.6/library/logging.config.html#logging-config-dictschema
Best practices
==============
Before you can test for rules, these rules must be registered with a rule set,
and for this to happen the modules containing your rule definitions must be
imported.
For complex projects with several predicates and rules, it may not be
practical to define all your predicates and rules inside one module. It might
be best to split them among any sub-components of your project. In a Django
context, these sub-components could be the apps for your project.
On the other hand, because importing predicates from all over the place in
order to define rules can lead to circular imports and broken hearts, it's
best to further split predicates and rules in different modules.
``rules`` may optionally be configured to autodiscover ``rules.py`` modules in
your apps and import them at startup. To have ``rules`` do so, just edit your
``INSTALLED_APPS`` setting:
.. code:: python
INSTALLED_APPS = (
# replace 'rules' with:
'rules.apps.AutodiscoverRulesConfig',
)
**Note:** On Python 2, you must also add the following to the top of your
``rules.py`` file, or you'll get import errors trying to import ``rules``
itself:
.. code:: python
from __future__ import absolute_import
API Reference
=============
The core APIs are accessible from the root ``rules`` module. Django-specific
functionality for the Admin and views is available from ``rules.contrib``.
Class ``rules.Predicate``
-------------------------
You create ``Predicate`` instances by passing in a callable:
.. code:: python
>>> def is_book_author(user, book):
... return book.author == user
...
>>> pred = Predicate(is_book_author)
>>> pred
<Predicate:is_book_author object at 0x10eeaa490>
You may optionally provide a different name for the predicate that is used
when inspecting it:
.. code:: python
>>> pred = Predicate(is_book_author, name='another_name')
>>> pred
<Predicate:another_name object at 0x10eeaa490>
Also, you may optionally provide ``bind=True`` in order to be able to access
the predicate instance with ``self``:
.. code:: python
>>> def is_book_author(self, user, book):
... if self.context.args:
... return user == book.author
... return False
...
>>> pred = Predicate(is_book_author, bind=True)
>>> pred
<Predicate:is_book_author object at 0x10eeaa490>
Instance methods
++++++++++++++++
``test(obj=None, target=None)``
Returns the result of calling the passed in callable with zero, one or two
positional arguments, depending on how many it accepts.
Class ``rules.RuleSet``
-----------------------
``RuleSet`` extends Python's built-in `dict`_ type. Therefore, you may create
and use a rule set any way you'd use a dict.
.. _dict: http://docs.python.org/library/stdtypes.html#mapping-types-dict
Instance methods
++++++++++++++++
``add_rule(name, predicate)``
Adds a predicate to the rule set, assigning it to the given rule name.
Raises ``KeyError`` if another rule with that name already exists.
``set_rule(name, predicate)``
Set the rule with the given name, regardless if one already exists.
``remove_rule(name)``
Remove the rule with the given name. Raises ``KeyError`` if a rule with
that name does not exist.
``rule_exists(name)``
Returns ``True`` if a rule with the given name exists, ``False`` otherwise.
``test_rule(name, obj=None, target=None)``
Returns the result of calling ``predicate.test(obj, target)`` where
``predicate`` is the predicate for the rule with the given name. Returns
``False`` if a rule with the given name does not exist.
Decorators
----------
``@predicate``
Decorator that creates a predicate out of any callable:
.. code:: python
>>> @predicate
... def is_book_author(user, book):
... return book.author == user
...
>>> is_book_author
<Predicate:is_book_author object at 0x10eeaa490>
Customising the predicate name:
.. code:: python
>>> @predicate(name='another_name')
... def is_book_author(user, book):
... return book.author == user
...
>>> is_book_author
<Predicate:another_name object at 0x10eeaa490>
Binding ``self``:
.. code:: python
>>> @predicate(bind=True)
... def is_book_author(self, user, book):
... if 'user_has_special_flag' in self.context:
... return self.context['user_has_special_flag']
... return book.author == user
Predefined predicates
---------------------
``always_allow()``, ``always_true()``
Always returns ``True``.
``always_deny()``, ``always_false()``
Always returns ``False``.
``is_authenticated(user)``
Returns the result of calling ``user.is_authenticated()``. Returns
``False`` if the given user does not have an ``is_authenticated`` method.
``is_superuser(user)``
Returns the result of calling ``user.is_superuser``. Returns ``False``
if the given user does not have an ``is_superuser`` property.
``is_staff(user)``
Returns the result of calling ``user.is_staff``. Returns ``False`` if the
given user does not have an ``is_staff`` property.
``is_active(user)``
Returns the result of calling ``user.is_active``. Returns ``False`` if the
given user does not have an ``is_active`` property.
``is_group_member(*groups)``
Factory that creates a new predicate that returns ``True`` if the given
user is a member of *all* the given groups, ``False`` otherwise.
Shortcuts
---------
Managing the shared rule set
++++++++++++++++++++++++++++
``add_rule(name, predicate)``
Adds a rule to the shared rule set. See ``RuleSet.add_rule``.
``set_rule(name, predicate)``
Set the rule with the given name from the shared rule set. See
``RuleSet.set_rule``.
``remove_rule(name)``
Remove a rule from the shared rule set. See ``RuleSet.remove_rule``.
``rule_exists(name)``
Returns whether a rule exists in the shared rule set. See
``RuleSet.rule_exists``.
``test_rule(name, obj=None, target=None)``
Tests the rule with the given name. See ``RuleSet.test_rule``.
Managing the permissions rule set
+++++++++++++++++++++++++++++++++
``add_perm(name, predicate)``
Adds a rule to the permissions rule set. See ``RuleSet.add_rule``.
``set_perm(name, predicate)``
Replace a rule from the permissions rule set. See ``RuleSet.set_rule``.
``remove_perm(name)``
Remove a rule from the permissions rule set. See ``RuleSet.remove_rule``.
``perm_exists(name)``
Returns whether a rule exists in the permissions rule set. See
``RuleSet.rule_exists``.
``has_perm(name, user=None, obj=None)``
Tests the rule with the given name. See ``RuleSet.test_rule``.
Licence
=======
``django-rules`` is distributed under the MIT licence.
Copyright (c) 2014 Akis Kesoglou
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Raw data
{
"_id": null,
"home_page": "http://github.com/dfunckt/django-rules",
"name": "rules",
"maintainer": "Akis Kesoglou",
"docs_url": null,
"requires_python": null,
"maintainer_email": "akiskesoglou@gmail.com",
"keywords": null,
"author": "Akis Kesoglou",
"author_email": "akiskesoglou@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/63/dd/06b3621f65133680297215d23567b4b83f939fe5a7b6ce92244d70950b94/rules-3.4.tar.gz",
"platform": null,
"description": "rules\n^^^^^\n\n``rules`` is a tiny but powerful app providing object-level permissions to\nDjango, without requiring a database. At its core, it is a generic framework\nfor building rule-based systems, similar to `decision trees`_. It can also be\nused as a standalone library in other contexts and frameworks.\n\n.. image:: https://img.shields.io/github/workflow/status/dfunckt/django-rules/CI/master\n :target: https://github.com/dfunckt/django-rules/actions\n.. image:: https://coveralls.io/repos/dfunckt/django-rules/badge.svg\n :target: https://coveralls.io/r/dfunckt/django-rules\n.. image:: https://img.shields.io/pypi/v/rules.svg\n :target: https://pypi.org/project/rules/\n.. image:: https://img.shields.io/pypi/pyversions/rules.svg\n :target: https://pypi.org/project/rules/\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n :target: https://github.com/psf/black\n.. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white\n :target: https://github.com/pre-commit/pre-commit\n\n.. _decision trees: http://wikipedia.org/wiki/Decision_tree\n\n\nFeatures\n========\n\n``rules`` has got you covered. ``rules`` is:\n\n- **Documented**, **tested**, **reliable** and **easy to use**.\n- **Versatile**. Decorate callables to build complex graphs of predicates.\n Predicates can be any type of callable -- simple functions, lambdas,\n methods, callable class objects, partial functions, decorated functions,\n anything really.\n- **A good Django citizen**. Seamless integration with Django views,\n templates and the Admin for testing for object-level permissions.\n- **Efficient** and **smart**. No need to mess around with a database to figure\n out whether John really wrote that book.\n- **Simple**. Dive in the code. You'll need 10 minutes to figure out how it\n works.\n- **Powerful**. ``rules`` comes complete with advanced features, such as\n invocation context and storage for arbitrary data, skipping evaluation of\n predicates under specific conditions, logging of evaluated predicates and more!\n\n\nTable of Contents\n=================\n\n- `Requirements`_\n- `Upgrading from 2.x`_\n- `Upgrading from 1.x`_\n- `How to install`_\n\n - `Configuring Django`_\n\n- `Using Rules`_\n\n - `Creating predicates`_\n - `Dynamic predicates`_\n - `Setting up rules`_\n - `Combining predicates`_\n\n- `Using Rules with Django`_\n\n - `Permissions`_\n - `Permissions in models`_\n - `Permissions in views`_\n - `Permissions and rules in templates`_\n - `Permissions in the Admin`_\n - `Permissions in Django Rest Framework`_\n\n- `Advanced features`_\n\n - `Custom rule sets`_\n - `Invocation context`_\n - `Binding \"self\"`_\n - `Skipping predicates`_\n - `Logging predicate evaluation`_\n\n- `Best practices`_\n- `API Reference`_\n- `Licence`_\n\n\nRequirements\n============\n\n``rules`` requires Python 3.8 or newer. The last version to support Python 2.7\nis ``rules`` 2.2. It can optionally integrate with Django, in which case\nrequires Django 3.2 or newer.\n\n*Note*: At any given moment in time, ``rules`` will maintain support for all\ncurrently supported Django versions, while dropping support for those versions\nthat reached end-of-life in minor releases. See the `Supported Versions`_\nsection on Django Project website for the current state and timeline.\n\n.. _Supported Versions: https://www.djangoproject.com/download/#supported-versions\n\n\nUpgrading from 2.x\n==================\n\nThe are no significant changes between ``rules`` 2.x and 3.x except dropping\nsupport for Python 2, so before upgrading to 3.x you just need to make sure\nyou're running a supported Python 3 version.\n\n\nUpgrading from 1.x\n==================\n\n* Support for Python 2.6 and 3.3, and Django versions before 1.11 has been\n dropped.\n\n* The ``SkipPredicate`` exception and ``skip()`` method of ``Predicate``,\n that were used to signify that a predicate should be skipped, have been\n removed. You may return ``None`` from your predicate to achieve this.\n\n* The APIs to replace a rule's predicate have been renamed and their\n behaviour changed. ``replace_rule`` and ``replace_perm`` functions and\n ``replace_rule`` method of ``RuleSet`` have been renamed to ``set_rule``,\n ``set_perm`` and ``RuleSet.set_perm`` respectively. The old behaviour was\n to raise a ``KeyError`` if a rule by the given name did not exist. Since\n version 2.0 this has changed and you can safely use ``set_*`` to set a\n rule's predicate without having to ensure the rule exists first.\n\n\nHow to install\n==============\n\nUsing pip:\n\n.. code:: bash\n\n $ pip install rules\n\nManually:\n\n.. code:: bash\n\n $ git clone https://github.com/dfunckt/django-rules.git\n $ cd django-rules\n $ python setup.py install\n\nRun tests with:\n\n.. code:: bash\n\n $ ./runtests.sh\n\nYou may also want to read `Best practices`_ for general advice on how to\nuse ``rules``.\n\n\nConfiguring Django\n------------------\n\nAdd ``rules`` to ``INSTALLED_APPS``:\n\n.. code:: python\n\n INSTALLED_APPS = (\n # ...\n 'rules',\n )\n\nAdd the authentication backend:\n\n.. code:: python\n\n AUTHENTICATION_BACKENDS = (\n 'rules.permissions.ObjectPermissionBackend',\n 'django.contrib.auth.backends.ModelBackend',\n )\n\n\nUsing Rules\n===========\n\n``rules`` is based on the idea that you maintain a dict-like object that maps\nstring keys used as identifiers of some kind, to callables, called\n*predicates*. This dict-like object is actually an instance of ``RuleSet`` and\nthe predicates are instances of ``Predicate``.\n\n\nCreating predicates\n-------------------\n\nLet's ignore rule sets for a moment and go ahead and define a predicate. The\neasiest way is with the ``@predicate`` decorator:\n\n.. code:: python\n\n >>> @rules.predicate\n >>> def is_book_author(user, book):\n ... return book.author == user\n ...\n >>> is_book_author\n <Predicate:is_book_author object at 0x10eeaa490>\n\nThis predicate will return ``True`` if the book's author is the given user,\n``False`` otherwise.\n\nPredicates can be created from any callable that accepts anything from zero to\ntwo positional arguments:\n\n* ``fn(obj, target)``\n* ``fn(obj)``\n* ``fn()``\n\nThis is their generic form. If seen from the perspective of authorization in\nDjango, the equivalent signatures are:\n\n* ``fn(user, obj)``\n* ``fn(user)``\n* ``fn()``\n\nPredicates can do pretty much anything with the given arguments, but must\nalways return ``True`` if the condition they check is true, ``False``\notherwise. ``rules`` comes with several predefined predicates that you may\nread about later on in `API Reference`_, that are mostly useful when dealing\nwith `authorization in Django`_.\n\n\nDynamic predicates\n-------------------\n\nIf needed predicates can be created dynamically depending on parameters:\n\n.. code:: python\n\n import rules\n\n\n def role_is(role_id):\n @rules.predicate\n def user_has_role(user):\n return user.role.id == role_id\n\n return user_has_role\n\n\n rules.add_perm(\"reports.view_report_abc\", role_is(12))\n rules.add_perm(\"reports.view_report_xyz\", role_is(13))\n\n\nSetting up rules\n----------------\n\nLet's pretend that we want to let authors edit or delete their books, but not\nbooks written by other authors. So, essentially, what determines whether an\nauthor *can edit* or *can delete* a given book is *whether they are its\nauthor*.\n\nIn ``rules``, such requirements are modelled as *rules*. A *rule* is a map of\na unique identifier (eg. \"can edit\") to a predicate. Rules are grouped\ntogether into a *rule set*. ``rules`` has two predefined rule sets:\n\n* A default rule set storing shared rules.\n* Another rule set storing rules that serve as permissions in a Django\n context.\n\nSo, let's define our first couple of rules, adding them to the shared rule\nset. We can use the ``is_book_author`` predicate we defined earlier:\n\n.. code:: python\n\n >>> rules.add_rule('can_edit_book', is_book_author)\n >>> rules.add_rule('can_delete_book', is_book_author)\n\nAssuming we've got some data, we can now test our rules:\n\n.. code:: python\n\n >>> from django.contrib.auth.models import User\n >>> from books.models import Book\n >>> guidetodjango = Book.objects.get(isbn='978-1-4302-1936-1')\n >>> guidetodjango.author\n <User: adrian>\n >>> adrian = User.objects.get(username='adrian')\n >>> rules.test_rule('can_edit_book', adrian, guidetodjango)\n True\n >>> rules.test_rule('can_delete_book', adrian, guidetodjango)\n True\n\nNice... but not awesome.\n\n\nCombining predicates\n--------------------\n\nPredicates by themselves are not so useful -- not more useful than any other\nfunction would be. Predicates, however, can be combined using binary operators\nto create more complex ones. Predicates support the following operators:\n\n* ``P1 & P2``: Returns a new predicate that returns ``True`` if *both*\n predicates return ``True``, otherwise ``False``. If P1 returns ``False``,\n P2 will not be evaluated.\n* ``P1 | P2``: Returns a new predicate that returns ``True`` if *any* of the\n predicates returns ``True``, otherwise ``False``. If P1 returns ``True``,\n P2 will not be evaluated.\n* ``P1 ^ P2``: Returns a new predicate that returns ``True`` if one of the\n predicates returns ``True`` and the other returns ``False``, otherwise\n ``False``.\n* ``~P``: Returns a new predicate that returns the negated result of the\n original predicate.\n\nSuppose the requirement for allowing a user to edit a given book was for them\nto be either the book's author, or a member of the \"editors\" group. Allowing\nusers to delete a book should still be determined by whether the user is the\nbook's author.\n\nWith ``rules`` that's easy to implement. We'd have to define another\npredicate, that would return ``True`` if the given user is a member of the\n\"editors\" group, ``False`` otherwise. The built-in ``is_group_member`` factory\nwill come in handy:\n\n.. code:: python\n\n >>> is_editor = rules.is_group_member('editors')\n >>> is_editor\n <Predicate:is_group_member:editors object at 0x10eee1350>\n\nWe could combine it with the ``is_book_author`` predicate to create a new one\nthat checks for either condition:\n\n.. code:: python\n\n >>> is_book_author_or_editor = is_book_author | is_editor\n >>> is_book_author_or_editor\n <Predicate:(is_book_author | is_group_member:editors) object at 0x10eee1390>\n\nWe can now update our ``can_edit_book`` rule:\n\n.. code:: python\n\n >>> rules.set_rule('can_edit_book', is_book_author_or_editor)\n >>> rules.test_rule('can_edit_book', adrian, guidetodjango)\n True\n >>> rules.test_rule('can_delete_book', adrian, guidetodjango)\n True\n\nLet's see what happens with another user:\n\n.. code:: python\n\n >>> martin = User.objects.get(username='martin')\n >>> list(martin.groups.values_list('name', flat=True))\n ['editors']\n >>> rules.test_rule('can_edit_book', martin, guidetodjango)\n True\n >>> rules.test_rule('can_delete_book', martin, guidetodjango)\n False\n\nAwesome.\n\nSo far, we've only used the underlying, generic framework for defining and\ntesting rules. This layer is not at all specific to Django; it may be used in\nany context. There's actually no import of anything Django-related in the\nwhole app (except in the ``rules.templatetags`` module). ``rules`` however can\nintegrate tightly with Django to provide authorization.\n\n\n.. _authorization in Django:\n\nUsing Rules with Django\n=======================\n\n``rules`` is able to provide object-level permissions in Django. It comes\nwith an authorization backend and a couple template tags for use in your\ntemplates.\n\n\nPermissions\n-----------\n\nIn ``rules``, permissions are a specialised type of rules. You still define\nrules by creating and combining predicates. These rules however, must be added\nto a permissions-specific rule set that comes with ``rules`` so that they can\nbe picked up by the ``rules`` authorization backend.\n\n\nCreating permissions\n++++++++++++++++++++\n\nThe convention for naming permissions in Django is ``app_label.action_object``,\nand we like to adhere to that. Let's add rules for the ``books.change_book``\nand ``books.delete_book`` permissions:\n\n.. code:: python\n\n >>> rules.add_perm('books.change_book', is_book_author | is_editor)\n >>> rules.add_perm('books.delete_book', is_book_author)\n\nSee the difference in the API? ``add_perm`` adds to a permissions-specific\nrule set, whereas ``add_rule`` adds to a default shared rule set. It's\nimportant to know however, that these two rule sets are separate, meaning that\nadding a rule in one does not make it available to the other.\n\n\nChecking for permission\n+++++++++++++++++++++++\n\nLet's go ahead and check whether ``adrian`` has change permission to the\n``guidetodjango`` book:\n\n.. code:: python\n\n >>> adrian.has_perm('books.change_book', guidetodjango)\n False\n\nWhen you call the ``User.has_perm`` method, Django asks each backend in\n``settings.AUTHENTICATION_BACKENDS`` whether a user has the given permission\nfor the object. When queried for object permissions, Django's default\nauthentication backend always returns ``False``. ``rules`` comes with an\nauthorization backend, that is able to provide object-level permissions by\nlooking into the permissions-specific rule set.\n\nLet's add the ``rules`` authorization backend in settings:\n\n.. code:: python\n\n AUTHENTICATION_BACKENDS = (\n 'rules.permissions.ObjectPermissionBackend',\n 'django.contrib.auth.backends.ModelBackend',\n )\n\nNow, checking again gives ``adrian`` the required permissions:\n\n.. code:: python\n\n >>> adrian.has_perm('books.change_book', guidetodjango)\n True\n >>> adrian.has_perm('books.delete_book', guidetodjango)\n True\n >>> martin.has_perm('books.change_book', guidetodjango)\n True\n >>> martin.has_perm('books.delete_book', guidetodjango)\n False\n\n**NOTE:** Calling `has_perm` on a superuser will ALWAYS return `True`.\n\nPermissions in models\n---------------------\n\n**NOTE:** The features described in this section work on Python 3+ only.\n\nIt is common to have a set of permissions for a model, like what Django offers with\nits default model permissions (such as *add*, *change* etc.). When using ``rules``\nas the permission checking backend, you can declare object-level permissions for\nany model in a similar way, using a new ``Meta`` option.\n\nFirst, you need to switch your model's base and metaclass to the slightly extended\nversions provided in ``rules.contrib.models``. There are several classes and mixins\nyou can use, depending on whether you're already using a custom base and/or metaclass\nfor your models or not. The extensions are very slim and don't affect the models'\nbehavior in any way other than making it register permissions.\n\n* If you're using the stock ``django.db.models.Model`` as base for your models,\n simply switch over to ``RulesModel`` and you're good to go.\n\n* If you already have a custom base class adding common functionality to your models,\n add ``RulesModelMixin`` to the classes it inherits from and set ``RulesModelBase``\n as its metaclass, like so::\n\n from django.db.models import Model\n from rules.contrib.models import RulesModelBase, RulesModelMixin\n\n class MyModel(RulesModelMixin, Model, metaclass=RulesModelBase):\n ...\n\n* If you're using a custom metaclass for your models, you'll already know how to\n make it inherit from ``RulesModelBaseMixin`` yourself.\n\nThen, create your models like so, assuming you're using ``RulesModel`` as base\ndirectly::\n\n import rules\n from rules.contrib.models import RulesModel\n\n class Book(RulesModel):\n class Meta:\n rules_permissions = {\n \"add\": rules.is_staff,\n \"read\": rules.is_authenticated,\n }\n\nThis would be equivalent to the following calls::\n\n rules.add_perm(\"app_label.add_book\", rules.is_staff)\n rules.add_perm(\"app_label.read_book\", rules.is_authenticated)\n\nThere are methods in ``RulesModelMixin`` that you can overwrite in order to customize\nhow a model's permissions are registered. See the documented source code for details\nif you need this.\n\nOf special interest is the ``get_perm`` classmethod of ``RulesModelMixin``, which can\nbe used to convert a permission type to the corresponding full permission name. If\nyou need to query for some type of permission on a given model programmatically,\nthis is handy::\n\n if user.has_perm(Book.get_perm(\"read\")):\n ...\n\n\nPermissions in views\n--------------------\n\n``rules`` comes with a set of view decorators to help you enforce\nauthorization in your views.\n\nUsing the function-based view decorator\n+++++++++++++++++++++++++++++++++++++++\n\nFor function-based views you can use the ``permission_required`` decorator:\n\n.. code:: python\n\n from django.shortcuts import get_object_or_404\n from rules.contrib.views import permission_required\n from posts.models import Post\n\n def get_post_by_pk(request, post_id):\n return get_object_or_404(Post, pk=post_id)\n\n @permission_required('posts.change_post', fn=get_post_by_pk)\n def post_update(request, post_id):\n # ...\n\nUsage is straight-forward, but there's one thing in the example above that\nstands out and this is the ``get_post_by_pk`` function. This function, given\nthe current request and all arguments passed to the view, is responsible for\nfetching and returning the object to check permissions against -- i.e. the\n``Post`` instance with PK equal to the given ``post_id`` in the example.\nThis specific use-case is quite common so, to save you some typing, ``rules``\ncomes with a generic helper function that you can use to do this declaratively.\nThe example below is equivalent to the one above:\n\n.. code:: python\n\n from rules.contrib.views import permission_required, objectgetter\n from posts.models import Post\n\n @permission_required('posts.change_post', fn=objectgetter(Post, 'post_id'))\n def post_update(request, post_id):\n # ...\n\nFor more information on the decorator and helper function, refer to the\n``rules.contrib.views`` module.\n\nUsing the class-based view mixin\n++++++++++++++++++++++++++++++++\n\nDjango includes a set of access mixins that you can use in your class-based\nviews to enforce authorization. ``rules`` extends this framework to provide\nobject-level permissions via a mixin, ``PermissionRequiredMixin``.\n\nThe following example will automatically test for permission against the\ninstance returned by the view's ``get_object`` method:\n\n.. code:: python\n\n from django.views.generic.edit import UpdateView\n from rules.contrib.views import PermissionRequiredMixin\n from posts.models import Post\n\n class PostUpdate(PermissionRequiredMixin, UpdateView):\n model = Post\n permission_required = 'posts.change_post'\n\nYou can customise the object either by overriding ``get_object`` or\n``get_permission_object``.\n\nFor more information refer to the `Django documentation`_ and the\n``rules.contrib.views`` module.\n\n.. _Django documentation: https://docs.djangoproject.com/en/1.9/topics/auth/default/#limiting-access-to-logged-in-users\n\nChecking permission automatically based on view type\n++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nIf you use the mechanisms provided by ``rules.contrib.models`` to register permissions\nfor your models as described in `Permissions in models`_, there's another convenient\nmixin for class-based views available for you.\n\n``rules.contrib.views.AutoPermissionRequiredMixin`` can recognize the type of view\nit's used with and check for the corresponding permission automatically.\n\nThis example view would, without any further configuration, automatically check for\nthe ``\"posts.change_post\"`` permission, given that the app label is ``\"posts\"``::\n\n from django.views.generic import UpdateView\n from rules.contrib.views import AutoPermissionRequiredMixin\n from posts.models import Post\n\n class UpdatePostView(AutoPermissionRequiredMixin, UpdateView):\n model = Post\n\nBy default, the generic CRUD views from ``django.views.generic`` are mapped to the\nnative Django permission types (*add*, *change*, *delete* and *view*). However,\nthe pre-defined mappings can be extended, changed or replaced altogether when\nsubclassing ``AutoPermissionRequiredMixin``. See the fully documented source code\nfor details on how to do that properly.\n\n\nPermissions and rules in templates\n----------------------------------\n\n``rules`` comes with two template tags to allow you to test for rules and\npermissions in templates.\n\nAdd ``rules`` to your ``INSTALLED_APPS``:\n\n.. code:: python\n\n INSTALLED_APPS = (\n # ...\n 'rules',\n )\n\nThen, in your template::\n\n {% load rules %}\n\n {% has_perm 'books.change_book' author book as can_edit_book %}\n {% if can_edit_book %}\n ...\n {% endif %}\n\n {% test_rule 'has_super_feature' user as has_super_feature %}\n {% if has_super_feature %}\n ...\n {% endif %}\n\n\nPermissions in the Admin\n------------------------\n\nIf you've setup ``rules`` to be used with permissions in Django, you're almost\nset to also use ``rules`` to authorize any add/change/delete actions in the\nAdmin. The Admin asks for *four* different permissions, depending on action:\n\n- ``<app_label>.add_<modelname>``\n- ``<app_label>.view_<modelname>``\n- ``<app_label>.change_<modelname>``\n- ``<app_label>.delete_<modelname>``\n- ``<app_label>``\n\n*Note:* view permission is new in Django v2.1 and should not be added in versions before that.\n\nThe first four are obvious. The fifth is the required permission for an app\nto be displayed in the Admin's \"dashboard\". Overriding it does not restrict access to the add,\nchange or delete views. Here's some rules for our imaginary ``books`` app as an example:\n\n.. code:: python\n\n >>> rules.add_perm('books', rules.always_allow)\n >>> rules.add_perm('books.add_book', is_staff)\n >>> rules.add_perm('books.view_book', is_staff | has_secret_access_code)\n >>> rules.add_perm('books.change_book', is_staff)\n >>> rules.add_perm('books.delete_book', is_staff)\n\nDjango Admin does not support object-permissions, in the sense that it will\nnever ask for permission to perform an action *on an object*, only whether a\nuser is allowed to act on (*any*) instances of a model.\n\nIf you'd like to tell Django whether a user has permissions on a specific\nobject, you'd have to override the following methods of a model's\n``ModelAdmin``:\n\n- ``has_view_permission(user, obj=None)``\n- ``has_change_permission(user, obj=None)``\n- ``has_delete_permission(user, obj=None)``\n\n``rules`` comes with a custom ``ModelAdmin`` subclass,\n``rules.contrib.admin.ObjectPermissionsModelAdmin``, that overrides these\nmethods to pass on the edited model instance to the authorization backends,\nthus enabling permissions per object in the Admin:\n\n.. code:: python\n\n # books/admin.py\n from django.contrib import admin\n from rules.contrib.admin import ObjectPermissionsModelAdmin\n from .models import Book\n\n class BookAdmin(ObjectPermissionsModelAdmin):\n pass\n\n admin.site.register(Book, BookAdmin)\n\nNow this allows you to specify permissions like this:\n\n.. code:: python\n\n >>> rules.add_perm('books', rules.always_allow)\n >>> rules.add_perm('books.add_book', has_author_profile)\n >>> rules.add_perm('books.change_book', is_book_author_or_editor)\n >>> rules.add_perm('books.delete_book', is_book_author)\n\nTo preserve backwards compatibility, Django will ask for either *view* or\n*change* permission. For maximum flexibility, ``rules`` behaves subtly\ndifferent: ``rules`` will ask for the change permission if and only if no rule\nexists for the view permission.\n\n\nPermissions in Django Rest Framework\n------------------------------------\n\nSimilar to ``rules.contrib.views.AutoPermissionRequiredMixin``, there is a\n``rules.contrib.rest_framework.AutoPermissionViewSetMixin`` for viewsets in Django\nRest Framework. The difference is that it doesn't derive permission from the type\nof view but from the API action (*create*, *retrieve* etc.) that's tried to be\nperformed. Of course, it also requires you to declare your models as described in\n`Permissions in models`_.\n\nHere is a possible ``ModelViewSet`` for the ``Post`` model with fully automated CRUD\npermission checking::\n\n from rest_framework.serializers import ModelSerializer\n from rest_framework.viewsets import ModelViewSet\n from rules.contrib.rest_framework import AutoPermissionViewSetMixin\n from posts.models import Post\n\n class PostSerializer(ModelSerializer):\n class Meta:\n model = Post\n fields = \"__all__\"\n\n class PostViewSet(AutoPermissionViewSetMixin, ModelViewSet):\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n\nBy default, the CRUD actions of ``ModelViewSet`` are mapped to the native\nDjango permission types (*add*, *change*, *delete* and *view*). The ``list``\naction has no permission checking enabled. However, the pre-defined mappings\ncan be extended, changed or replaced altogether when using (or subclassing)\n``AutoPermissionViewSetMixin``. Custom API actions defined via the ``@action``\ndecorator may then be mapped as well. See the fully documented source code for\ndetails on how to properly customize the default behavior.\n\n\nAdvanced features\n=================\n\nCustom rule sets\n----------------\n\nYou may create as many rule sets as you need:\n\n.. code:: python\n\n >>> features = rules.RuleSet()\n\nAnd manipulate them by adding, removing, querying and testing rules:\n\n.. code:: python\n\n >>> features.rule_exists('has_super_feature')\n False\n >>> is_special_user = rules.is_group_member('special')\n >>> features.add_rule('has_super_feature', is_special_user)\n >>> 'has_super_feature' in features\n True\n >>> features['has_super_feature']\n <Predicate:is_group_member:special object at 0x10eeaa500>\n >>> features.test_rule('has_super_feature', adrian)\n True\n >>> features.remove_rule('has_super_feature')\n\nNote however that custom rule sets are *not available* in Django templates --\nyou need to provide integration yourself.\n\n\nInvocation context\n------------------\n\nA new context is created as a result of invoking ``Predicate.test()`` and is\nonly valid for the duration of the invocation. A context is a simple ``dict``\nthat you can use to store arbitrary data, (eg. caching computed values,\nsetting flags, etc.), that can be used by predicates later on in the chain.\nInside a predicate function it can be used like so:\n\n.. code:: python\n\n >>> @predicate\n ... def mypred(a, b):\n ... value = compute_expensive_value(a)\n ... mypred.context['value'] = value\n ... return True\n\nOther predicates can later use stored values:\n\n.. code:: python\n\n >>> @predicate\n ... def myotherpred(a, b):\n ... value = myotherpred.context.get('value')\n ... if value is not None:\n ... return do_something_with_value(value)\n ... else:\n ... return do_something_without_value()\n\n``Predicate.context`` provides a single ``args`` attribute that contains the\narguments as given to ``test()`` at the beginning of the invocation.\n\n\nBinding \"self\"\n--------------\n\nIn a predicate's function body, you can refer to the predicate instance itself\nby its name, eg. ``is_book_author``. Passing ``bind=True`` as a keyword\nargument to the ``predicate`` decorator will let you refer to the predicate\nwith ``self``, which is more convenient. Binding ``self`` is just syntactic\nsugar. As a matter of fact, the following two are equivalent:\n\n.. code:: python\n\n >>> @predicate\n ... def is_book_author(user, book):\n ... if is_book_author.context.args:\n ... return user == book.author\n ... return False\n\n >>> @predicate(bind=True)\n ... def is_book_author(self, user, book):\n ... if self.context.args:\n ... return user == book.author\n ... return False\n\n\nSkipping predicates\n-------------------\n\nYou may skip evaluation by returning ``None`` from your predicate:\n\n.. code:: python\n\n >>> @predicate(bind=True)\n ... def is_book_author(self, user, book):\n ... if len(self.context.args) > 1:\n ... return user == book.author\n ... else:\n ... return None\n\nReturning ``None`` signifies that the predicate need not be evaluated, thus\nleaving the predicate result up to that point unchanged.\n\n\nLogging predicate evaluation\n----------------------------\n\n``rules`` can optionally be configured to log debug information as rules are\nevaluated to help with debugging your predicates. Messages are sent at the\nDEBUG level to the ``'rules'`` logger. The following `dictConfig`_ configures\na console logger (place this in your project's `settings.py` if you're using\n`rules` with Django):\n\n.. code:: python\n\n LOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'rules': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n },\n }\n\nWhen this logger is active each individual predicate will have a log message\nprinted when it is evaluated.\n\n.. _dictConfig: https://docs.python.org/3.6/library/logging.config.html#logging-config-dictschema\n\n\nBest practices\n==============\n\nBefore you can test for rules, these rules must be registered with a rule set,\nand for this to happen the modules containing your rule definitions must be\nimported.\n\nFor complex projects with several predicates and rules, it may not be\npractical to define all your predicates and rules inside one module. It might\nbe best to split them among any sub-components of your project. In a Django\ncontext, these sub-components could be the apps for your project.\n\nOn the other hand, because importing predicates from all over the place in\norder to define rules can lead to circular imports and broken hearts, it's\nbest to further split predicates and rules in different modules.\n\n``rules`` may optionally be configured to autodiscover ``rules.py`` modules in\nyour apps and import them at startup. To have ``rules`` do so, just edit your\n``INSTALLED_APPS`` setting:\n\n.. code:: python\n\n INSTALLED_APPS = (\n # replace 'rules' with:\n 'rules.apps.AutodiscoverRulesConfig',\n )\n\n**Note:** On Python 2, you must also add the following to the top of your\n``rules.py`` file, or you'll get import errors trying to import ``rules``\nitself:\n\n.. code:: python\n\n from __future__ import absolute_import\n\n\nAPI Reference\n=============\n\nThe core APIs are accessible from the root ``rules`` module. Django-specific\nfunctionality for the Admin and views is available from ``rules.contrib``.\n\n\nClass ``rules.Predicate``\n-------------------------\n\nYou create ``Predicate`` instances by passing in a callable:\n\n.. code:: python\n\n >>> def is_book_author(user, book):\n ... return book.author == user\n ...\n >>> pred = Predicate(is_book_author)\n >>> pred\n <Predicate:is_book_author object at 0x10eeaa490>\n\nYou may optionally provide a different name for the predicate that is used\nwhen inspecting it:\n\n.. code:: python\n\n >>> pred = Predicate(is_book_author, name='another_name')\n >>> pred\n <Predicate:another_name object at 0x10eeaa490>\n\nAlso, you may optionally provide ``bind=True`` in order to be able to access\nthe predicate instance with ``self``:\n\n.. code:: python\n\n >>> def is_book_author(self, user, book):\n ... if self.context.args:\n ... return user == book.author\n ... return False\n ...\n >>> pred = Predicate(is_book_author, bind=True)\n >>> pred\n <Predicate:is_book_author object at 0x10eeaa490>\n\n\nInstance methods\n++++++++++++++++\n\n``test(obj=None, target=None)``\n Returns the result of calling the passed in callable with zero, one or two\n positional arguments, depending on how many it accepts.\n\n\nClass ``rules.RuleSet``\n-----------------------\n\n``RuleSet`` extends Python's built-in `dict`_ type. Therefore, you may create\nand use a rule set any way you'd use a dict.\n\n.. _dict: http://docs.python.org/library/stdtypes.html#mapping-types-dict\n\n\nInstance methods\n++++++++++++++++\n\n``add_rule(name, predicate)``\n Adds a predicate to the rule set, assigning it to the given rule name.\n Raises ``KeyError`` if another rule with that name already exists.\n\n``set_rule(name, predicate)``\n Set the rule with the given name, regardless if one already exists.\n\n``remove_rule(name)``\n Remove the rule with the given name. Raises ``KeyError`` if a rule with\n that name does not exist.\n\n``rule_exists(name)``\n Returns ``True`` if a rule with the given name exists, ``False`` otherwise.\n\n``test_rule(name, obj=None, target=None)``\n Returns the result of calling ``predicate.test(obj, target)`` where\n ``predicate`` is the predicate for the rule with the given name. Returns\n ``False`` if a rule with the given name does not exist.\n\nDecorators\n----------\n\n``@predicate``\n Decorator that creates a predicate out of any callable:\n\n .. code:: python\n\n >>> @predicate\n ... def is_book_author(user, book):\n ... return book.author == user\n ...\n >>> is_book_author\n <Predicate:is_book_author object at 0x10eeaa490>\n\n Customising the predicate name:\n\n .. code:: python\n\n >>> @predicate(name='another_name')\n ... def is_book_author(user, book):\n ... return book.author == user\n ...\n >>> is_book_author\n <Predicate:another_name object at 0x10eeaa490>\n\n Binding ``self``:\n\n .. code:: python\n\n >>> @predicate(bind=True)\n ... def is_book_author(self, user, book):\n ... if 'user_has_special_flag' in self.context:\n ... return self.context['user_has_special_flag']\n ... return book.author == user\n\n\nPredefined predicates\n---------------------\n\n``always_allow()``, ``always_true()``\n Always returns ``True``.\n\n``always_deny()``, ``always_false()``\n Always returns ``False``.\n\n``is_authenticated(user)``\n Returns the result of calling ``user.is_authenticated()``. Returns\n ``False`` if the given user does not have an ``is_authenticated`` method.\n\n``is_superuser(user)``\n Returns the result of calling ``user.is_superuser``. Returns ``False``\n if the given user does not have an ``is_superuser`` property.\n\n``is_staff(user)``\n Returns the result of calling ``user.is_staff``. Returns ``False`` if the\n given user does not have an ``is_staff`` property.\n\n``is_active(user)``\n Returns the result of calling ``user.is_active``. Returns ``False`` if the\n given user does not have an ``is_active`` property.\n\n``is_group_member(*groups)``\n Factory that creates a new predicate that returns ``True`` if the given\n user is a member of *all* the given groups, ``False`` otherwise.\n\n\nShortcuts\n---------\n\nManaging the shared rule set\n++++++++++++++++++++++++++++\n\n``add_rule(name, predicate)``\n Adds a rule to the shared rule set. See ``RuleSet.add_rule``.\n\n``set_rule(name, predicate)``\n Set the rule with the given name from the shared rule set. See\n ``RuleSet.set_rule``.\n\n``remove_rule(name)``\n Remove a rule from the shared rule set. See ``RuleSet.remove_rule``.\n\n``rule_exists(name)``\n Returns whether a rule exists in the shared rule set. See\n ``RuleSet.rule_exists``.\n\n``test_rule(name, obj=None, target=None)``\n Tests the rule with the given name. See ``RuleSet.test_rule``.\n\n\nManaging the permissions rule set\n+++++++++++++++++++++++++++++++++\n\n``add_perm(name, predicate)``\n Adds a rule to the permissions rule set. See ``RuleSet.add_rule``.\n\n``set_perm(name, predicate)``\n Replace a rule from the permissions rule set. See ``RuleSet.set_rule``.\n\n``remove_perm(name)``\n Remove a rule from the permissions rule set. See ``RuleSet.remove_rule``.\n\n``perm_exists(name)``\n Returns whether a rule exists in the permissions rule set. See\n ``RuleSet.rule_exists``.\n\n``has_perm(name, user=None, obj=None)``\n Tests the rule with the given name. See ``RuleSet.test_rule``.\n\n\nLicence\n=======\n\n``django-rules`` is distributed under the MIT licence.\n\nCopyright (c) 2014 Akis Kesoglou\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Awesome Django authorization, without the database",
"version": "3.4",
"project_urls": {
"Homepage": "http://github.com/dfunckt/django-rules"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "9a3f495dd85d24f194167fa36805970ede547aa8f395b8fb8d6fe6cf593bd274",
"md5": "8ae3442bc9772ed42c3c6c4046ba2172",
"sha256": "e906114d9b3cce73871213c6311b94cb26a5bc2c3b00aa2f13d3633a65447817"
},
"downloads": -1,
"filename": "rules-3.4-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "8ae3442bc9772ed42c3c6c4046ba2172",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 25656,
"upload_time": "2024-05-18T10:40:57",
"upload_time_iso_8601": "2024-05-18T10:40:57.109544Z",
"url": "https://files.pythonhosted.org/packages/9a/3f/495dd85d24f194167fa36805970ede547aa8f395b8fb8d6fe6cf593bd274/rules-3.4-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "63dd06b3621f65133680297215d23567b4b83f939fe5a7b6ce92244d70950b94",
"md5": "1aae2b886b7d6bc310cc88475adaeec6",
"sha256": "c4702c1d60ca43e97d4dfced31e98274c652dea3c461105d8df6186d663e3212"
},
"downloads": -1,
"filename": "rules-3.4.tar.gz",
"has_sig": false,
"md5_digest": "1aae2b886b7d6bc310cc88475adaeec6",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 55479,
"upload_time": "2024-05-18T10:40:59",
"upload_time_iso_8601": "2024-05-18T10:40:59.429238Z",
"url": "https://files.pythonhosted.org/packages/63/dd/06b3621f65133680297215d23567b4b83f939fe5a7b6ce92244d70950b94/rules-3.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-18 10:40:59",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "dfunckt",
"github_project": "django-rules",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "rules"
}