pax_global_header00006660000000000000000000000064146653602500014521gustar00rootroot0000000000000052 comment=6ce69d03bab6831ecfa194765b42110439ebe1bb django-rules-3.5.0/000077500000000000000000000000001466536025000141205ustar00rootroot00000000000000django-rules-3.5.0/.github/000077500000000000000000000000001466536025000154605ustar00rootroot00000000000000django-rules-3.5.0/.github/workflows/000077500000000000000000000000001466536025000175155ustar00rootroot00000000000000django-rules-3.5.0/.github/workflows/ci.yml000066400000000000000000000045751466536025000206460ustar00rootroot00000000000000name: CI on: push: branches: - master pull_request: jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Python 3.10 uses: actions/setup-python@v4 with: python-version: "3.10" - uses: pre-commit/action@v2.0.2 with: token: ${{ secrets.GITHUB_TOKEN }} tests: name: Python ${{ matrix.python-version }} / Django ${{ matrix.django-version }} runs-on: ubuntu-latest needs: lint strategy: matrix: python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.10"] django-version: ["3.2", "4.2", "5.0", "5.1"] experimental: [false] include: - python-version: "3.12" django-version: "packaging" experimental: false - python-version: "3.12" django-version: "main" experimental: true exclude: # Unsupported Python versions for Django 5.0 - python-version: 3.8 django-version: 5.0 - python-version: 3.9 django-version: 5.0 # Unsupported Python versions for Django 5.1 - python-version: 3.8 django-version: 5.1 - python-version: 3.9 django-version: 5.1 steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools wheel python -m pip install --upgrade coveralls tox tox-py tox-venv tox-gh-actions - name: Tox tests run: tox -v continue-on-error: ${{ matrix.experimental }} env: DJANGO: ${{ matrix.django-version }} - name: Upload coverage data to coveralls.io if: ${{ matrix.python-version != 'pypy-3.10' }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} COVERALLS_FLAG_NAME: run-${{ matrix.python-version }} COVERALLS_PARALLEL: true run: coveralls --service=github finish: name: Indicate completion to coveralls.io needs: tests runs-on: ubuntu-latest steps: - name: Finalize publishing to coveralls.io uses: coverallsapp/github-action@master with: github-token: ${{ secrets.GITHUB_TOKEN }} parallel-finished: true django-rules-3.5.0/.github/workflows/publish.yml000066400000000000000000000016331466536025000217110ustar00rootroot00000000000000name: Publish Package to PyPi on: release: types: [released, prereleased] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build - name: Build run: | python -m build - name: Publish to PyPI Staging if: "github.event.release.prerelease" uses: pypa/gh-action-pypi-publish@release/v1 with: user: '__token__' password: ${{ secrets.TEST_PYPI_TOKEN }} repository_url: https://test.pypi.org/legacy/ - name: Publish to PyPI if: "!github.event.release.prerelease" uses: pypa/gh-action-pypi-publish@release/v1 with: user: '__token__' password: ${{ secrets.PYPI_TOKEN }} django-rules-3.5.0/.gitignore000066400000000000000000000001521466536025000161060ustar00rootroot00000000000000*.egg-info *.pyc *~ ._* .coverage .DS_Store .Python __pycache__ dist/ docs/_build pip-log.txt .tox .eggs/ django-rules-3.5.0/.pre-commit-config.yaml000066400000000000000000000015121466536025000204000ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-added-large-files - id: check-case-conflict - id: check-json - id: check-merge-conflict - id: check-symlinks - id: check-toml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black rev: 24.3.0 hooks: - id: black language_version: python3 - repo: https://github.com/pycqa/isort rev: 5.13.0 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 rev: 7.0.0 hooks: - id: flake8 additional_dependencies: - flake8-bugbear - flake8-comprehensions - repo: https://github.com/pre-commit/mirrors-mypy rev: "v1.9.0" hooks: - id: mypy - repo: https://github.com/mgedmin/check-manifest rev: "0.49" hooks: - id: check-manifest args: [--no-build-isolation] django-rules-3.5.0/CHANGELOG.md000066400000000000000000000073251466536025000157400ustar00rootroot00000000000000Changelog ========= ## Unreleased *Add a sentence for each interesting change in this section.* ------- ## v3.5.0 - 2024/09/02 - Add support for Django 5.1 ## v3.4.0 - 2024/05/18 - Add support for Django 4.2 and 5.0 - Add support for Python 3.11 and 3.12 - Drop support for EOL Python 3.7 - Drop support for EOL Django 2.2 and 4.0 - Fix bug: type annotations were not used because ``py.typed`` was not always installed. ## v3.3.0 - 2022/03/23 - Introduce type annotations for common APIs ## v3.2.1 - 2022/03/02 - Fixed incorrect Django versions mentioned in CHANGELOG ## v3.2.0 - 2022/03/02 - Added support for Python 3.10 - Dropped support for Python 3.6 (EOL) - Dropped support for Django 3.0 and 3.1 (EOL) ## v3.1.0 - 2021/12/22 - Added support for Django 4.0 ## v3.0.0 - 2021/05/10 - Dropped support for Python 2 - Dropped support for Django versions before 2.2 ## v2.2.0 - 2020/01/17 - Added support for Django v3.0 ## v2.1.0 - 2019/08/11 - Added ability to automatically check for permissions in Drango Rest Framework viewsets. - Added ability to automatically check for permissions in Drango class-based views. - Added ability to automatically register permissions for models. - Added shim for "six" in anticipation for Django 3.0 dropping support for Python 2 and removing "six" from its codebase. ## v2.0.1 - 2018/12/07 - Fixed issue with using ``rules`` in ``CreateView`` CBV ## v2.0.0 - 2018/07/22 - Dropped support for Python 2.6 and 3.3 - Dropped support for Django versions before 1.11 - Removed ``SkipPredicate`` exception and ``skip`` method of ``Predicate`` - Removed ``replace_rule`` and related APIs - Added ``set_rule`` and related APIs to safely replace a rule without having to ensure one already exists - Added compatibility with Django v2.1 - Re-introduced support for PyPy and PyPy 3 - Changed Python and Django supported versions policy to exclude end-of-life versions. Support for EOL'd versions will be dropped in minor version updates of ``rules`` from now on. ## v1.4.0 - 2018/07/21 - Fixed masking AttributeErrors raised from CBV get_object - Fixed compatibility with `inspect` in newer Python 3 versions - Added ability to replace rules and permissions ## 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-3.5.0/INSTALL000066400000000000000000000000751466536025000151530ustar00rootroot00000000000000 Please use:: $ python setup.py install See README.rst django-rules-3.5.0/LICENSE000066400000000000000000000020411466536025000151220ustar00rootroot00000000000000Copyright (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-3.5.0/MANIFEST.in000066400000000000000000000004251466536025000156570ustar00rootroot00000000000000include CHANGELOG.md include INSTALL include LICENSE include README.rst include runtests.sh recursive-include tests * global-exclude *.py[cod] __pycache__ global-exclude .coverage global-exclude .DS_Store exclude .pre-commit-config.yaml tox.ini recursive-include rules *.typed django-rules-3.5.0/README.rst000066400000000000000000001107721466536025000156170ustar00rootroot00000000000000rules ^^^^^ ``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 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 >>> 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.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/stable/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: - ``.add_`` - ``.view_`` - ``.change_`` - ``.delete_`` - ```` *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'] >>> 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 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. ``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 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``. ``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. django-rules-3.5.0/pyproject.toml000066400000000000000000000004351466536025000170360ustar00rootroot00000000000000[tool.black] target-version = ['py38', 'py39', 'py310'] [tool.isort] profile = "black" known_django = "django" known_first_party = ['django-rules'] sections = ['FUTURE', 'STDLIB', 'DJANGO', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'] skip=['migrations', '.git', '__pycache__', 'venv'] django-rules-3.5.0/rules/000077500000000000000000000000001466536025000152525ustar00rootroot00000000000000django-rules-3.5.0/rules/__init__.py000066400000000000000000000007271466536025000173710ustar00rootroot00000000000000from .permissions import add_perm, has_perm, perm_exists, remove_perm, set_perm # noqa from .predicates import ( # noqa Predicate, always_allow, always_deny, always_false, always_true, is_active, is_authenticated, is_group_member, is_staff, is_superuser, predicate, ) from .rulesets import ( # noqa RuleSet, add_rule, remove_rule, rule_exists, set_rule, test_rule, ) VERSION = (3, 5, 0, "final", 1) django-rules-3.5.0/rules/apps.py000066400000000000000000000004541466536025000165720ustar00rootroot00000000000000from django.apps import AppConfig class RulesConfig(AppConfig): name = "rules" default = True class AutodiscoverRulesConfig(RulesConfig): default = False def ready(self): from django.utils.module_loading import autodiscover_modules autodiscover_modules("rules") django-rules-3.5.0/rules/contrib/000077500000000000000000000000001466536025000167125ustar00rootroot00000000000000django-rules-3.5.0/rules/contrib/__init__.py000066400000000000000000000000001466536025000210110ustar00rootroot00000000000000django-rules-3.5.0/rules/contrib/admin.py000066400000000000000000000041111466536025000203510ustar00rootroot00000000000000from django.contrib import admin from django.contrib.auth import get_permission_codename from ..permissions import perm_exists class ObjectPermissionsModelAdminMixin(object): def has_view_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename("view", opts) perm = "%s.%s" % (opts.app_label, codename) if perm_exists(perm): return request.user.has_perm(perm, obj) else: return self.has_change_permission(request, obj) 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-3.5.0/rules/contrib/models.py000066400000000000000000000060711466536025000205530ustar00rootroot00000000000000from django.core.exceptions import ImproperlyConfigured from django.db.models import Model from django.db.models.base import ModelBase from ..permissions import add_perm class RulesModelBaseMixin: """ Mixin for the metaclass of Django's Model that allows declaring object-level permissions in the model's Meta options. If set, the Meta attribute "rules_permissions" has to be a dictionary with permission types (like "add" or "change") as keys and predicates (like rules.is_staff) as values. Permissions are then registered with the rules framework automatically upon Model creation. This mixin can be used for creating custom metaclasses. """ def __new__(cls, name, bases, attrs, **kwargs): model_meta = attrs.get("Meta") if hasattr(model_meta, "rules_permissions"): perms = model_meta.rules_permissions del model_meta.rules_permissions if not isinstance(perms, dict): raise ImproperlyConfigured( "The rules_permissions Meta option of %s must be a dict, not %s." % (name, type(perms)) ) perms = perms.copy() else: perms = {} new_class = super().__new__(cls, name, bases, attrs, **kwargs) new_class._meta.rules_permissions = perms new_class.preprocess_rules_permissions(perms) for perm_type, predicate in perms.items(): add_perm(new_class.get_perm(perm_type), predicate) return new_class class RulesModelBase(RulesModelBaseMixin, ModelBase): """ A subclass of Django's ModelBase with the RulesModelBaseMixin mixed in. """ class RulesModelMixin: """ A mixin for Django's Model that adds hooks for stepping into the process of permission registration, which are called by the metaclass implementation in RulesModelBaseMixin. Use this mixin in a custom subclass of Model in order to change its behavior. """ @classmethod def get_perm(cls, perm_type): """Converts permission type ("add") to permission name ("app.add_modelname") :param perm_type: "add", "change", etc., or custom value :type perm_type: str :returns str: """ return "%s.%s_%s" % (cls._meta.app_label, perm_type, cls._meta.model_name) @classmethod def preprocess_rules_permissions(cls, perms): """May alter a permissions dict before it's processed further. Use this, for instance, to alter the supplied permissions or insert default values into the given dict. :param perms: Shallow-copied value of the rules_permissions model Meta option :type perms: dict """ class RulesModel(RulesModelMixin, Model, metaclass=RulesModelBase): """ An abstract model with RulesModelMixin mixed in, using RulesModelBase as metaclass. Use this as base for your models directly if you don't need to customize the behavior of RulesModelMixin and thus don't want to create a custom base class. """ class Meta: abstract = True django-rules-3.5.0/rules/contrib/rest_framework.py000066400000000000000000000053701466536025000223230ustar00rootroot00000000000000from django.core.exceptions import ImproperlyConfigured, PermissionDenied class AutoPermissionViewSetMixin: """ Enforces object-level permissions in ``rest_framework.viewsets.ViewSet``, deriving the permission type from the particular action to be performed.. As with ``rules.contrib.views.AutoPermissionRequiredMixin``, this only works when model permissions are registered using ``rules.contrib.models.RulesModelMixin``. """ # Maps API actions to model permission types. None as value skips permission # checks for the particular action. # This map needs to be extended when custom actions are implemented # using the @action decorator. # Extend or replace it in subclasses like so: # permission_type_map = { # **AutoPermissionViewSetMixin.permission_type_map, # "close": "change", # "reopen": "change", # } permission_type_map = { "create": "add", "destroy": "delete", "list": None, "partial_update": "change", "retrieve": "view", "update": "change", } def initial(self, *args, **kwargs): """Ensures user has permission to perform the requested action.""" super().initial(*args, **kwargs) if not self.request.user: # No user, don't check permission return # Get the handler for the HTTP method in use try: if self.request.method.lower() not in self.http_method_names: raise AttributeError handler = getattr(self, self.request.method.lower()) except AttributeError: # method not supported, will be denied anyway return try: perm_type = self.permission_type_map[self.action] except KeyError: raise ImproperlyConfigured( "AutoPermissionViewSetMixin tried to authorize a request with the " "{!r} action, but permission_type_map only contains: {!r}".format( self.action, self.permission_type_map ) ) if perm_type is None: # Skip permission checking for this action return # Determine whether we've to check object permissions (for detail actions) obj = None extra_actions = self.get_extra_actions() # We have to access the unbound function via __func__ if handler.__func__ in extra_actions: if handler.detail: obj = self.get_object() elif self.action not in ("create", "list"): obj = self.get_object() # Finally, check permission perm = self.get_queryset().model.get_perm(perm_type) if not self.request.user.has_perm(perm, obj): raise PermissionDenied django-rules-3.5.0/rules/contrib/views.py000066400000000000000000000240721466536025000204260ustar00rootroot00000000000000from functools import wraps from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME, mixins from django.contrib.auth.views import redirect_to_login from django.core.exceptions import FieldError, ImproperlyConfigured, PermissionDenied from django.shortcuts import get_object_or_404 from django.utils.encoding import force_str from django.views.generic import CreateView, DeleteView, DetailView, UpdateView # 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. from django.views.generic.edit import BaseCreateView 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. """ if not isinstance(self, BaseCreateView): # We do NOT want to call get_object in a BaseCreateView, see issue #85 if hasattr(self, "get_object") and callable(self.get_object): # Requires SingleObjectMixin or equivalent ``get_object`` method return self.get_object() return None def has_permission(self): obj = self.get_permission_object() perms = self.get_permission_required() return self.request.user.has_perms(perms, obj) class AutoPermissionRequiredMixin(PermissionRequiredMixin): """ An extended variant of PermissionRequiredMixin which automatically determines the permission to check based on the type of view it's used with. It works by checking the current view for being an instance of a pre-defined list of view types. On a match, the corresponding permission type (such as "add" or "change") is converted into the full model-specific permission name and checked. See the permission_type_map attribute for the default view type -> permission type mappings. When a view using this mixin has an attribute ``permission_type``, that type is used directly and overwrites the permission_type_map for the particular view. A permission type of ``None`` (either as ``permission_type`` or in ``permission_type_map``) causes permission checking to be skipped. If the type of permission to check for should depend on dynamic factors other than the view type, you may overwrite the ``permission_type`` attribute with a ``@property``. The ``permission_required`` attribute behaves like it does in ``PermissionRequiredMixin`` and can be used to specify concrete permission name(s) to be checked in addition to the automatically derived one. NOTE: The model-based permission registration from ``rules.contrib.models`` must be used with the models for which you create views using this mixin, because the permission names are derived via ``RulesModelMixin.get_perm()`` internally. The second requirement is the presence of either an attribute ``model`` holding the ``Model`` the view acts on, or the ``get_queryset()`` method as provided by Django's ``SingleObjectMixin``. Hence with the normal model views, you don't need to care about anything. """ # These reflect Django's default model permissions. If needed, this list can be # extended or replaced entirely when subclassing, like so: # permission_type_map = [ # (SomeCustomViewType, "add"), # (SomeOtherCustomViewType, "some_fancy_action"), # *AutoPermissionRequiredMixin.permission_type_map, # ] # Note that ordering matters, which is why this is a list and not a dict. The # first entry for which isinstance(self, view_type) returns True will be used. permission_type_map = [ (CreateView, "add"), (UpdateView, "change"), (DeleteView, "delete"), (DetailView, "view"), ] def get_permission_required(self): """Adds the correct permission to check according to view type.""" try: perm_type = self.permission_type except AttributeError: # Perform auto-detection by view type for view_type, _perm_type in self.permission_type_map: if isinstance(self, view_type): perm_type = _perm_type break else: raise ImproperlyConfigured( "AutoPermissionRequiredMixin was used, but permission_type was " "neither set nor could be determined automatically for {0}. " "Consider setting permission_type on the view manually or " "adding {0} to the permission_type_map.".format( self.__class__.__name__ ) ) perms = [] if perm_type is not None: model = getattr(self, "model", None) if model is None: model = self.get_queryset().model perms.append(model.get_perm(perm_type)) # If additional permissions have been defined, consider them as well if self.permission_required is not None: perms.extend(super().get_permission_required()) return perms 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) def _wrapped_view(request, *args, **kwargs): # Normalize to a list of permissions if isinstance(perm, str): perms = (perm,) else: perms = perm # Get the object to check permissions against if callable(fn): obj = fn(request, *args, **kwargs) else: # pragma: no cover 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_str(redirect_url) return redirect_to_login(request.get_full_path(), redirect_url, redirect_field_name) django-rules-3.5.0/rules/permissions.py000066400000000000000000000013051466536025000201760ustar00rootroot00000000000000from .rulesets import RuleSet permissions = RuleSet() def add_perm(name, pred): permissions.add_rule(name, pred) def set_perm(name, pred): permissions.set_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, *args, **kwargs): 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-3.5.0/rules/predicates.py000066400000000000000000000241221466536025000177500ustar00rootroot00000000000000import logging import operator import threading from functools import partial, update_wrapper from inspect import getfullargspec, isfunction, ismethod from typing import Any, Callable, List, Optional, Tuple, Union logger = logging.getLogger("rules") def assert_has_kwonlydefaults(fn: Callable[..., Any], msg: str) -> None: argspec = getfullargspec(fn) if hasattr(argspec, "kwonlyargs"): if not argspec.kwonlyargs: return if not argspec.kwonlydefaults or len(argspec.kwonlyargs) > len( argspec.kwonlydefaults.keys() ): raise TypeError(msg) class Context(dict): def __init__(self, args: Tuple[Any, ...]) -> None: super(Context, self).__init__() self.args = args class localcontext(threading.local): def __init__(self) -> None: self.stack: List[Context] = [] _context = localcontext() class NoValueSentinel(object): def __bool__(self) -> bool: return False __nonzero__ = __bool__ # python 2 NO_VALUE = NoValueSentinel() del NoValueSentinel class Predicate(object): fn: Callable[..., Any] num_args: int var_args: bool name: str def __init__( self, fn: Union["Predicate", Callable[..., Any]], name: Optional[str] = None, bind: bool = False, ) -> None: # 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." innerfn = fn if isinstance(fn, Predicate): innerfn, num_args, var_args, name = ( fn.fn, fn.num_args, fn.var_args, name or fn.name, ) fn = innerfn elif isinstance(fn, partial): innerfn = fn.func argspec = getfullargspec(innerfn) var_args = argspec.varargs is not None num_args = len(argspec.args) - len(fn.args) if ismethod(innerfn): num_args -= 1 # skip `self` name = fn.func.__name__ elif ismethod(fn): argspec = getfullargspec(fn) var_args = argspec.varargs is not None num_args = len(argspec.args) - 1 # skip `self` elif isfunction(fn): argspec = getfullargspec(fn) var_args = argspec.varargs is not None num_args = len(argspec.args) elif isinstance(fn, object): innerfn = getattr(fn, "__call__") # noqa argspec = getfullargspec(innerfn) 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_has_kwonlydefaults( innerfn, "The given predicate is missing defaults for keyword-only arguments", ) 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) -> str: return "<%s:%s object at %s>" % (type(self).__name__, str(self), hex(id(self))) def __str__(self) -> str: return self.name def __call__(self, *args, **kwargs) -> Any: # 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) -> Optional[Context]: """ 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 test(self, obj: Any = NO_VALUE, target: Any = NO_VALUE) -> bool: """ 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) -> "Predicate": def AND(*args): return self._combine(other, operator.and_, args) return type(self)(AND, "(%s & %s)" % (self.name, other.name)) def __or__(self, other) -> "Predicate": def OR(*args): return self._combine(other, operator.or_, args) return type(self)(OR, "(%s | %s)" % (self.name, other.name)) def __xor__(self, other) -> "Predicate": def XOR(*args): return self._combine(other, operator.xor, args) return type(self)(XOR, "(%s ^ %s)" % (self.name, other.name)) def __invert__(self) -> "Predicate": 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) -> Optional[bool]: # 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 result = self.fn(*callargs) result = None if result is None else bool(result) 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) -> bool: return hasattr(obj, "__bool__") or hasattr(obj, "__nonzero__") @predicate def is_authenticated(user) -> bool: 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) -> bool: 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) -> bool: 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) -> bool: 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) -> Callable[..., Any]: 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) -> bool: 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-3.5.0/rules/py.typed000066400000000000000000000000001466536025000167370ustar00rootroot00000000000000django-rules-3.5.0/rules/rulesets.py000066400000000000000000000020221466536025000174660ustar00rootroot00000000000000from .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 set_rule(self, name, pred): 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 set_rule(name, pred): default_rules.set_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-3.5.0/rules/templatetags/000077500000000000000000000000001466536025000177445ustar00rootroot00000000000000django-rules-3.5.0/rules/templatetags/__init__.py000066400000000000000000000000001466536025000220430ustar00rootroot00000000000000django-rules-3.5.0/rules/templatetags/rules.py000066400000000000000000000007151466536025000214530ustar00rootroot00000000000000from django import template from ..rulesets import default_rules register = template.Library() @register.simple_tag def test_rule(name, obj=None, target=None): return default_rules.test_rule(name, obj, target) @register.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-3.5.0/runtests.sh000077500000000000000000000002401466536025000163420ustar00rootroot00000000000000#!/bin/sh # NOTE: Make sure you `pip install -e .` first coverage run tests/manage.py test --failfast -v2 testsuite "$@" \ && echo \ && coverage report -m django-rules-3.5.0/setup.cfg000066400000000000000000000003351466536025000157420ustar00rootroot00000000000000[bdist_wheel] universal = 1 [flake8] max-line-length=88 select = C,E,F,W,B,B950,I ignore = E203,E501,W503 [coverage:run] source = rules [coverage:report] exclude_lines = pragma: no cover omit = */rules/apps.py django-rules-3.5.0/setup.py000066400000000000000000000035531466536025000156400ustar00rootroot00000000000000#!/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", ], include_package_data=True, 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 :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", ], ) django-rules-3.5.0/tests/000077500000000000000000000000001466536025000152625ustar00rootroot00000000000000django-rules-3.5.0/tests/manage.py000077500000000000000000000003721466536025000170710ustar00rootroot00000000000000#!/usr/bin/env python import os import sys if __name__ == "__main__": 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-3.5.0/tests/testapp/000077500000000000000000000000001466536025000167425ustar00rootroot00000000000000django-rules-3.5.0/tests/testapp/__init__.py000066400000000000000000000000001466536025000210410ustar00rootroot00000000000000django-rules-3.5.0/tests/testapp/admin.py000066400000000000000000000004001466536025000203760ustar00rootroot00000000000000from __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-3.5.0/tests/testapp/migrations/000077500000000000000000000000001466536025000211165ustar00rootroot00000000000000django-rules-3.5.0/tests/testapp/migrations/0001_initial.py000066400000000000000000000034311466536025000235620ustar00rootroot00000000000000# Generated by Django 2.2.2 on 2019-08-05 08:04 import sys 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, ), ), ], ), ] # TestModel doesn't work under Python 2 if sys.version_info.major >= 3: import rules.contrib.models operations += [ migrations.CreateModel( name="TestModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], bases=(rules.contrib.models.RulesModelMixin, models.Model), ), ] django-rules-3.5.0/tests/testapp/migrations/__init__.py000066400000000000000000000000001466536025000232150ustar00rootroot00000000000000django-rules-3.5.0/tests/testapp/models.py000066400000000000000000000012271466536025000206010ustar00rootroot00000000000000from __future__ import absolute_import from django.conf import settings from django.db import models import rules from rules.contrib.models import RulesModel 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 class TestModel(RulesModel): class Meta: rules_permissions = {"add": rules.always_true, "view": rules.always_true} @classmethod def preprocess_rules_permissions(cls, perms): perms["custom"] = rules.always_true django-rules-3.5.0/tests/testapp/rules.py000066400000000000000000000011161466536025000204450ustar00rootroot00000000000000from __future__ import absolute_import import rules # Predicates @rules.predicate def is_book_author(user, book): if not book: return False return book.author == user @rules.predicate def is_boss(user): return user.is_superuser 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) rules.add_rule("create_book", is_boss) # Permissions rules.add_perm("testapp.change_book", is_book_author | is_editor) rules.add_perm("testapp.delete_book", is_book_author) django-rules-3.5.0/tests/testapp/settings.py000066400000000000000000000026011466536025000211530ustar00rootroot00000000000000from os.path import abspath, dirname BASE_DIR = dirname(dirname(abspath(__file__))) DEBUG = True 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", ] 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": { "debug": DEBUG, "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-3.5.0/tests/testapp/templates/000077500000000000000000000000001466536025000207405ustar00rootroot00000000000000django-rules-3.5.0/tests/testapp/templates/empty.html000066400000000000000000000000031466536025000227550ustar00rootroot00000000000000OK django-rules-3.5.0/tests/testapp/urls.py000066400000000000000000000032351466536025000203040ustar00rootroot00000000000000from django.contrib import admin from django.urls import re_path from .views import ( BookCreateView, BookDeleteView, BookUpdateErrorView, BookUpdateView, ViewThatRaises, ViewWithPermissionList, change_book, delete_book, view_that_raises, view_with_object, view_with_permission_list, ) admin.autodiscover() urlpatterns = [ re_path(r"^admin/", admin.site.urls), # Function-based views re_path(r"^(?P\d+)/change/$", change_book, name="change_book"), re_path(r"^(?P\d+)/delete/$", delete_book, name="delete_book"), re_path(r"^(?P\d+)/raise/$", view_that_raises, name="view_that_raises"), re_path(r"^(?P\d+)/object/$", view_with_object, name="view_with_object"), re_path( r"^(?P\d+)/list/$", view_with_permission_list, name="view_with_permission_list", ), # Class-based views re_path(r"^cbv/create/$", BookCreateView.as_view(), name="cbv.create_book"), re_path( r"^cbv/(?P\d+)/change/$", BookUpdateView.as_view(), name="cbv.change_book", ), re_path( r"^cbv/(?P\d+)/delete/$", BookDeleteView.as_view(), name="cbv.delete_book", ), re_path( r"^cbv/(?P\d+)/raise/$", ViewThatRaises.as_view(), name="cbv.view_that_raises", ), re_path( r"^cbv/(?P\d+)/list/$", ViewWithPermissionList.as_view(), name="cbv.view_with_permission_list", ), re_path( r"^cbv/(?P\d+)/change-error/$", BookUpdateErrorView.as_view(), name="cbv.change_book_error", ), ] django-rules-3.5.0/tests/testapp/views.py000066400000000000000000000047671466536025000204670ustar00rootroot00000000000000from __future__ import absolute_import from django.http import HttpResponse from django.views.generic.edit import CreateView, DeleteView, UpdateView from rules.contrib.views import ( LoginRequiredMixin, PermissionRequiredMixin, objectgetter, permission_required, ) from .models import Book class BookMixin(object): def get_object(self): return Book.objects.get(pk=self.kwargs["book_id"]) class BookMixinWithError(object): def get_object(self): raise AttributeError("get_object") @permission_required("testapp.change_book", fn=objectgetter(Book, "book_id")) def change_book(request, book_id): return HttpResponse("OK") class BookCreateView( LoginRequiredMixin, PermissionRequiredMixin, BookMixin, CreateView ): fields = ["title"] template_name = "empty.html" permission_required = "testapp.create_book" class BookUpdateView( LoginRequiredMixin, PermissionRequiredMixin, BookMixin, UpdateView ): fields = ["title"] template_name = "empty.html" permission_required = "testapp.change_book" class BookUpdateErrorView( LoginRequiredMixin, PermissionRequiredMixin, BookMixinWithError, 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=objectgetter(Book, "book_id")) def view_with_object(request, book_id): return HttpResponse("OK") django-rules-3.5.0/tests/testsuite/000077500000000000000000000000001466536025000173135ustar00rootroot00000000000000django-rules-3.5.0/tests/testsuite/__init__.py000066400000000000000000000000001466536025000214120ustar00rootroot00000000000000django-rules-3.5.0/tests/testsuite/contrib/000077500000000000000000000000001466536025000207535ustar00rootroot00000000000000django-rules-3.5.0/tests/testsuite/contrib/__init__.py000066400000000000000000000012161466536025000230640ustar00rootroot00000000000000from django.contrib.auth.models import Group, User import testapp.rules # noqa .imported to register rules from testapp.models import Book ISBN = "978-1-4302-1936-1" class TestData: @classmethod def setUpTestData(cls): adrian = User.objects.create_user( "adrian", password="secr3t", is_superuser=True, is_staff=True ) martin = User.objects.create_user("martin", password="secr3t", is_staff=True) editors = Group.objects.create(name="editors") martin.groups.add(editors) Book.objects.create( isbn=ISBN, title="The Definitive Guide to Django", author=adrian ) django-rules-3.5.0/tests/testsuite/contrib/test_admin.py000066400000000000000000000023721466536025000234600ustar00rootroot00000000000000from django.test import TestCase from django.urls import reverse from . import TestData class ModelAdminTests(TestData, 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-3.5.0/tests/testsuite/contrib/test_models.py000066400000000000000000000012241466536025000236460ustar00rootroot00000000000000from __future__ import absolute_import from django.core.exceptions import ImproperlyConfigured from django.test import TestCase import rules class RulesModelTests(TestCase): def test_preprocess(self): self.assertTrue(rules.perm_exists("testapp.add_testmodel")) self.assertTrue(rules.perm_exists("testapp.custom_testmodel")) def test_invalid_config(self): from rules.contrib.models import RulesModel with self.assertRaises(ImproperlyConfigured): class InvalidTestModel(RulesModel): class Meta: app_label = "testapp" rules_permissions = "invalid" django-rules-3.5.0/tests/testsuite/contrib/test_predicates.py000066400000000000000000000026261466536025000245150ustar00rootroot00000000000000from django.contrib.auth.models import User from django.test import TestCase from rules.predicates import ( is_active, is_authenticated, is_group_member, is_staff, is_superuser, ) from . import TestData class SwappedUser(object): pass class PredicateTests(TestData, TestCase): def test_is_authenticated(self): assert is_authenticated(User.objects.get(username="adrian")) assert not is_authenticated(SwappedUser()) def test_is_superuser(self): assert is_superuser(User.objects.get(username="adrian")) assert not is_superuser(SwappedUser()) def test_is_staff(self): assert is_staff(User.objects.get(username="adrian")) assert not is_staff(SwappedUser()) def test_is_active(self): assert is_active(User.objects.get(username="adrian")) assert not is_active(SwappedUser()) def test_is_group_member(self): 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-3.5.0/tests/testsuite/contrib/test_rest_framework.py000066400000000000000000000055531466536025000254260ustar00rootroot00000000000000from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.serializers import ModelSerializer from rest_framework.test import APIRequestFactory from rest_framework.viewsets import ModelViewSet import rules # noqa from rules.contrib.rest_framework import AutoPermissionViewSetMixin class AutoPermissionRequiredMixinTests(TestCase): def setUp(self): from testapp.models import TestModel class TestModelSerializer(ModelSerializer): class Meta: model = TestModel fields = "__all__" class TestViewSet(AutoPermissionViewSetMixin, ModelViewSet): queryset = TestModel.objects.all() serializer_class = TestModelSerializer permission_type_map = AutoPermissionViewSetMixin.permission_type_map.copy() permission_type_map["custom_detail"] = "add" permission_type_map["custom_nodetail"] = "add" @action(detail=True) def custom_detail(self, request): return Response() @action(detail=False) def custom_nodetail(self, request): return Response() @action(detail=False) def unknown(self, request): return Response() self.model = TestModel self.vs = TestViewSet self.req = APIRequestFactory().get("/") self.req.user = AnonymousUser() def test_predefined_action(self): # Create should be allowed due to the add permission set on TestModel self.assertEqual(self.vs.as_view({"get": "create"})(self.req).status_code, 201) # List should be allowed due to None in permission_type_map self.assertEqual( self.vs.as_view({"get": "list"})(self.req, pk=1).status_code, 200 ) # Retrieve should be allowed due to the view permission set on TestModel self.assertEqual( self.vs.as_view({"get": "retrieve"})(self.req, pk=1).status_code, 200 ) # Destroy should be forbidden due to missing delete permission self.assertEqual( self.vs.as_view({"get": "destroy"})(self.req, pk=1).status_code, 403 ) def test_custom_actions(self): # Both should not produce 403 due to being mapped to the add permission self.assertEqual( self.vs.as_view({"get": "custom_detail"})(self.req, pk=1).status_code, 404 ) self.assertEqual( self.vs.as_view({"get": "custom_nodetail"})(self.req).status_code, 200 ) def test_unknown_action(self): with self.assertRaises(ImproperlyConfigured): self.vs.as_view({"get": "unknown"})(self.req) django-rules-3.5.0/tests/testsuite/contrib/test_templatetags.py000066400000000000000000000070531466536025000250630ustar00rootroot00000000000000from django.contrib.auth.models import User from django.template import Context, Template from django.test import TestCase from testapp.models import Book from . import ISBN, TestData class TemplateTagTests(TestData, 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-3.5.0/tests/testsuite/contrib/test_views.py000066400000000000000000000221531466536025000235240ustar00rootroot00000000000000from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.http import Http404, HttpRequest from django.test import RequestFactory, TestCase from django.urls import reverse from django.utils.encoding import force_str from django.views.generic import CreateView, View from testapp.models import Book import rules # noqa from rules.contrib.views import AutoPermissionRequiredMixin, objectgetter from . import TestData class FBVDecoratorTests(TestData, 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).strip(), "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).strip(), "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).strip(), "OK") # Martin can *not* create a book # Up to Django v2.1, the response was a redirect to login self.assertTrue(self.client.login(username="martin", password="secr3t")) response = self.client.get(reverse("cbv.create_book")) self.assertIn(response.status_code, [302, 403]) # 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).strip(), "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).strip(), "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(TestData, TestCase): def test_get_object_error(self): self.assertTrue(self.client.login(username="adrian", password="secr3t")) with self.assertRaises(AttributeError): self.client.get(reverse("cbv.change_book_error", args=(1,))) 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).strip(), "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).strip(), "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).strip(), "OK") # Martin can *not* delete Adrian's book # Up to Django v2.1, the response was a redirect to login self.assertTrue(self.client.login(username="martin", password="secr3t")) response = self.client.get(reverse("cbv.delete_book", args=(1,))) self.assertIn(response.status_code, [302, 403]) # 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).strip(), "OK") # Martin does not have delete permission # Up to Django v2.1, the response was a redirect to login self.assertTrue(self.client.login(username="martin", password="secr3t")) response = self.client.get(reverse("cbv.view_with_permission_list", args=(1,))) self.assertIn(response.status_code, [302, 403]) class AutoPermissionRequiredMixinTests(TestCase): def setUp(self): from testapp.models import TestModel self.model = TestModel self.req = RequestFactory().get("/") self.req.user = AnonymousUser() def test_predefined_view_type(self): class TestView(AutoPermissionRequiredMixin, CreateView): model = self.model fields = () self.assertEqual(TestView.as_view()(self.req).status_code, 200) def test_custom_view_type(self): class CustomViewMixin: pass class TestView(AutoPermissionRequiredMixin, CustomViewMixin, CreateView): model = self.model fields = () permission_type_map = [ (CustomViewMixin, "unknown_perm") ] + AutoPermissionRequiredMixin.permission_type_map raise_exception = True with self.assertRaises(PermissionDenied): TestView.as_view()(self.req) def test_unknown_view_type(self): class TestView(AutoPermissionRequiredMixin, View): pass with self.assertRaises(ImproperlyConfigured): TestView.as_view()(self.req) def test_overwrite_perm_type(self): class TestView(AutoPermissionRequiredMixin, CreateView): model = self.model fields = () permission_type = "unknown" raise_exception = True with self.assertRaises(PermissionDenied): TestView.as_view()(self.req) def test_disable_perm_checking(self): class TestView(AutoPermissionRequiredMixin, CreateView): model = self.model fields = () permission_type = None self.assertEqual(TestView.as_view()(self.req).status_code, 200) def test_permission_required_passthrough(self): class TestView(AutoPermissionRequiredMixin, CreateView): model = self.model fields = () permission_required = "testapp.unknown_perm" raise_exception = True with self.assertRaises(PermissionDenied): TestView.as_view()(self.req) django-rules-3.5.0/tests/testsuite/test_permissions.py000066400000000000000000000031621466536025000233010ustar00rootroot00000000000000from unittest import TestCase from rules.permissions import ( ObjectPermissionBackend, add_perm, has_perm, perm_exists, permissions, remove_perm, set_perm, ) from rules.predicates import always_false, always_true class PermissionsTests(TestCase): @staticmethod def reset_ruleset(ruleset): for k in list(ruleset.keys()): ruleset.pop(k) def setUp(self): self.reset_ruleset(permissions) def tearDown(self): self.reset_ruleset(permissions) def test_permissions_ruleset(self): 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") with self.assertRaises(KeyError): add_perm("can_edit_book", always_false) set_perm("can_edit_book", always_false) assert not has_perm("can_edit_book") remove_perm("can_edit_book") assert not perm_exists("can_edit_book") def test_backend(self): 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") with self.assertRaises(KeyError): add_perm("can_edit_book", always_true) set_perm("can_edit_book", always_false) assert not backend.has_perm(None, "can_edit_book") remove_perm("can_edit_book") assert not perm_exists("can_edit_book") django-rules-3.5.0/tests/testsuite/test_predicates.py000066400000000000000000000311061466536025000230500ustar00rootroot00000000000000import functools from unittest import TestCase from rules.predicates import ( NO_VALUE, Predicate, always_allow, always_deny, always_false, always_true, predicate, ) class PredicateKwonlyTests(TestCase): def test_predicate_kwargonly(self): def p(foo, *, bar): return True with self.assertRaises(TypeError): predicate(p) def p2(foo, *a, bar): return True with self.assertRaises(TypeError): predicate(p2) def p3(foo, *, bar="bar"): return True # Should not fail predicate(p3) class PredicateTests(TestCase): def test_always_true(self): assert always_true() def test_always_false(self): assert not always_false() def test_always_allow(self): assert always_allow() def test_always_deny(self): assert not always_deny() def test_lambda_predicate(self): p = Predicate(lambda x: x == "a") assert p.name == "" assert p.num_args == 1 assert p("a") def test_lambda_predicate_custom_name(self): p = Predicate(lambda x: x == "a", name="mypred") assert p.name == "mypred" assert p.num_args == 1 assert p("a") def test_function_predicate(self): 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(self): 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(self): 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(self): 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(self): 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(self): 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(self): 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(self): 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(self): 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(self): @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(self): @predicate def mypred(arg1, arg2): return True assert mypred.name == "mypred" assert mypred.num_args == 2 def test_decorator_noargs(self): @predicate() def mypred(arg1, arg2): return True assert mypred.name == "mypred" assert mypred.num_args == 2 def test_decorator_custom_name(self): @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(self): @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(self): @predicate def p(*args, **kwargs): assert len(args) == 0 assert len(kwargs) == 0 assert p.num_args == 0 p.test() def test_one_arg(self): @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(self): @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(self): @predicate def p(a=None, b=None, *args, **kwargs): assert len(args) == 0 assert len(kwargs) == 1 assert "c" in kwargs assert a == "a" assert b == "b" p("a", b="b", c="c") def test_no_value_marker(self): @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(self): @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(self): @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(self): @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(self): @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(self): @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-3.5.0/tests/testsuite/test_rulesets.py000066400000000000000000000027361466536025000226020ustar00rootroot00000000000000from unittest import TestCase from rules.predicates import always_false, always_true from rules.rulesets import ( RuleSet, add_rule, default_rules, remove_rule, rule_exists, set_rule, test_rule, ) class RulesetTests(TestCase): @staticmethod def reset_ruleset(ruleset): for k in list(ruleset.keys()): ruleset.pop(k) def setUp(self): self.reset_ruleset(default_rules) def tearDown(self): self.reset_ruleset(default_rules) def test_shared_ruleset(self): add_rule("somerule", always_true) assert "somerule" in default_rules assert rule_exists("somerule") assert test_rule("somerule") assert test_rule("somerule") with self.assertRaises(KeyError): add_rule("somerule", always_false) set_rule("somerule", always_false) assert not test_rule("somerule") remove_rule("somerule") assert not rule_exists("somerule") def test_ruleset(self): ruleset = RuleSet() ruleset.add_rule("somerule", always_true) assert "somerule" in ruleset assert ruleset.rule_exists("somerule") assert ruleset.test_rule("somerule") with self.assertRaises(KeyError): ruleset.add_rule("somerule", always_true) ruleset.set_rule("somerule", always_false) assert not test_rule("somerule") ruleset.remove_rule("somerule") assert not ruleset.rule_exists("somerule") django-rules-3.5.0/tox.ini000066400000000000000000000021551466536025000154360ustar00rootroot00000000000000[tox] envlist = py{38,39,310,311,312,py3}-dj{32,42} py{310,311,312,py3}-dj{50,51} py312-packaging [gh-actions] python = 3.8: py38 3.9: py39 3.10: py310 3.11: py311 3.12: py312 pypy-3.10: pypy3 [gh-actions:env] DJANGO = 3.2: dj32 4.2: dj42 5.0: dj50 5.1: dj51 main: djmain packaging: packaging [testenv] usedevelop = true deps = coverage djangorestframework dj32: Django~=3.2.0 dj42: Django~=4.2.0 dj50: Django~=5.0.0 dj51: Django~=5.1.0 commands = py{38,39,310,311,312}: coverage run tests/manage.py test testsuite {posargs: -v 2} py{38,39,310,311,312}: coverage report -m pypy3: {envpython} tests/manage.py test testsuite {posargs: -v 2} [testenv:py312-packaging] usedevelop = false deps = django djangorestframework commands = {envpython} tests/manage.py test testsuite {posargs: -v 2} [testenv:py312-djmain] deps = https://github.com/django/django/archive/main.tar.gz#egg=django djangorestframework commands = {envpython} tests/manage.py test testsuite {posargs: -v 2}