pax_global_header00006660000000000000000000000064132140525450014513gustar00rootroot0000000000000052 comment=ec0d0905240cd1e4d79724fd53f7fd461023a3bf django-rules-1.3.0/000077500000000000000000000000001321405254500141065ustar00rootroot00000000000000django-rules-1.3.0/.coveragerc000066400000000000000000000002131321405254500162230ustar00rootroot00000000000000[report] exclude_lines = pragma: no cover omit = */python?.?/* */site-packages/nose/* */rules/compat/* */rules/apps.py django-rules-1.3.0/.gitignore000066400000000000000000000001521321405254500160740ustar00rootroot00000000000000*.egg-info *.pyc *~ ._* .coverage .DS_Store .Python __pycache__ dist/ docs/_build pip-log.txt .tox .eggs/ django-rules-1.3.0/.travis.yml000066400000000000000000000035511321405254500162230ustar00rootroot00000000000000# --------------------------------------------------------------------------- # Python support matrix per Django version # # 2.6 1.5 1.6 # 2.7 1.5 1.6 1.7 1.8 1.9 1.10 1.11 # 3.3 1.5 1.6 1.7 1.8 # 3.4 1.7 1.8 1.9 1.10 1.11 2.0 # 3.5 1.8 1.9 1.10 1.11 2.0 # 3.6 1.10 1.11 2.0 # --------------------------------------------------------------------------- sudo: false language: python matrix: include: - { python: 2.6, env: TOXENV=py26-django15 } - { python: 2.6, env: TOXENV=py26-django16 } - { python: 2.7, env: TOXENV=py27-django15 } - { python: 2.7, env: TOXENV=py27-django16 } - { python: 2.7, env: TOXENV=py27-django17 } - { python: 2.7, env: TOXENV=py27-django18 } - { python: 2.7, env: TOXENV=py27-django19 } - { python: 2.7, env: TOXENV=py27-django110 } - { python: 2.7, env: TOXENV=py27-django111 } - { python: 3.3, env: TOXENV=py33-django15 } - { python: 3.3, env: TOXENV=py33-django16 } - { python: 3.3, env: TOXENV=py33-django17 } - { python: 3.3, env: TOXENV=py33-django18 } - { python: 3.4, env: TOXENV=py34-django17 } - { python: 3.4, env: TOXENV=py34-django18 } - { python: 3.4, env: TOXENV=py34-django19 } - { python: 3.4, env: TOXENV=py34-django110 } - { python: 3.4, env: TOXENV=py34-django20 } - { python: 3.4, env: TOXENV=py34-django111 } - { python: 3.5, env: TOXENV=py35-django18 } - { python: 3.5, env: TOXENV=py35-django19 } - { python: 3.5, env: TOXENV=py35-django110 } - { python: 3.5, env: TOXENV=py35-django111 } - { python: 3.5, env: TOXENV=py35-django20 } - { python: 3.6, env: TOXENV=py36-django110 } - { python: 3.6, env: TOXENV=py36-django111 } - { python: 3.6, env: TOXENV=py36-django20 } install: - pip install tox script: tox after_success: - coveralls django-rules-1.3.0/CHANGELOG.md000066400000000000000000000030671321405254500157250ustar00rootroot00000000000000Changelog ========= ## v1.3.0 - 2017/12/13 - Added support for Django 2.0 - Added support for Django 1.11 and Python 3.6 - Dropped support for PyPy and PyPy3 ## v1.2.1 - 2017/05/13 - Reverted "Fixed undesired caching in `is_group_member` factory" ## v1.2.0 - 2016/12/18 - Added logging to predicates - Added support for Django 1.10 - Fixed undesired caching in `is_group_member` factory ## v1.1.1 - 2015/12/07 - Improved handling of skipped predicates ## v1.1.0 - 2015/12/05 - Fixed regression that wouldn't short-circuit boolean expressions - Added support for Django 1.9 and Python 3.5 - Added support for skipping predicates simply by returning `None`. The previous way of skipping predicates by raising `SkipPredicate` has been deprecated and will not be supported in a future release. ## v1.0.0 - 2015/10/06 - Initial stable public release - Dropped support for Python 3.2 - Added Django test suite - Added function-based view decorator - Added class-based view mixin ## v0.4 - 2015/02/16 - Added support for creating predicates from partial functions - Added support for creating predicates from instance methods - Added predicate invocation context - Added support for automatically passing `self` to a predicate - Added support for discarding a predicate's result ## v0.3 - 2014/10/15 - Added compatibility with PyPy and PyPy 3 - Added `always_true()` and `always_false()` predicates - Added integration with Tox - Bug fixes ## v0.2 - 2014/06/09 - Added compatibility with Python 3.4 - Improved admin integration ## v0.1 - 2014/03/07 - Initial public release django-rules-1.3.0/INSTALL000066400000000000000000000000751321405254500151410ustar00rootroot00000000000000 Please use:: $ python setup.py install See README.rst django-rules-1.3.0/LICENSE000066400000000000000000000020411321405254500151100ustar00rootroot00000000000000Copyright (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. django-rules-1.3.0/MANIFEST.in000066400000000000000000000002511321405254500156420ustar00rootroot00000000000000include CHANGELOG.md include INSTALL include LICENSE include README.rst recursive-include tests * global-exclude *.pyc global-exclude .coverage global-exclude .DS_Store django-rules-1.3.0/README.rst000066400000000000000000000711631321405254500156050ustar00rootroot00000000000000django-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://travis-ci.org/dfunckt/django-rules.svg?branch=master :target: https://travis-ci.org/dfunckt/django-rules .. 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.python.org/pypi/rules .. image:: https://img.shields.io/pypi/pyversions/rules.svg :target: https://pypi.python.org/pypi/rules .. _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`_ - `How to install`_ - `Configuring Django`_ - `Using Rules`_ - `Creating predicates`_ - `Setting up rules`_ - `Combining predicates`_ - `Using Rules with Django`_ - `Permissions`_ - `Rules and permissions in views`_ - `Rules and permissions in templates`_ - `Rules and permissions in the Admin`_ - `Advanced features`_ - `Custom rule sets`_ - `Invocation context`_ - `Binding "self"`_ - `Skipping predicates`_ - `Logging predicate evaluation`_ - `Best practices`_ - `API Reference`_ - `Licence`_ Requirements ============ ``rules`` requires Python 2.6/3.3 or newer. It can optionally integrate with Django, in which case requires Django 1.5 or newer. 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 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`_. 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 >>> 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 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 We can now update our ``can_edit_book`` rule: .. code:: python >>> rules.add_rule('can_edit_book', is_book_author_or_editor) Traceback (most recent call last): ... KeyError: A rule with name `can_edit_book` already exists >>> rules.remove_rule('can_edit_book') >>> rules.add_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 Rules and 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 1.9 introduced a new set of access mixins that you can use in your class-based views to enforce authorization. ``rules`` extends this framework to provide a mixin for object-level permissions, ``PermissionRequiredMixin``. Note that ``rules`` will seamlessly fall back to importing its own copy of Django's access mixins module for versions of Django prior to 1.9. 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 Rules and permissions 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 %} Rules and 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: - ``.add_`` - ``.change_`` - ``.delete_`` - ```` The first three are obvious. The fourth is the required permission for an app to be displayed in the Admin's "dashboard". 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.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_change_permission(user, obj=None)`` - ``has_delete_permission(user, obj=None)`` **Note:** There's also ``has_add_permission(user)`` but is not relevant here. ``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) 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'] >>> 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. **Note:** This is new in version 1.1.0. It was possible to skip predicates in older versions by calling the predicate's ``skip()`` method, but this has been deprecated and support will be completely removed in a future version. 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. If using Django 1.7 and later, ``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 ``django-rules`` itself: .. code:: python from __future__ import absolute_import API Reference ============= Everything is accessible from the root ``rules`` module. 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 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 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 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. ``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 Customising the predicate name: .. code:: python >>> @predicate(name='another_name') ... def is_book_author(user, book): ... return book.author == user ... >>> is_book_author 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``. ``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``. ``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. django-rules-1.3.0/rules/000077500000000000000000000000001321405254500152405ustar00rootroot00000000000000django-rules-1.3.0/rules/__init__.py000066400000000000000000000007001321405254500173460ustar00rootroot00000000000000from .rulesets import RuleSet, add_rule, remove_rule, rule_exists, test_rule from .permissions import add_perm, remove_perm, perm_exists, has_perm from .predicates import (Predicate, predicate, always_true, always_false, always_allow, always_deny, is_authenticated, is_superuser, is_staff, is_active, is_group_member) VERSION = (1, 3, 0, 'final', 1) default_app_config = 'rules.apps.RulesConfig' django-rules-1.3.0/rules/apps.py000066400000000000000000000004031321405254500165520ustar00rootroot00000000000000from django.apps import AppConfig class RulesConfig(AppConfig): name = 'rules' class AutodiscoverRulesConfig(RulesConfig): def ready(self): from django.utils.module_loading import autodiscover_modules autodiscover_modules('rules') django-rules-1.3.0/rules/compat/000077500000000000000000000000001321405254500165235ustar00rootroot00000000000000django-rules-1.3.0/rules/compat/__init__.py000066400000000000000000000000001321405254500206220ustar00rootroot00000000000000django-rules-1.3.0/rules/compat/access_mixins.py000066400000000000000000000133141321405254500217270ustar00rootroot00000000000000""" This is a copy of django.contrib.auth.mixins module, shipped with django-rules for compatibility with Django versions before 1.9. Used under permission by the Django Software Foundation. Copyright (c) Django Software Foundation and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.utils import six from django.utils.encoding import force_text class AccessMixin(object): """ Abstract CBV mixin that gives access mixins the same customizable functionality. """ login_url = None permission_denied_message = '' raise_exception = False redirect_field_name = REDIRECT_FIELD_NAME def get_login_url(self): """ Override this method to override the login_url attribute. """ login_url = self.login_url or settings.LOGIN_URL if not login_url: raise ImproperlyConfigured( '{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override ' '{0}.get_login_url().'.format(self.__class__.__name__) ) return force_text(login_url) def get_permission_denied_message(self): """ Override this method to override the permission_denied_message attribute. """ return self.permission_denied_message def get_redirect_field_name(self): """ Override this method to override the redirect_field_name attribute. """ return self.redirect_field_name def handle_no_permission(self): if self.raise_exception: raise PermissionDenied(self.get_permission_denied_message()) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) class LoginRequiredMixin(AccessMixin): """ CBV mixin which verifies that the current user is authenticated. """ def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated(): return self.handle_no_permission() return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) class PermissionRequiredMixin(AccessMixin): """ CBV mixin which verifies that the current user has all specified permissions. """ permission_required = None def get_permission_required(self): """ Override this method to override the permission_required attribute. Must return an iterable. """ if self.permission_required is None: raise ImproperlyConfigured( '{0} is missing the permission_required attribute. Define {0}.permission_required, or override ' '{0}.get_permission_required().'.format(self.__class__.__name__) ) if isinstance(self.permission_required, six.string_types): perms = (self.permission_required, ) else: perms = self.permission_required return perms def has_permission(self): """ Override this method to customize the way permissions are checked. """ perms = self.get_permission_required() return self.request.user.has_perms(perms) def dispatch(self, request, *args, **kwargs): if not self.has_permission(): return self.handle_no_permission() return super(PermissionRequiredMixin, self).dispatch(request, *args, **kwargs) class UserPassesTestMixin(AccessMixin): """ CBV Mixin that allows you to define a test function which must return True if the current user can access the view. """ def test_func(self): raise NotImplementedError( '{0} is missing the implementation of the test_func() method.'.format(self.__class__.__name__) ) def get_test_func(self): """ Override this method to use a different test_func method. """ return self.test_func def dispatch(self, request, *args, **kwargs): user_test_result = self.get_test_func()() if not user_test_result: return self.handle_no_permission() return super(UserPassesTestMixin, self).dispatch(request, *args, **kwargs) django-rules-1.3.0/rules/contrib/000077500000000000000000000000001321405254500167005ustar00rootroot00000000000000django-rules-1.3.0/rules/contrib/__init__.py000066400000000000000000000000001321405254500207770ustar00rootroot00000000000000django-rules-1.3.0/rules/contrib/admin.py000066400000000000000000000035271321405254500203510ustar00rootroot00000000000000from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): def has_change_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('delete', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) class ObjectPermissionsInlineModelAdminMixin(ObjectPermissionsModelAdminMixin): def has_change_permission(self, request, obj=None): # pragma: no cover opts = self.opts if opts.auto_created: for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): # pragma: no cover if self.opts.auto_created: return self.has_change_permission(request, obj) return super(ObjectPermissionsInlineModelAdminMixin, self).has_delete_permission(request, obj) class ObjectPermissionsModelAdmin(ObjectPermissionsModelAdminMixin, admin.ModelAdmin): pass class ObjectPermissionsStackedInline(ObjectPermissionsInlineModelAdminMixin, admin.StackedInline): pass class ObjectPermissionsTabularInline(ObjectPermissionsInlineModelAdminMixin, admin.TabularInline): pass django-rules-1.3.0/rules/contrib/views.py000066400000000000000000000143621321405254500204150ustar00rootroot00000000000000from functools import wraps from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied, ImproperlyConfigured, FieldError from django.shortcuts import get_object_or_404 from django.utils import six from django.utils.decorators import available_attrs from django.utils.encoding import force_text try: from django.contrib.auth import mixins except ImportError: # pragma: no cover # Django < 1.9 from ..compat import access_mixins as mixins # These are made available for convenience, as well as for use in Django # versions before 1.9. For usage help see Django's docs for 1.9 or later. LoginRequiredMixin = mixins.LoginRequiredMixin UserPassesTestMixin = mixins.UserPassesTestMixin class PermissionRequiredMixin(mixins.PermissionRequiredMixin): """ CBV mixin to provide object-level permission checking to views. Best used with views that inherit from ``SingleObjectMixin`` (``DetailView``, ``UpdateView``, etc.), though not required. The single requirement is for a ``get_object`` method to be available in the view. If there's no ``get_object`` method, permission checking is model-level, that is exactly like Django's ``PermissionRequiredMixin``. """ def get_permission_object(self): """ Override this method to provide the object to check for permission against. By default uses ``self.get_object()`` as provided by ``SingleObjectMixin``. Returns None if there's no ``get_object`` method. """ try: # Requires SingleObjectMixin or equivalent ``get_object`` method return self.get_object() except AttributeError: # pragma: no cover return None def has_permission(self): obj = self.get_permission_object() perms = self.get_permission_required() return self.request.user.has_perms(perms, obj) def objectgetter(model, attr_name='pk', field_name='pk'): """ Helper that returns a function suitable for use as the ``fn`` argument to the ``permission_required`` decorator. Internally uses ``get_object_or_404``, so keep in mind that this may raise ``Http404``. ``model`` can be a model class, manager or queryset. ``attr_name`` is the name of the view attribute. ``field_name`` is the model's field name by which the lookup is made, eg. "id", "slug", etc. """ def _getter(request, *view_args, **view_kwargs): if attr_name not in view_kwargs: raise ImproperlyConfigured( 'Argument {0} is not available. Given arguments: [{1}]' .format(attr_name, ', '.join(view_kwargs.keys()))) try: return get_object_or_404(model, **{field_name: view_kwargs[attr_name]}) except FieldError: raise ImproperlyConfigured( 'Model {0} has no field named {1}' .format(model, field_name)) return _getter def permission_required(perm, fn=None, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: 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): # ... ``perm`` is either a permission name as a string, or a list of permission names. ``fn`` is an optional callback that receives the same arguments as those passed to the decorated view and must return the object to check permissions against. If omitted, the decorator behaves just like Django's ``permission_required`` decorator, i.e. checks for model-level permissions. ``raise_exception`` is a boolean specifying whether to raise a ``django.core.exceptions.PermissionDenied`` exception if the check fails. You will most likely want to set this argument to ``True`` if you have specified a custom 403 response handler in your urlconf. If ``False``, the user will be redirected to the URL specified by ``login_url``. ``login_url`` is an optional custom URL to redirect the user to if permissions check fails. If omitted or empty, ``settings.LOGIN_URL`` is used. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # Normalize to a list of permissions if isinstance(perm, six.string_types): perms = (perm,) else: perms = perm # Get the object to check permissions against if callable(fn): obj = fn(request, *args, **kwargs) else: obj = fn # Get the user user = request.user # Check for permissions and return a response if not user.has_perms(perms, obj): # User does not have a required permission if raise_exception: raise PermissionDenied() else: return _redirect_to_login(request, view_func.__name__, login_url, redirect_field_name) else: # User has all required permissions -- allow the view to execute return view_func(request, *args, **kwargs) return _wrapped_view return decorator def _redirect_to_login(request, view_name, login_url, redirect_field_name): redirect_url = login_url or settings.LOGIN_URL if not redirect_url: # pragma: no cover raise ImproperlyConfigured( 'permission_required({0}): You must either provide ' 'the "login_url" argument to the "permission_required" ' 'decorator or configure settings.LOGIN_URL'.format(view_name) ) redirect_url = force_text(redirect_url) return redirect_to_login(request.get_full_path(), redirect_url, redirect_field_name) django-rules-1.3.0/rules/permissions.py000066400000000000000000000012101321405254500201570ustar00rootroot00000000000000from .rulesets import RuleSet permissions = RuleSet() def add_perm(name, pred): permissions.add_rule(name, pred) def remove_perm(name): permissions.remove_rule(name) def perm_exists(name): return permissions.rule_exists(name) def has_perm(name, *args, **kwargs): return permissions.test_rule(name, *args, **kwargs) class ObjectPermissionBackend(object): def authenticate(self, username, password): return None def has_perm(self, user, perm, *args, **kwargs): return has_perm(perm, user, *args, **kwargs) def has_module_perms(self, user, app_label): return has_perm(app_label, user) django-rules-1.3.0/rules/predicates.py000066400000000000000000000231111321405254500177330ustar00rootroot00000000000000import inspect import logging import operator import threading from functools import partial, update_wrapper from warnings import warn logger = logging.getLogger('rules') class SkipPredicate(Exception): """ Use to reject usage of a predicate. """ def __init__(self, *args, **kwargs): warn('Skipping predicates by raising the SkipPredicate exception ' 'has been deprecated. Return `None` from your predicate instead.', DeprecationWarning) super(SkipPredicate, self).__init__(*args, **kwargs) class Context(dict): def __init__(self, args): super(Context, self).__init__() self.args = args class localcontext(threading.local): def __init__(self): self.stack = [] _context = localcontext() class NoValueSentinel(object): def __bool__(self): return False __nonzero__ = __bool__ # python 2 NO_VALUE = NoValueSentinel() del NoValueSentinel class Predicate(object): def __init__(self, fn, name=None, bind=False): # fn can be a callable with any of the following signatures: # - fn(obj=None, target=None) # - fn(obj=None) # - fn() assert callable(fn), 'The given predicate is not callable.' if isinstance(fn, Predicate): fn, num_args, var_args, name = fn.fn, fn.num_args, fn.var_args, name or fn.name elif isinstance(fn, partial): argspec = inspect.getargspec(fn.func) var_args = argspec.varargs is not None num_args = len(argspec.args) - len(fn.args) if inspect.ismethod(fn.func): num_args -= 1 # skip `self` name = fn.func.__name__ elif inspect.ismethod(fn): argspec = inspect.getargspec(fn) var_args = argspec.varargs is not None num_args = len(argspec.args) - 1 # skip `self` elif inspect.isfunction(fn): argspec = inspect.getargspec(fn) var_args = argspec.varargs is not None num_args = len(argspec.args) elif isinstance(fn, object): callfn = getattr(fn, '__call__') argspec = inspect.getargspec(callfn) var_args = argspec.varargs is not None num_args = len(argspec.args) - 1 # skip `self` name = name or type(fn).__name__ else: # pragma: no cover # We handle all cases, so there's no way we can reach here raise TypeError('Incompatible predicate.') if bind: num_args -= 1 assert num_args <= 2, 'Incompatible predicate.' self.fn = fn self.num_args = num_args self.var_args = var_args self.name = name or fn.__name__ self.bind = bind def __repr__(self): return '<%s:%s object at %s>' % ( type(self).__name__, str(self), hex(id(self))) def __str__(self): return self.name def __call__(self, *args, **kwargs): # this method is defined as variadic in order to not mask the # underlying callable's signature that was most likely decorated # as a predicate. internally we consistently call ``_apply`` that # provides a single interface to the callable. if self.bind: return self.fn(self, *args, **kwargs) return self.fn(*args, **kwargs) @property def context(self): """ The currently active invocation context. A new context is created as a result of invoking ``test()`` and is only valid for the duration of the invocation. Can be used by predicates to store arbitrary data, eg. for 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:: >>> @predicate ... def mypred(a, b): ... value = compute_expensive_value(a) ... mypred.context['value'] = value ... return True ... Other predicates can later use stored values:: >>> @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() ... """ try: return _context.stack[-1] except IndexError: return None def skip(self): """ Use this method in a predicate body to signal that it should be ignored for the current invocation. """ raise SkipPredicate() def test(self, obj=NO_VALUE, target=NO_VALUE): """ The canonical method to invoke predicates. """ args = tuple(arg for arg in (obj, target) if arg is not NO_VALUE) _context.stack.append(Context(args)) logger.debug('Testing %s', self) try: return bool(self._apply(*args)) finally: _context.stack.pop() def __and__(self, other): def AND(*args): return self._combine(other, operator.and_, args) return type(self)(AND, '(%s & %s)' % (self.name, other.name)) def __or__(self, other): def OR(*args): return self._combine(other, operator.or_, args) return type(self)(OR, '(%s | %s)' % (self.name, other.name)) def __xor__(self, other): def XOR(*args): return self._combine(other, operator.xor, args) return type(self)(XOR, '(%s ^ %s)' % (self.name, other.name)) def __invert__(self): def INVERT(*args): result = self._apply(*args) return None if result is None else not result if self.name.startswith('~'): name = self.name[1:] else: name = '~' + self.name return type(self)(INVERT, name) def _combine(self, other, op, args): self_result = self._apply(*args) if self_result is None: return other._apply(*args) # short-circuit evaluation if op is operator.and_ and not self_result: return False elif op is operator.or_ and self_result: return True other_result = other._apply(*args) if other_result is None: return self_result return op(self_result, other_result) def _apply(self, *args): # Internal method that is used to invoke the predicate with the # proper number of positional arguments, inside the current # invocation context. if self.var_args: callargs = args elif self.num_args > len(args): callargs = args + (None,) * (self.num_args - len(args)) else: callargs = args[:self.num_args] if self.bind: callargs = (self,) + callargs try: result = self.fn(*callargs) result = None if result is None else bool(result) except SkipPredicate: result = None logger.debug(' %s = %s', self, 'skipped' if result is None else result) return result def predicate(fn=None, name=None, **options): """ Decorator that constructs a ``Predicate`` instance from any function:: >>> @predicate ... def is_book_author(user, book): ... return user == book.author ... >>> @predicate(bind=True) ... def is_book_author(self, user, book): ... if self.context.args: ... return user == book.author """ if not name and not callable(fn): name = fn fn = None def inner(fn): if isinstance(fn, Predicate): return fn p = Predicate(fn, name, **options) update_wrapper(p, fn) return p if fn: return inner(fn) else: return inner # Predefined predicates always_true = predicate(lambda: True, name='always_true') always_false = predicate(lambda: False, name='always_false') always_allow = predicate(lambda: True, name='always_allow') always_deny = predicate(lambda: False, name='always_deny') def is_bool_like(obj): return hasattr(obj, '__bool__') or hasattr(obj, '__nonzero__') @predicate def is_authenticated(user): if not hasattr(user, 'is_authenticated'): return False # not a user model if not is_bool_like(user.is_authenticated): # pragma: no cover # Django < 1.10 return user.is_authenticated() return user.is_authenticated @predicate def is_superuser(user): if not hasattr(user, 'is_superuser'): return False # swapped user model, doesn't support is_superuser return user.is_superuser @predicate def is_staff(user): if not hasattr(user, 'is_staff'): return False # swapped user model, doesn't support is_staff return user.is_staff @predicate def is_active(user): if not hasattr(user, 'is_active'): return False # swapped user model, doesn't support is_active return user.is_active def is_group_member(*groups): assert len(groups) > 0, 'You must provide at least one group name' if len(groups) > 3: g = groups[:3] + ('...',) else: g = groups name = 'is_group_member:%s' % ','.join(g) @predicate(name) def fn(user): if not hasattr(user, 'groups'): return False # swapped user model, doesn't support groups if not hasattr(user, '_group_names_cache'): # pragma: no cover user._group_names_cache = set(user.groups.values_list('name', flat=True)) return set(groups).issubset(user._group_names_cache) return fn django-rules-1.3.0/rules/rulesets.py000066400000000000000000000016201321405254500174570ustar00rootroot00000000000000from .predicates import predicate class RuleSet(dict): def test_rule(self, name, *args, **kwargs): return name in self and self[name].test(*args, **kwargs) def rule_exists(self, name): return name in self def add_rule(self, name, pred): if name in self: raise KeyError('A rule with name `%s` already exists' % name) self[name] = pred def remove_rule(self, name): del self[name] def __setitem__(self, name, pred): fn = predicate(pred) super(RuleSet, self).__setitem__(name, fn) # Shared rule set default_rules = RuleSet() def add_rule(name, pred): default_rules.add_rule(name, pred) def remove_rule(name): default_rules.remove_rule(name) def rule_exists(name): return default_rules.rule_exists(name) def test_rule(name, *args, **kwargs): return default_rules.test_rule(name, *args, **kwargs) django-rules-1.3.0/rules/templatetags/000077500000000000000000000000001321405254500177325ustar00rootroot00000000000000django-rules-1.3.0/rules/templatetags/__init__.py000066400000000000000000000000001321405254500220310ustar00rootroot00000000000000django-rules-1.3.0/rules/templatetags/rules.py000066400000000000000000000011151321405254500214340ustar00rootroot00000000000000from django import template from ..rulesets import default_rules register = template.Library() try: # Django < 2.0 simple_tag = register.assignment_tag except AttributeError: # pragma: no cover simple_tag = register.simple_tag @simple_tag def test_rule(name, obj=None, target=None): return default_rules.test_rule(name, obj, target) @simple_tag def has_perm(perm, user, obj=None): if not hasattr(user, 'has_perm'): # pragma: no cover return False # swapped user model that doesn't support permissions else: return user.has_perm(perm, obj) django-rules-1.3.0/runtests.py000077500000000000000000000017201321405254500163520ustar00rootroot00000000000000#!/usr/bin/env python import sys from os import environ from os.path import abspath, dirname, join import nose def main(): project_dir = dirname(abspath(__file__)) # setup path sys.path.insert(0, project_dir) # project dir sys.path.insert(0, join(project_dir, 'tests')) # tests dir environ['DJANGO_SETTINGS_MODULE'] = 'testapp.settings' try: # django >= 1.7 from django import setup except ImportError: pass else: setup() # setup test env from django.test.utils import setup_test_environment setup_test_environment() # setup db from django.core.management import call_command, CommandError options = { 'interactive': False, 'verbosity': 1, } try: call_command('migrate', **options) except CommandError: # Django < 1.7 call_command('syncdb', **options) # run tests return nose.main() if __name__ == '__main__': main() django-rules-1.3.0/runtests.sh000077500000000000000000000002061321405254500163320ustar00rootroot00000000000000#!/bin/sh coverage run --source=rules runtests.py --nologcapture --nocapture "$@" result=$? echo coverage report -m echo exit $result django-rules-1.3.0/setup.cfg000066400000000000000000000001141321405254500157230ustar00rootroot00000000000000[nosetests] verbosity=2 cover-package=rules cover-erase=1 #cover-branches=1 django-rules-1.3.0/setup.py000066400000000000000000000037701321405254500156270ustar00rootroot00000000000000#!/usr/bin/env python from os.path import dirname, join try: from setuptools import setup except ImportError: from distutils.core import setup from rules import VERSION def get_version(version): """ Returns a PEP 386-compliant version number from ``version``. """ assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') parts = 2 if version[2] == 0 else 3 main = '.'.join(str(x) for x in version[:parts]) sub = '' if version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return main + sub with open(join(dirname(__file__), 'README.rst')) as f: long_description = f.read() setup( name='rules', description='Awesome Django authorization, without the database', version=get_version(VERSION), long_description=long_description, url='http://github.com/dfunckt/django-rules', author='Akis Kesoglou', author_email='akiskesoglou@gmail.com', maintainer='Akis Kesoglou', maintainer_email='akiskesoglou@gmail.com', license='MIT', zip_safe=False, packages=[ 'rules', 'rules.templatetags', 'rules.contrib', 'rules.compat', ], install_requires=[ # 'Django >= 1.5', ], tests_require=[ 'nose', 'coverage', 'Django >= 1.5', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], ) django-rules-1.3.0/tests/000077500000000000000000000000001321405254500152505ustar00rootroot00000000000000django-rules-1.3.0/tests/manage.py000077500000000000000000000006641321405254500170630ustar00rootroot00000000000000#!/usr/bin/env python import os import sys from os.path import abspath, dirname, join if __name__ == "__main__": project_dir = dirname(dirname(abspath(__file__))) sys.path.insert(0, project_dir) sys.path.insert(0, join(project_dir, 'tests')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) django-rules-1.3.0/tests/testapp/000077500000000000000000000000001321405254500167305ustar00rootroot00000000000000django-rules-1.3.0/tests/testapp/__init__.py000066400000000000000000000000001321405254500210270ustar00rootroot00000000000000django-rules-1.3.0/tests/testapp/admin.py000066400000000000000000000003761321405254500204000ustar00rootroot00000000000000from __future__ import absolute_import from django.contrib import admin from rules.contrib.admin import ObjectPermissionsModelAdmin from .models import Book class BookAdmin(ObjectPermissionsModelAdmin): pass admin.site.register(Book, BookAdmin) django-rules-1.3.0/tests/testapp/migrations/000077500000000000000000000000001321405254500211045ustar00rootroot00000000000000django-rules-1.3.0/tests/testapp/migrations/0001_initial.py000066400000000000000000000015511321405254500235510ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-05 09:27 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('isbn', models.CharField(max_length=50, unique=True)), ('title', models.CharField(max_length=100)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] django-rules-1.3.0/tests/testapp/migrations/__init__.py000066400000000000000000000000001321405254500232030ustar00rootroot00000000000000django-rules-1.3.0/tests/testapp/models.py000066400000000000000000000006371321405254500205730ustar00rootroot00000000000000from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Book(models.Model): isbn = models.CharField(max_length=50, unique=True) title = models.CharField(max_length=100) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title django-rules-1.3.0/tests/testapp/rules.py000066400000000000000000000007461321405254500204430ustar00rootroot00000000000000from __future__ import absolute_import import rules # Predicates @rules.predicate def is_book_author(user, book): if not book: return False return book.author == user is_editor = rules.is_group_member('editors') # Rules rules.add_rule('change_book', is_book_author | is_editor) rules.add_rule('delete_book', is_book_author) # Permissions rules.add_perm('testapp.change_book', is_book_author | is_editor) rules.add_perm('testapp.delete_book', is_book_author) django-rules-1.3.0/tests/testapp/settings.py000066400000000000000000000026541321405254500211510ustar00rootroot00000000000000from os.path import abspath, dirname BASE_DIR = dirname(dirname(abspath(__file__))) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = [ ('test@example.com', 'Administrator'), ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'rules', 'testapp', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] # Django < 2.0 MIDDLEWARE_CLASSES = MIDDLEWARE AUTHENTICATION_BACKENDS = [ 'rules.permissions.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', ] CACHE_BACKEND = 'locmem://' SECRET_KEY = 'thats-a-secret' ROOT_URLCONF = 'testapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] django-rules-1.3.0/tests/testapp/templates/000077500000000000000000000000001321405254500207265ustar00rootroot00000000000000django-rules-1.3.0/tests/testapp/templates/empty.html000066400000000000000000000000021321405254500227420ustar00rootroot00000000000000OKdjango-rules-1.3.0/tests/testapp/urls.py000066400000000000000000000022561321405254500202740ustar00rootroot00000000000000from django.conf.urls import url from django.contrib import admin from .views import (change_book, delete_book, view_that_raises, view_with_object, view_with_permission_list, BookUpdateView, BookDeleteView, ViewThatRaises, ViewWithPermissionList) admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), # Function-based views url(r'^(?P\d+)/change/$', change_book, name='change_book'), url(r'^(?P\d+)/delete/$', delete_book, name='delete_book'), url(r'^(?P\d+)/raise/$', view_that_raises, name='view_that_raises'), url(r'^(?P\d+)/object/$', view_with_object, name='view_with_object'), url(r'^(?P\d+)/list/$', view_with_permission_list, name='view_with_permission_list'), # Class-based views url(r'^cbv/(?P\d+)/change/$', BookUpdateView.as_view(), name='cbv.change_book'), url(r'^cbv/(?P\d+)/delete/$', BookDeleteView.as_view(), name='cbv.delete_book'), url(r'^cbv/(?P\d+)/raise/$', ViewThatRaises.as_view(), name='cbv.view_that_raises'), url(r'^cbv/(?P\d+)/list/$', ViewWithPermissionList.as_view(), name='cbv.view_with_permission_list'), ] django-rules-1.3.0/tests/testapp/views.py000066400000000000000000000036771321405254500204540ustar00rootroot00000000000000from __future__ import absolute_import from django.http import HttpResponse from django.views.generic.edit import UpdateView, DeleteView from rules.contrib.views import permission_required, objectgetter from rules.contrib.views import LoginRequiredMixin, PermissionRequiredMixin from .models import Book class BookMixin(object): def get_object(self): return Book.objects.get(pk=self.kwargs['book_id']) @permission_required('testapp.change_book', fn=objectgetter(Book, 'book_id')) def change_book(request, book_id): return HttpResponse('OK') class BookUpdateView(LoginRequiredMixin, PermissionRequiredMixin, BookMixin, UpdateView): fields = ['title'] template_name = 'empty.html' permission_required = 'testapp.change_book' @permission_required('testapp.delete_book', fn=objectgetter(Book, 'book_id')) def delete_book(request, book_id): return HttpResponse('OK') class BookDeleteView(LoginRequiredMixin, PermissionRequiredMixin, BookMixin, DeleteView): template_name = 'empty.html' permission_required = 'testapp.delete_book' @permission_required('testapp.delete_book', fn=objectgetter(Book, 'book_id'), raise_exception=True) def view_that_raises(request, book_id): return HttpResponse('OK') class ViewThatRaises(LoginRequiredMixin, PermissionRequiredMixin, BookMixin, DeleteView): template_name = 'empty.html' raise_exception = True permission_required = 'testapp.delete_book' @permission_required(['testapp.change_book', 'testapp.delete_book'], fn=objectgetter(Book, 'book_id')) def view_with_permission_list(request, book_id): return HttpResponse('OK') class ViewWithPermissionList(LoginRequiredMixin, PermissionRequiredMixin, BookMixin, DeleteView): template_name = 'empty.html' permission_required = ['testapp.change_book', 'testapp.delete_book'] @permission_required('testapp.delete_book', fn=Book.objects.get(pk=1)) def view_with_object(request, book_id): return HttpResponse('OK') django-rules-1.3.0/tests/testsuite/000077500000000000000000000000001321405254500173015ustar00rootroot00000000000000django-rules-1.3.0/tests/testsuite/__init__.py000066400000000000000000000000001321405254500214000ustar00rootroot00000000000000django-rules-1.3.0/tests/testsuite/contrib/000077500000000000000000000000001321405254500207415ustar00rootroot00000000000000django-rules-1.3.0/tests/testsuite/contrib/__init__.py000066400000000000000000000015151321405254500230540ustar00rootroot00000000000000from django.contrib.auth.models import User, Group from testapp.models import Book import testapp.rules # to register rules ISBN = '978-1-4302-1936-1' def setup_package(): adrian = User.objects.create_user('adrian', password='secr3t') adrian.is_superuser = True adrian.is_staff = True adrian.save() martin = User.objects.create_user('martin', password='secr3t') martin.is_staff = True martin.save() editors = Group.objects.create(name='editors') martin.groups.add(editors) Book.objects.create( isbn=ISBN, title='The Definitive Guide to Django', author=adrian) def teardown_package(): Book.objects.get(isbn=ISBN).delete() Group.objects.get(name='editors').delete() User.objects.get(username='adrian').delete() User.objects.get(username='martin').delete() django-rules-1.3.0/tests/testsuite/contrib/test_admin.py000066400000000000000000000026741321405254500234530ustar00rootroot00000000000000from django.test import TestCase try: from django.urls import reverse except ImportError: # django < 1.10 from django.core.urlresolvers import reverse try: from django.urls import reverse except ImportError: # Django < 2.0 from django.core.urlresolvers import reverse class ModelAdminTests(TestCase): def test_change_book(self): # adrian can change his book as its author self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('admin:testapp_book_change', args=(1,))) self.assertEqual(response.status_code, 200) # martin can change adrian's book as an editor self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('admin:testapp_book_change', args=(1,))) self.assertEqual(response.status_code, 200) def test_delete_book(self): # martin can *not* delete adrian's book self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('admin:testapp_book_delete', args=(1,))) self.assertEqual(response.status_code, 403) # adrian can delete his book as its author self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('admin:testapp_book_delete', args=(1,))) self.assertEqual(response.status_code, 200) django-rules-1.3.0/tests/testsuite/contrib/test_predicates.py000066400000000000000000000023111321405254500244720ustar00rootroot00000000000000from django.contrib.auth.models import User from rules.predicates import (is_authenticated, is_superuser, is_staff, is_active, is_group_member) class SwappedUser(object): pass def test_is_authenticated(): assert is_authenticated(User.objects.get(username='adrian')) assert not is_authenticated(SwappedUser()) def test_is_superuser(): assert is_superuser(User.objects.get(username='adrian')) assert not is_superuser(SwappedUser()) def test_is_staff(): assert is_staff(User.objects.get(username='adrian')) assert not is_staff(SwappedUser()) def test_is_active(): assert is_active(User.objects.get(username='adrian')) assert not is_active(SwappedUser()) def test_is_group_member(): p1 = is_group_member('somegroup') assert p1.name == 'is_group_member:somegroup' assert p1.num_args == 1 p2 = is_group_member('g1', 'g2', 'g3', 'g4') assert p2.name == 'is_group_member:g1,g2,g3,...' p = is_group_member('editors') assert p(User.objects.get(username='martin')) assert not p(SwappedUser()) p = is_group_member('editors', 'staff') assert not p(User.objects.get(username='martin')) assert not p(SwappedUser()) django-rules-1.3.0/tests/testsuite/contrib/test_templatetags.py000066400000000000000000000056131321405254500250510ustar00rootroot00000000000000from django.contrib.auth.models import User from django.template import Template, Context from django.test import TestCase from testapp.models import Book from . import ISBN class TemplateTagTests(TestCase): tpl_format = """{{% spaceless %}} {{% load rules %}} {{% {tag} "{name}" user book as can_update %}} {{% if can_update %}} OK {{% else %}} NOT OK {{% endif %}} {{% endspaceless %}}""" def test_rule_tag(self): # change_book rule tpl = Template(self.tpl_format.format(tag='test_rule', name='change_book')) # adrian can change his book as its author html = tpl.render(Context({ 'user': User.objects.get(username='adrian'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'OK') # martin can change adrian's book as an editor html = tpl.render(Context({ 'user': User.objects.get(username='martin'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'OK') # delete_book rule tpl = Template(self.tpl_format.format(tag='test_rule', name='delete_book')) # adrian can delete his book as its author html = tpl.render(Context({ 'user': User.objects.get(username='adrian'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'OK') # martin can *not* delete adrian's book html = tpl.render(Context({ 'user': User.objects.get(username='martin'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'NOT OK') def test_perm_tag(self): # change_book permission tpl = Template(self.tpl_format.format(tag='has_perm', name='testapp.change_book')) # adrian can change his book as its author html = tpl.render(Context({ 'user': User.objects.get(username='adrian'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'OK') # martin can change adrian's book as an editor html = tpl.render(Context({ 'user': User.objects.get(username='martin'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'OK') # delete_book permission tpl = Template(self.tpl_format.format(tag='has_perm', name='testapp.delete_book')) # adrian can delete his book as its author html = tpl.render(Context({ 'user': User.objects.get(username='adrian'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'OK') # martin can *not* delete adrian's book html = tpl.render(Context({ 'user': User.objects.get(username='martin'), 'book': Book.objects.get(isbn=ISBN), })) self.assertEqual(html, 'NOT OK') django-rules-1.3.0/tests/testsuite/contrib/test_views.py000066400000000000000000000142571321405254500235200ustar00rootroot00000000000000from __future__ import absolute_import from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest, Http404 from django.test import TestCase from django.utils.encoding import force_str try: from django.urls import reverse except ImportError: # Django < 2.0 from django.core.urlresolvers import reverse from rules.contrib.views import objectgetter from testapp.models import Book class FBVDecoratorTests(TestCase): def test_objectgetter(self): request = HttpRequest() book = Book.objects.get(pk=1) self.assertEqual(book, objectgetter(Book)(request, pk=1)) self.assertEqual(book, objectgetter(Book, attr_name='id')(request, id=1)) self.assertEqual(book, objectgetter(Book, field_name='id')(request, pk=1)) with self.assertRaises(ImproperlyConfigured): # Raise if no `pk` argument is provided to the view self.assertEqual(book, objectgetter(Book)(request, foo=1)) with self.assertRaises(ImproperlyConfigured): # Raise if given invalid model lookup field self.assertEqual(book, objectgetter(Book, field_name='foo')(request, pk=1)) with self.assertRaises(Http404): # Raise 404 if no model instance found self.assertEqual(book, objectgetter(Book)(request, pk=100000)) def test_permission_required(self): # Adrian can change his book self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('change_book', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Martin can change Adrian's book self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('change_book', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Adrian can delete his book self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('delete_book', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Martin can *not* delete Adrian's book and is redirected to login self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('delete_book', args=(1,))) self.assertEqual(response.status_code, 302) # Martin can *not* delete Adrian's book and an PermissionDenied is raised self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('view_that_raises', args=(1,))) self.assertEqual(response.status_code, 403) # Test views that require a list of permissions # Adrian has both permissions self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('view_with_permission_list', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Martin does not have delete permission self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('view_with_permission_list', args=(1,))) self.assertEqual(response.status_code, 302) # Test views that accept a static object as argument # fn is passed to has_perm as-is self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('view_with_object', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('view_with_object', args=(1,))) self.assertEqual(response.status_code, 302) class CBVMixinTests(TestCase): def test_permission_required_mixin(self): # Adrian can change his book self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('cbv.change_book', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Martin can change Adrian's book self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('cbv.change_book', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Adrian can delete his book self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('cbv.delete_book', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Martin can *not* delete Adrian's book and is redirected to login self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('cbv.delete_book', args=(1,))) self.assertEqual(response.status_code, 302) # Martin can *not* delete Adrian's book and an PermissionDenied is raised self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('cbv.view_that_raises', args=(1,))) self.assertEqual(response.status_code, 403) # Test views that require a list of permissions # Adrian has both permissions self.assertTrue(self.client.login(username='adrian', password='secr3t')) response = self.client.get(reverse('cbv.view_with_permission_list', args=(1,))) self.assertEqual(response.status_code, 200) self.assertEqual(force_str(response.content), 'OK') # Martin does not have delete permission self.assertTrue(self.client.login(username='martin', password='secr3t')) response = self.client.get(reverse('cbv.view_with_permission_list', args=(1,))) self.assertEqual(response.status_code, 302) django-rules-1.3.0/tests/testsuite/test_permissions.py000066400000000000000000000022021321405254500232610ustar00rootroot00000000000000from nose.tools import with_setup from rules.predicates import always_true from rules.permissions import (permissions, add_perm, remove_perm, perm_exists, has_perm, ObjectPermissionBackend) def reset_ruleset(ruleset): def fn(): for k in list(ruleset.keys()): ruleset.pop(k) return fn @with_setup(reset_ruleset(permissions), reset_ruleset(permissions)) def test_permissions_ruleset(): add_perm('can_edit_book', always_true) assert 'can_edit_book' in permissions assert perm_exists('can_edit_book') assert has_perm('can_edit_book') remove_perm('can_edit_book') assert not perm_exists('can_edit_book') @with_setup(reset_ruleset(permissions), reset_ruleset(permissions)) def test_backend(): backend = ObjectPermissionBackend() assert backend.authenticate('someuser', 'password') is None add_perm('can_edit_book', always_true) assert 'can_edit_book' in permissions assert backend.has_perm(None, 'can_edit_book') assert backend.has_module_perms(None, 'can_edit_book') remove_perm('can_edit_book') assert not perm_exists('can_edit_book') django-rules-1.3.0/tests/testsuite/test_predicates.py000066400000000000000000000260141321405254500230400ustar00rootroot00000000000000import functools import warnings from rules.predicates import ( NO_VALUE, Predicate, always_allow, always_deny, always_false, always_true, predicate, ) def test_always_true(): assert always_true() def test_always_false(): assert not always_false() def test_always_allow(): assert always_allow() def test_always_deny(): assert not always_deny() def test_lambda_predicate(): p = Predicate(lambda x: x == 'a') assert p.name == '' assert p.num_args == 1 assert p('a') def test_lambda_predicate_custom_name(): p = Predicate(lambda x: x == 'a', name='mypred') assert p.name == 'mypred' assert p.num_args == 1 assert p('a') def test_function_predicate(): def mypred(x): return x == 'a' p = Predicate(mypred) assert p.name == 'mypred' assert p.num_args == 1 assert p('a') def test_function_predicate_custom_name(): def mypred(x): return x == 'a' p = Predicate(mypred, name='foo') assert p.name == 'foo' assert p.num_args == 1 assert p('a') def test_partial_function_predicate(): def mypred(one, two, three): return one < two < three p = Predicate(functools.partial(mypred, 1)) assert p.name == 'mypred' assert p.num_args == 2 # 3 - 1 partial assert p(2, 3) p = Predicate(functools.partial(mypred, 1, 2)) assert p.name == 'mypred' assert p.num_args == 1 # 3 - 2 partial assert p(3) def test_method_predicate(): class SomeClass(object): def some_method(self, arg1, arg2): return arg1 == arg2 obj = SomeClass() p = Predicate(obj.some_method) assert p.name == 'some_method' assert p.num_args == 2 assert p(2, 2) def test_partial_method_predicate(): class SomeClass(object): def some_method(self, arg1, arg2): return arg1 == arg2 obj = SomeClass() p = Predicate(functools.partial(obj.some_method, 2)) assert p.name == 'some_method' assert p.num_args == 1 assert p(2) def test_class_predicate(): class callableclass(object): def __call__(self, arg1, arg2): return arg1 == arg2 fn = callableclass() p = Predicate(fn) assert p.name == 'callableclass' assert p.num_args == 2 assert p('a', 'a') def test_class_predicate_custom_name(): class callableclass(object): def __call__(self, arg): return arg == 'a' fn = callableclass() p = Predicate(fn, name='bar') assert p.name == 'bar' assert p.num_args == 1 assert p('a') def test_predicate_predicate(): def mypred(x): return x == 'a' p = Predicate(Predicate(mypred)) assert p.name == 'mypred' assert p.num_args == 1 assert p('a') def test_predicate_predicate_custom_name(): def mypred(x): return x == 'a' p = Predicate(Predicate(mypred, name='foo')) assert p.name == 'foo' assert p.num_args == 1 assert p('a') def test_predicate_bind(): @predicate(bind=True) def is_bound(self): return self is is_bound assert is_bound() p = None def mypred(self): return self is p p = Predicate(mypred, bind=True) assert p() def test_decorator(): @predicate def mypred(arg1, arg2): return True assert mypred.name == 'mypred' assert mypred.num_args == 2 def test_decorator_noargs(): @predicate() def mypred(arg1, arg2): return True assert mypred.name == 'mypred' assert mypred.num_args == 2 def test_decorator_custom_name(): @predicate('foo') def mypred(): return True assert mypred.name == 'foo' assert mypred.num_args == 0 @predicate(name='bar') def myotherpred(): return False assert myotherpred.name == 'bar' assert myotherpred.num_args == 0 def test_repr(): @predicate def mypred(arg1, arg2): return True assert repr(mypred).startswith(' 0 assert len(kwargs) == 0 assert p.num_args == 0 p.test('a') p.test('a', 'b') def test_no_args(): @predicate def p(*args, **kwargs): assert len(args) == 0 assert len(kwargs) == 0 assert p.num_args == 0 p.test() def test_one_arg(): @predicate def p(a=None, *args, **kwargs): assert len(args) == 0 assert len(kwargs) == 0 assert a == 'a' assert p.num_args == 1 p.test('a') def test_two_args(): @predicate def p(a=None, b=None, *args, **kwargs): assert len(args) == 0 assert len(kwargs) == 0 assert a == 'a' assert b == 'b' assert p.num_args == 2 p.test('a', 'b') def test_no_mask(): @predicate def p(a=None, b=None, *args, **kwargs): assert len(args) == 0 assert len(kwargs) == 1 'c' in kwargs assert a == 'a' assert b == 'b' p('a', b='b', c='c') def test_no_value_marker(): @predicate def p(a, b=None): assert a == 'a' assert b is None assert not NO_VALUE p.test('a') p.test('a', NO_VALUE) def test_short_circuit(): @predicate def skipped_predicate(self): return None @predicate def shorted_predicate(self): raise Exception('this predicate should not be evaluated') assert (always_false & shorted_predicate).test() is False assert (always_true | shorted_predicate).test() is True def raises(pred): try: pred.test() return False except Exception as e: return 'evaluated' in str(e) assert raises(always_true & shorted_predicate) assert raises(always_false | shorted_predicate) assert raises(skipped_predicate & shorted_predicate) assert raises(skipped_predicate | shorted_predicate) def test_skip_predicate_deprecation(): @predicate(bind=True) def skipped_predicate(self): self.skip() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert skipped_predicate.test() is False assert len(w) == 1 and 'deprecated' in str(w[-1].message) def test_skip_predicate(): @predicate(bind=True) def requires_two_args(self, a, b): return a == b if len(self.context.args) > 1 else None @predicate def passthrough(a): return a assert (requires_two_args & passthrough).test(True, True) is True assert (requires_two_args & passthrough).test(True, False) is False # because requires_two_args is called with only one argument # its result is not taken into account, only the result of the # other predicate matters. assert (requires_two_args & passthrough).test(True) is True assert (requires_two_args & passthrough).test(False) is False assert (requires_two_args | passthrough).test(True) is True assert (requires_two_args | passthrough).test(False) is False # test that order does not matter assert (passthrough & requires_two_args).test(True) is True assert (passthrough & requires_two_args).test(False) is False assert (passthrough | requires_two_args).test(True) is True assert (passthrough | requires_two_args).test(False) is False # test that inversion does not modify the result assert (~requires_two_args & passthrough).test(True) is True assert (~requires_two_args & passthrough).test(False) is False assert (~requires_two_args | passthrough).test(True) is True assert (~requires_two_args | passthrough).test(False) is False assert (passthrough & ~requires_two_args).test(True) is True assert (passthrough & ~requires_two_args).test(False) is False assert (passthrough | ~requires_two_args).test(True) is True assert (passthrough | ~requires_two_args).test(False) is False # test that when all predicates are skipped, result is False assert requires_two_args.test(True) is False assert (requires_two_args | requires_two_args).test(True) is False assert (requires_two_args & requires_two_args).test(True) is False # test that a skipped predicate doesn't alter the result at all assert (requires_two_args | requires_two_args | passthrough).test(True) is True assert (requires_two_args & requires_two_args & passthrough).test(True) is True def test_invocation_context(): @predicate def p1(): assert id(p1.context) == id(p2.context) assert p1.context.args == ('a',) return True @predicate def p2(): assert id(p1.context) == id(p2.context) assert p2.context.args == ('a',) return True p = p1 & p2 assert p.test('a') assert p.context is None def test_invocation_context_nested(): @predicate def p1(): assert p1.context.args == ('b1',) return True @predicate def p2(): assert p2.context.args == ('b2',) return True @predicate def p(): assert p1.context.args == ('a',) return p1.test('b1') & p2.test('b2') assert p.test('a') assert p.context is None def test_invocation_context_storage(): @predicate def p1(a): p1.context['p1.a'] = a return True @predicate def p2(a): return p2.context['p1.a'] == a p = p1 & p2 assert p.test('a') django-rules-1.3.0/tests/testsuite/test_rulesets.py000066400000000000000000000021221321405254500225550ustar00rootroot00000000000000from nose.tools import nottest, with_setup, assert_raises from rules.predicates import predicate from rules.rulesets import (RuleSet, default_rules, add_rule, remove_rule, rule_exists, test_rule) test_rule = nottest(test_rule) def reset_ruleset(ruleset): def fn(): for k in list(ruleset.keys()): ruleset.pop(k) return fn @predicate def always_true(): return True @with_setup(reset_ruleset(default_rules), reset_ruleset(default_rules)) def test_shared_ruleset(): add_rule('somerule', always_true) assert 'somerule' in default_rules assert rule_exists('somerule') assert test_rule('somerule') remove_rule('somerule') assert not rule_exists('somerule') def test_ruleset(): ruleset = RuleSet() ruleset.add_rule('somerule', always_true) assert 'somerule' in ruleset assert ruleset.rule_exists('somerule') assert ruleset.test_rule('somerule') assert_raises(KeyError, ruleset.add_rule, 'somerule', always_true) ruleset.remove_rule('somerule') assert not ruleset.rule_exists('somerule') django-rules-1.3.0/tox.ini000066400000000000000000000011731321405254500154230ustar00rootroot00000000000000[tox] envlist = {py26}-django{15,16}, {py27}-django{15,16,17,18,19,110,111}, {py33}-django{15,16,17,18}, {py34}-django{17,18,19,110,111,20}, {py35}-django{18,19,110,111,20}, {py36}-django{110,111,20} [testenv] deps = nose coverage django15: Django>=1.5,<1.6 django16: Django>=1.6,<1.7 django17: Django>=1.7,<1.8 django18: Django>=1.8,<1.9 django19: Django>=1.9,<1.10 django110: Django>=1.10,<1.11 django111: Django>=1.11,<1.12 django20: Django>=2.0,<2.1 commands = coverage run --source=rules runtests.py --nologcapture --nocapture {posargs} coverage report -m