├── restfw_composed_permissions ├── generic │ ├── __init__.py │ ├── permissions.py │ └── components.py ├── tests │ ├── __init__.py │ ├── settings_sqlite.py │ └── tests.py ├── __init__.py ├── models.py └── base.py ├── MANIFEST.in ├── .gitignore ├── CHANGES.rst ├── README.rst ├── setup.py ├── LICENSE └── docs ├── Makefile ├── conf.py └── index.rst /restfw_composed_permissions/generic/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /restfw_composed_permissions/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /restfw_composed_permissions/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include CHANGES.rst 3 | include README.rst 4 | -------------------------------------------------------------------------------- /restfw_composed_permissions/models.py: -------------------------------------------------------------------------------- 1 | # This app has no models. File needed for Django < 1.7 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .*swp 3 | doc/build 4 | dist 5 | versiontools* 6 | build* 7 | *.egg* 8 | docs/_build 9 | .venv 10 | -------------------------------------------------------------------------------- /restfw_composed_permissions/generic/permissions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .generics import * 4 | 5 | 6 | class AllowAnyPermission(BaseComposedPermision): 7 | global_permission_set = (lambda self: AllowAll) 8 | object_permission_set = (lambda self: AllowAll) 9 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | Version 0.1 5 | ----------- 6 | 7 | - Initial version. 8 | 9 | Version 0.2 10 | ----------- 11 | 12 | - Spelling Fixes 13 | - Added RestComponentPermission with same arguments as the rest framework permissions 14 | - Updated Documentation 15 | 16 | Version 0.2.1 17 | ------------- 18 | 19 | - Django 2 compatibility 20 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Composed permissions for django-rest-framework 2 | ---------------------------------------------- 3 | 4 | A simple way to define complex permissions for django-rest-framework. 5 | 6 | - **Documentation:** https://djangorestframework-composed-permissions.readthedocs.org/en/latest/ 7 | 8 | Development 9 | ----------- 10 | 11 | Run tests with our settings using the following command: 12 | 13 | ``django-admin test restfw_composed_permissions --settings=restfw_composed_permissions.tests.settings_sqlite`` 14 | 15 | License 16 | ------- 17 | 18 | New BSD License 19 | -------------------------------------------------------------------------------- /restfw_composed_permissions/tests/settings_sqlite.py: -------------------------------------------------------------------------------- 1 | # This is an example test settings file for use with the Django test suite. 2 | # 3 | # The 'sqlite3' backend requires only the ENGINE setting (an in- 4 | # memory database will be used). All other backends will require a 5 | # NAME and potentially authentication information. See the 6 | # following section in the docs for more information: 7 | # 8 | # https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/ 9 | # 10 | # The different databases that Django supports behave differently in certain 11 | # situations, so it is recommended to run the test suite against as many 12 | # database backends as possible. You may want to create a separate settings 13 | # file for each of the backends you test against. 14 | 15 | DATABASES = { 16 | 'default': { 17 | 'ENGINE': 'django.db.backends.sqlite3' 18 | }, 19 | } 20 | 21 | SECRET_KEY = "django_tests_secret_key" 22 | TIME_ZONE = 'UTC' 23 | LANGUAGE_CODE = 'en' 24 | ADMIN_MEDIA_PREFIX = '/static/admin/' 25 | STATICFILES_DIRS = () 26 | 27 | 28 | INSTALLED_APPS = ( 29 | 'restfw_composed_permissions', 30 | ) 31 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import setup, find_packages 5 | 6 | with open('README.rst') as file: 7 | long_description = file.read() 8 | 9 | INSTALL_REQUIRES = [ 10 | "django >= 1.11", 11 | "djangorestframework", 12 | ] 13 | 14 | setup( 15 | name="djangorestframework-composed-permissions", 16 | version="0.2.1", 17 | description="Composed permissions for django-rest-framework", 18 | long_description=long_description, 19 | keywords="django, rest, restframework, permissions", 20 | author="Andrey Antukh", 21 | author_email="niwi@niwi.be", 22 | url="https://github.com/niwibe/djangorestframework-composed-permissions", 23 | license="BSD", 24 | packages=find_packages(), 25 | install_requires=INSTALL_REQUIRES, 26 | classifiers=[ 27 | "Development Status :: 4 - Beta", 28 | "Framework :: Django", 29 | "Intended Audience :: Developers", 30 | "License :: OSI Approved :: BSD License", 31 | "Operating System :: OS Independent", 32 | "Programming Language :: Python", 33 | "Programming Language :: Python :: 2", 34 | "Programming Language :: Python :: 3", 35 | "Topic :: Internet :: WWW/HTTP", 36 | ] 37 | ) 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Andrey Antukh 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions 5 | are met: 6 | 1. Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | 2. Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | 3. Neither the name of copyright holders nor the names of its 12 | contributors may be used to endorse or promote products derived 13 | from this software without specific prior written permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16 | ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 17 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS 19 | BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 20 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 21 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 22 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 23 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 24 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 25 | POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /restfw_composed_permissions/generic/components.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from rest_framework import permissions 4 | from ..base import (BasePermissionComponent, 5 | BaseComposedPermision, 6 | And, Or) 7 | 8 | 9 | class AllowAll(BasePermissionComponent): 10 | """ 11 | Always allow all requests without 12 | any constraints. 13 | """ 14 | 15 | def has_permission(self, permission, request, view): 16 | return True 17 | 18 | 19 | class AllowOnlyAnonymous(BasePermissionComponent): 20 | """ 21 | Allow only anonymous requests. 22 | """ 23 | 24 | def has_permission(self, permission, request, view): 25 | return request.user.is_anonymous 26 | 27 | 28 | class AllowOnlyAuthenticated(BasePermissionComponent): 29 | def has_permission(self, permission, request, view): 30 | if request.user.is_anonymous: 31 | return False 32 | return True 33 | 34 | 35 | class AllowOnlySafeHttpMethod(BasePermissionComponent): 36 | def has_permission(self, permission, request, view): 37 | if request.method in permissions.SAFE_METHODS: 38 | return True 39 | return False 40 | 41 | 42 | class ObjectAttrEqualToObjectAttr(BasePermissionComponent): 43 | """ 44 | This is a object level permision component and if is used on 45 | global permission context it always returns True. 46 | 47 | This component checks the equality of two expressions that are 48 | evaluted in "safe" way. On the context of eval are exposed "obj" 49 | as current object and "request" as the current request. 50 | 51 | This component works well for check a object owner os similary. 52 | 53 | Example: 54 | 55 | .. code-block:: python 56 | 57 | class SomePermission(BaseComposedPermision): 58 | global_permission_set = (lambda self: AllowAll) 59 | object_permission_set = (lambda self: 60 | ObjectAttrEqualToObjectAttr("request.user", "obj.owner")) 61 | """ 62 | 63 | def __init__(self, obj_attr1, obj_attr2): 64 | self.obj_attr1 = obj_attr1 65 | self.obj_attr2 = obj_attr2 66 | 67 | def has_object_permission(self, permission, request, view, obj): 68 | safe_locals = {"obj": obj, "request": request} 69 | 70 | try: 71 | attr1_value = eval(self.obj_attr1, {}, safe_locals) 72 | attr2_value = eval(self.obj_attr2, {}, safe_locals) 73 | except AttributeError: 74 | return False 75 | else: 76 | return attr1_value == attr2_value 77 | -------------------------------------------------------------------------------- /restfw_composed_permissions/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import copy 4 | import inspect 5 | 6 | 7 | from rest_framework import permissions 8 | 9 | 10 | class BaseComposedPermission(permissions.BasePermission): 11 | """ 12 | Base class for compose permission with permission 13 | components and logical operators. 14 | 15 | This class should have permission_set defined as 16 | a instance function or lambda. 17 | 18 | Examles: 19 | 20 | .. code-block:: python 21 | 22 | class SomePermission(BaseComposedPermision): 23 | global_permission_set = (lambda self: Component1() | Component2()) 24 | object_permission_set = (lambda self: Component1() | Component2()) 25 | 26 | .. code-block:: python 27 | 28 | class SomePermission(BaseComposedPermision): 29 | def global_permission_set(self): 30 | return (Component1() | Component2()) 31 | 32 | def object_permission_set(self): 33 | return (Component1() | Component2()) 34 | 35 | Defining a permission set as function instead of 36 | a class attribute directly prevent storing state 37 | on the component instances. 38 | 39 | `permission_set` method or lambda function should 40 | return a iterable, `BasePermissionComponent` or 41 | `BasePermissionSet` subclass instance. 42 | 43 | Example: 44 | 45 | .. code-block: python 46 | 47 | class SomePermission(BaseComposedPermision): 48 | global_permission_set = (lambda self: [Component1, Component2]) 49 | # Is same as: 50 | # global_permission_set = (lambda self: Component1() | Component2()) 51 | """ 52 | 53 | def global_permission_set(self): 54 | raise NotImplementedError() 55 | 56 | def object_permission_set(self): 57 | raise NotImplementedError() 58 | 59 | def _evaluate_permission_set(self, permission_set): 60 | # Evaluate components 61 | permission_set = permission_set() 62 | 63 | if isinstance(permission_set, (list, tuple, set)): 64 | _permission_set = Or(*permission_set) 65 | elif inspect.isclass(permission_set): 66 | _permission_set = Or(permission_set()) 67 | else: 68 | _permission_set = Or(permission_set) 69 | 70 | return _permission_set 71 | 72 | def has_permission(self, request, view): 73 | permission_set = self._evaluate_permission_set(self.global_permission_set) 74 | return permission_set.has_permission(self, request, view) 75 | 76 | def has_object_permission(self, request, view, obj): 77 | permission_set = self._evaluate_permission_set(self.object_permission_set) 78 | return permission_set.has_object_permission(self, request, view, obj) 79 | 80 | 81 | class BasePermissionComponent(object): 82 | """ 83 | Base class for permission component. 84 | Is a unit permission class. 85 | """ 86 | 87 | def has_permission(self, permission, request, view): 88 | raise NotImplementedError() 89 | 90 | def has_object_permission(self, permission, request, view, obj): 91 | # By default return same as that "has_permission" method 92 | return self.has_permission(permission, request, view) 93 | 94 | def __and__(self, component): 95 | return And(self, component) 96 | 97 | def __or__(self, component): 98 | return Or(self, component) 99 | 100 | def __invert__(self): 101 | return Not(self) 102 | 103 | 104 | class RestPermissionComponent(BasePermissionComponent): 105 | 106 | def _has_permission(self, permission, request, view): 107 | return self.has_permission(request, view) 108 | 109 | def _has_object_permission(self, permission, request, view, obj): 110 | return self.has_object_permission(request, view, obj) 111 | 112 | def has_permission(self, request, view): 113 | raise NotImplementedError() 114 | 115 | def has_object_permission(self, request, view, obj): 116 | # By default return same as that "has_permission" method 117 | return self.has_permission(request, view) 118 | 119 | 120 | class BasePermissionSet(object): 121 | """ 122 | Base class for permission set. 123 | Permission Set is composed of Permission Components 124 | """ 125 | 126 | def __init__(self, *args): 127 | self.components = [c() if inspect.isclass(c) else c for c in args] 128 | 129 | def update_method_name(self, name, component): 130 | if isinstance(component, RestPermissionComponent): 131 | name = '_' + name 132 | 133 | return name 134 | 135 | def get_component_result(self, component, method_name, *args, **kwargs): 136 | final_method_name = self.update_method_name(method_name, component) 137 | method = getattr(component, final_method_name) 138 | return method(*args, **kwargs) 139 | 140 | def _check_permission(self, method_name, *args, **kwargs): 141 | raise NotImplementedError() 142 | 143 | def has_permission(self, permission, request, view): 144 | return self._check_permission("has_permission", permission, 145 | request, view) 146 | 147 | def has_object_permission(self, permission, request, view, obj): 148 | return self._check_permission("has_object_permission", permission, 149 | request, view, obj) 150 | def __invert__(self): 151 | return Not(self) 152 | 153 | 154 | class Not(BasePermissionSet): 155 | def has_permission(self, *args, **kwargs): 156 | result = self.get_component_result(self.components[0], 'has_permission', *args, **kwargs) 157 | return not result 158 | 159 | def has_object_permission(self, *args, **kwargs): 160 | result = self.get_component_result(self.components[0], 'has_object_permission', *args, **kwargs) 161 | return not result 162 | 163 | 164 | class Or(BasePermissionSet): 165 | def _check_permission(self, method_name, *args, **kwargs): 166 | valid = False 167 | 168 | for component in self.components: 169 | result = self.get_component_result(component, method_name, *args, **kwargs) 170 | if result: 171 | valid = True 172 | break 173 | 174 | return valid 175 | 176 | def __and__(self, component): 177 | return And(self, component) 178 | 179 | def __or__(self, component): 180 | components = copy.copy(self.components) 181 | components.append(component) 182 | return Or(*components) 183 | 184 | 185 | class And(BasePermissionSet): 186 | def _check_permission(self, method_name, *args, **kwargs): 187 | valid = True 188 | 189 | for component in self.components: 190 | result = self.get_component_result(component, method_name, *args, **kwargs) 191 | if not result: 192 | valid = False 193 | break 194 | 195 | return valid 196 | 197 | def __and__(self, component): 198 | components = copy.copy(self.components) 199 | components.append(component) 200 | return And(*components) 201 | 202 | def __or__(self, component): 203 | return Or(self, component) 204 | 205 | #Alias to old typo for backwards compatability 206 | BaseComposedPermision = BaseComposedPermission 207 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/djangorestframework-composed-permissions.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/djangorestframework-composed-permissions.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/djangorestframework-composed-permissions" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/djangorestframework-composed-permissions" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # djangorestframework-composed-permissions documentation build configuration file, created by 5 | # sphinx-quickstart on Wed Aug 28 15:28:50 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys, os 16 | 17 | # If extensions (or modules to document with autodoc) are in another directory, 18 | # add these directories to sys.path here. If the directory is relative to the 19 | # documentation root, use os.path.abspath to make it absolute, like shown here. 20 | #sys.path.insert(0, os.path.abspath('.')) 21 | 22 | # -- General configuration ----------------------------------------------------- 23 | 24 | # If your documentation needs a minimal Sphinx version, state it here. 25 | #needs_sphinx = '1.0' 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be extensions 28 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 29 | extensions = [] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The suffix of source filenames. 35 | source_suffix = '.rst' 36 | 37 | # The encoding of source files. 38 | #source_encoding = 'utf-8-sig' 39 | 40 | # The master toctree document. 41 | master_doc = 'index' 42 | 43 | # General information about the project. 44 | project = 'djangorestframework-composed-permissions' 45 | copyright = '2013, Andrey Antukh' 46 | 47 | # The version info for the project you're documenting, acts as replacement for 48 | # |version| and |release|, also used in various other places throughout the 49 | # built documents. 50 | # 51 | # The short X.Y version. 52 | version = '0.1' 53 | # The full version, including alpha/beta/rc tags. 54 | release = '0.1' 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | #language = None 59 | 60 | # There are two options for replacing |today|: either, you set today to some 61 | # non-false value, then it is used: 62 | #today = '' 63 | # Else, today_fmt is used as the format for a strftime call. 64 | #today_fmt = '%B %d, %Y' 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | exclude_patterns = ['_build'] 69 | 70 | # The reST default role (used for this markup: `text`) to use for all documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | # A list of ignored prefixes for module index sorting. 88 | #modindex_common_prefix = [] 89 | 90 | # If true, keep warnings as "system message" paragraphs in the built documents. 91 | #keep_warnings = False 92 | 93 | 94 | # -- Options for HTML output --------------------------------------------------- 95 | 96 | # The theme to use for HTML and HTML Help pages. See the documentation for 97 | # a list of builtin themes. 98 | html_theme = 'pyramid' 99 | 100 | # Theme options are theme-specific and customize the look and feel of a theme 101 | # further. For a list of options available for each theme, see the 102 | # documentation. 103 | #html_theme_options = {} 104 | 105 | # Add any paths that contain custom themes here, relative to this directory. 106 | #html_theme_path = [] 107 | 108 | # The name for this set of Sphinx documents. If None, it defaults to 109 | # " v documentation". 110 | #html_title = None 111 | 112 | # A shorter title for the navigation bar. Default is the same as html_title. 113 | #html_short_title = None 114 | 115 | # The name of an image file (relative to this directory) to place at the top 116 | # of the sidebar. 117 | #html_logo = None 118 | 119 | # The name of an image file (within the static path) to use as favicon of the 120 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 121 | # pixels large. 122 | #html_favicon = None 123 | 124 | # Add any paths that contain custom static files (such as style sheets) here, 125 | # relative to this directory. They are copied after the builtin static files, 126 | # so a file named "default.css" will overwrite the builtin "default.css". 127 | html_static_path = ['_static'] 128 | 129 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 130 | # using the given strftime format. 131 | #html_last_updated_fmt = '%b %d, %Y' 132 | 133 | # If true, SmartyPants will be used to convert quotes and dashes to 134 | # typographically correct entities. 135 | #html_use_smartypants = True 136 | 137 | # Custom sidebar templates, maps document names to template names. 138 | #html_sidebars = {} 139 | 140 | # Additional templates that should be rendered to pages, maps page names to 141 | # template names. 142 | #html_additional_pages = {} 143 | 144 | # If false, no module index is generated. 145 | #html_domain_indices = True 146 | 147 | # If false, no index is generated. 148 | #html_use_index = True 149 | 150 | # If true, the index is split into individual pages for each letter. 151 | #html_split_index = False 152 | 153 | # If true, links to the reST sources are added to the pages. 154 | #html_show_sourcelink = True 155 | 156 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 157 | #html_show_sphinx = True 158 | 159 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 160 | #html_show_copyright = True 161 | 162 | # If true, an OpenSearch description file will be output, and all pages will 163 | # contain a tag referring to it. The value of this option must be the 164 | # base URL from which the finished HTML is served. 165 | #html_use_opensearch = '' 166 | 167 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 168 | #html_file_suffix = None 169 | 170 | # Output file base name for HTML help builder. 171 | htmlhelp_basename = 'djangorestframework-composed-permissionsdoc' 172 | 173 | 174 | # -- Options for LaTeX output -------------------------------------------------- 175 | 176 | latex_elements = { 177 | # The paper size ('letterpaper' or 'a4paper'). 178 | #'papersize': 'letterpaper', 179 | 180 | # The font size ('10pt', '11pt' or '12pt'). 181 | #'pointsize': '10pt', 182 | 183 | # Additional stuff for the LaTeX preamble. 184 | #'preamble': '', 185 | } 186 | 187 | # Grouping the document tree into LaTeX files. List of tuples 188 | # (source start file, target name, title, author, documentclass [howto/manual]). 189 | latex_documents = [ 190 | ('index', 'djangorestframework-composed-permissions.tex', 'djangorestframework-composed-permissions Documentation', 191 | 'Andrey Antukh', 'manual'), 192 | ] 193 | 194 | # The name of an image file (relative to this directory) to place at the top of 195 | # the title page. 196 | #latex_logo = None 197 | 198 | # For "manual" documents, if this is true, then toplevel headings are parts, 199 | # not chapters. 200 | #latex_use_parts = False 201 | 202 | # If true, show page references after internal links. 203 | #latex_show_pagerefs = False 204 | 205 | # If true, show URL addresses after external links. 206 | #latex_show_urls = False 207 | 208 | # Documents to append as an appendix to all manuals. 209 | #latex_appendices = [] 210 | 211 | # If false, no module index is generated. 212 | #latex_domain_indices = True 213 | 214 | 215 | # -- Options for manual page output -------------------------------------------- 216 | 217 | # One entry per manual page. List of tuples 218 | # (source start file, name, description, authors, manual section). 219 | man_pages = [ 220 | ('index', 'djangorestframework-composed-permissions', 'djangorestframework-composed-permissions Documentation', 221 | ['Andrey Antukh'], 1) 222 | ] 223 | 224 | # If true, show URL addresses after external links. 225 | #man_show_urls = False 226 | 227 | 228 | # -- Options for Texinfo output ------------------------------------------------ 229 | 230 | # Grouping the document tree into Texinfo files. List of tuples 231 | # (source start file, target name, title, author, 232 | # dir menu entry, description, category) 233 | texinfo_documents = [ 234 | ('index', 'djangorestframework-composed-permissions', 'djangorestframework-composed-permissions Documentation', 235 | 'Andrey Antukh', 'djangorestframework-composed-permissions', 'One line description of project.', 236 | 'Miscellaneous'), 237 | ] 238 | 239 | # Documents to append as an appendix to all manuals. 240 | #texinfo_appendices = [] 241 | 242 | # If false, no module index is generated. 243 | #texinfo_domain_indices = True 244 | 245 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 246 | #texinfo_show_urls = 'footnote' 247 | 248 | # If true, do not generate a @detailmenu in the "Top" node's menu. 249 | #texinfo_no_detailmenu = False 250 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | djangorestframework-composed-permissions 2 | ======================================== 3 | 4 | A simple way to define complex permissions for django-rest-framework. 5 | 6 | 7 | Introduction 8 | ------------ 9 | 10 | django-rest-framework by default has large ways to define permissions but none of them 11 | permits define a complex, multi depth and with logical operators permissions rules. 12 | 13 | djangorestframework-composed-permissions is full compatible with a django-rest-framework 14 | permissions api but implements a simple way to build permission objects using reusable 15 | components (called permission components). 16 | 17 | djangorestframework-composed-permissions has 3 type of classes: 18 | 19 | - Permission components: a basic unit of permission. 20 | - Permission set: a collection of components joined with logic operator (and, or, not) 21 | - Composed permissions: container of both, components and sets. Having the same interface 22 | as django-rest-framework default permission. 23 | 24 | 25 | How to install? 26 | --------------- 27 | 28 | It is very simple, install it on your virtualenv with pip: 29 | 30 | .. code-block:: console 31 | 32 | pip install djangorestframework-composed-permissions 33 | 34 | 35 | Quickstart 36 | ---------- 37 | 38 | The best way to understand how djangorestframework-composed-permissions works, is 39 | looking some examples. 40 | 41 | This package comes with some generic permission components defined for you, later 42 | we will see how to define your own component but for the first example we go to use 43 | one generic. 44 | 45 | We go to define one permission and viewset that uses it: 46 | 47 | .. code-block:: python 48 | 49 | from restfw_composed_permissions.base import (BaseComposedPermission, And, Or) 50 | from restfw_composed_permissions.generic.components import ( 51 | AllowAll, AllowOnlyAuthenticated, AllowOnlySafeHttpMethod) 52 | 53 | 54 | class UserPermission(BaseComposedPermission): 55 | def global_permission_set(self): 56 | return Or(AllowOnlyAuthenticated, 57 | And(AllowAll, AllowOnlySafeHttpMethod)) 58 | 59 | def object_permission_set(self): 60 | return AllowAll 61 | 62 | 63 | class UserViewSet(viewsets.ModelViewSet): 64 | """ 65 | A viewset for viewing and editing user instances. 66 | """ 67 | permission_classes = (UserPermission,) 68 | 69 | serializer_class = UserSerializer 70 | queryset = User.objects.all() 71 | 72 | 73 | .. note:: 74 | 75 | `And` & `Or` classes are permission sets, that groups some components with logical 76 | operator. Also exists `Not` but we don't use it on this example. 77 | 78 | `global_permission_set` method must return a permission set or only one component, and it 79 | is evaluted on every request, however `object_permission_set` is only evaluted when 80 | a create, update, delete operation is executed. 81 | 82 | With `UserPermission` defined on previous example, we allow any authenticated user 83 | for do any thing and allow anonymous requests only if request method is safe. 84 | 85 | See Permission Component below for classes to use when creating your own custom permission 86 | 87 | Low level api reference 88 | ----------------------- 89 | 90 | This is a low level api documentation for 3 main components of this package. 91 | 92 | 93 | Permission Component 94 | ~~~~~~~~~~~~~~~~~~~~ 95 | 96 | .. py:class:: restfw_composed_permissions.base.BasePermissionComponent 97 | 98 | .. py:method:: has_permission(self, permission, request, view) 99 | 100 | This method must be defined always, because it is used 101 | on global permission evaluation process and it is executed 102 | always on every request. 103 | 104 | If you not implement this method, it will raise NotImplementedError 105 | exception. 106 | 107 | :rtype: bool 108 | 109 | .. py:method:: has_object_permission(self, permission, request, view, obj) 110 | 111 | This method must be defined if this component will be used for object 112 | permission checking. 113 | 114 | By default, returns same thing as :py:ref:`has_permission`. 115 | 116 | :rtype: bool 117 | 118 | Here the extra permission argument contains the composed permission object. 119 | If you do not need this argument or are converting an existing permission class 120 | to a permission component you can subclass RestPermissionComponent instead 121 | 122 | .. py:class:: restfw_composed_permissions.base.RestPermissionComponent 123 | 124 | .. py:method:: has_permission(self, request, view) 125 | 126 | Same as above 127 | 128 | :rtype: bool 129 | 130 | .. py:method:: has_object_permission(self, request, view, obj) 131 | 132 | Same as above 133 | 134 | :rtype: bool 135 | 136 | Converting existing rest framework permissions is then done like this 137 | 138 | .. code-block:: python 139 | 140 | from rest_framework.permissions import IsAdminUser 141 | from restfw_composed_permissions.base import RestPermissionComponent 142 | 143 | class IsAdminUserComponent(IsAdminUser, RestPermissionComponent): 144 | pass 145 | 146 | Components subclassed from either RestPermissionComponent or BasePermissionComponent 147 | (Or a combination of both) can be used when creating a permission set 148 | 149 | You can look though `restfw_composed_permissions.generic.components` for more examples 150 | of how define your own permission components. 151 | 152 | 153 | Permission Sets 154 | ~~~~~~~~~~~~~~~ 155 | 156 | Permissions sets implement same interface as components. Permission sets groups 157 | N number of components with logical operator, with exception of `Not` that has 158 | special behavior and it accepts only one component as parameter. 159 | 160 | `And`, `Or` & `Not` are the default permission sets defined on this package. 161 | 162 | The usage of `And` example: 163 | 164 | .. code-block:: python 165 | 166 | # Simple usage as class instance 167 | class SomePermission1(BaseComposedPermission): 168 | global_permission_set = (lambda s: And(Component1, Component2)) 169 | 170 | # Using & operator of components 171 | class SomePermission2(BaseComposedPermission): 172 | global_permission_set = (lambda s: Component1() & Component2()) 173 | 174 | 175 | The usage of `Or` examples: 176 | 177 | .. code-block:: python 178 | 179 | # Simple usage as class instance 180 | class SomePermission1(BaseComposedPermission): 181 | global_permission_set = (lambda s: Or(Component1(some_param), Component2)) 182 | 183 | # Using | operator of components 184 | class SomePermission2(BaseComposedPermission): 185 | global_permission_set = (lambda s: Component1() | Component2()) 186 | 187 | # Returning a list of components 188 | class SomePermission3(BaseComposedPermission): 189 | global_permission_set = (lambda s: [Component1, Component2]) 190 | 191 | 192 | Finally, `Not` usage examples: 193 | 194 | .. code-block:: python 195 | 196 | # Simple usage as class instance 197 | class SomePermission1(BaseComposedPermission): 198 | global_permission_set = (lambda s: Not(Component1)) 199 | 200 | # Using ~ operator of components 201 | class SomePermission2(BaseComposedPermission): 202 | global_permission_set = (lambda s: ~Component1()) 203 | 204 | 205 | Composed Permission 206 | ~~~~~~~~~~~~~~~~~~~ 207 | 208 | This is a toplevel class of 3 main components of this package. 209 | 210 | .. py:class:: restfw_composed_permissions.base.BaseComposedPermission 211 | 212 | Any subclass of this must define `global_permission_set` as mandatory 213 | method and optionally `object_permission_set` method. 214 | 215 | These methods must return a :py:class:`~restfw_composed_permissions.base.BasePermissionComponent` subclass 216 | or :py:class:`~restfw_composed_permissions.base.BasePermissionSet` subclass. 217 | 218 | 219 | Generics 220 | -------- 221 | 222 | Components 223 | ~~~~~~~~~~ 224 | 225 | .. py:class:: restfw_composed_permissions.generic.components.AllowAll 226 | 227 | Always allow all requests without any constraints. 228 | 229 | .. py:class:: restfw_composed_permissions.generic.components.AllowOnlyAnonymous 230 | 231 | Only allow anonymous requests. 232 | 233 | .. py:class:: restfw_composed_permissions.generic.components.AllowOnlyAuthenticated 234 | 235 | Only allow authenticated requests. 236 | 237 | .. py:class:: restfw_composed_permissions.generic.components.AllowOnlySafeHttpMethod 238 | 239 | Only allow safe http methods. 240 | 241 | .. py:class:: restfw_composed_permissions.generic.components.ObjectAttrEqualToObjectAttr 242 | 243 | This is a object level permission component and if is used on 244 | global permission context it always returns True. 245 | 246 | This component checks the equality of two expressions that are 247 | evaluted in "safe" way. On the context of eval are exposed "obj" 248 | as current object and "request" as the current request. 249 | 250 | This component works well for check a object owner os similary. 251 | 252 | Example: 253 | 254 | .. code-block:: python 255 | 256 | class SomePermission(BaseComposedPermission): 257 | global_permission_set = (lambda self: AllowAll) 258 | object_permission_set = (lambda self: 259 | ObjectAttrEqualToObjectAttr("request.user", "obj.owner")) 260 | -------------------------------------------------------------------------------- /restfw_composed_permissions/tests/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from django.test import TestCase, tag 4 | from restfw_composed_permissions.base import (BaseComposedPermission, 5 | BasePermissionComponent, 6 | RestPermissionComponent, 7 | And, Or, Not) 8 | 9 | from restfw_composed_permissions.generic import components 10 | 11 | 12 | def create_component(value, instance=False): 13 | class SimpleComponent(BasePermissionComponent): 14 | def has_permission(self, permission, request, view): 15 | return value 16 | 17 | def has_object_permission(self, permission, request, view, obj): 18 | return value 19 | 20 | if instance: 21 | return SimpleComponent() 22 | return SimpleComponent 23 | 24 | def create_rest_component(value, instance=False): 25 | class SimpleComponent(RestPermissionComponent): 26 | def has_permission(self, request, view): 27 | return value 28 | 29 | def has_object_permission(self, request, view, obj): 30 | return value 31 | 32 | if instance: 33 | return SimpleComponent() 34 | return SimpleComponent 35 | 36 | 37 | def create_permission(callback1, callback2=None): 38 | class Permission(BaseComposedPermission): 39 | if callback1: 40 | global_permission_set = lambda self: callback1() 41 | 42 | if callback2: 43 | object_permission_set = lambda self: callback2() 44 | 45 | return Permission 46 | 47 | 48 | class CorePermissionFrameworkTests(TestCase): 49 | 50 | def test_permission_with_unique_component(self): 51 | Component = create_component(True) 52 | Permission = create_permission(lambda: Component, None) 53 | 54 | permission = Permission() 55 | self.assertTrue(permission.has_permission(None, None)) 56 | 57 | #self.assertTrue(len(permission._permission_set.components), 1) 58 | 59 | def test_permission_with_two_components_as_list(self): 60 | Component = create_component(True) 61 | Permission = create_permission(lambda: [Component, Component], None) 62 | 63 | permission = Permission() 64 | self.assertTrue(permission.has_permission(None, None)) 65 | self.assertTrue(len(permission.global_permission_set()), 2) 66 | 67 | def test_permission_with_or_permission_set_01(self): 68 | Permission = create_permission(lambda: Or( 69 | create_component(True), 70 | create_component(True), 71 | create_component(True)), None) 72 | 73 | permission = Permission() 74 | self.assertTrue(permission.has_permission(None, None)) 75 | self.assertTrue(len(permission.global_permission_set().components), 3) 76 | 77 | 78 | def test_permission_with_or_permission_set_02(self): 79 | # | operator only works for instances and not classes 80 | components = (lambda: Or( 81 | create_component(False)(), 82 | create_component(False)(), 83 | create_component(True)())) 84 | 85 | Permission = create_permission(components, components) 86 | 87 | permission = Permission() 88 | self.assertTrue(permission.has_permission(None, None)) 89 | self.assertTrue(permission.has_object_permission(None, None, None)) 90 | self.assertIsInstance(permission.global_permission_set(), Or) 91 | self.assertTrue(len(permission.global_permission_set().components), 3) 92 | 93 | def test_permission_with_or_permission_set_03(self): 94 | # | operator only works for instances and not classes 95 | components = (lambda: 96 | create_component(False)() | 97 | create_component(False)() | 98 | create_component(True)()) 99 | 100 | Permission = create_permission(components, components) 101 | 102 | permission = Permission() 103 | self.assertTrue(permission.has_permission(None, None)) 104 | self.assertTrue(permission.has_object_permission(None, None, None)) 105 | self.assertTrue(len(permission.object_permission_set().components), 3) 106 | 107 | def test_permission_with_and_permission_set_01(self): 108 | Permission = create_permission(lambda: And( 109 | create_component(True), 110 | create_component(True), 111 | create_component(True))) 112 | 113 | permission = Permission() 114 | self.assertTrue(permission.has_permission(None, None)) 115 | self.assertTrue(len(list(permission.global_permission_set().components)), 3) 116 | 117 | 118 | def test_permission_with_and_permission_set_02(self): 119 | Permission = create_permission(lambda: And( 120 | create_component(False), 121 | create_component(False), 122 | create_component(True))) 123 | 124 | permission = Permission() 125 | self.assertFalse(permission.has_permission(None, None)) 126 | self.assertTrue(len(list(permission.global_permission_set().components)), 3) 127 | 128 | def test_permission_with_and_permission_set_03(self): 129 | Permission = create_permission(lambda: create_component(False)() & 130 | create_component(False)() & 131 | create_component(True)() ) 132 | 133 | permission = Permission() 134 | self.assertFalse(permission.has_permission(None, None)) 135 | self.assertTrue(len(permission.global_permission_set().components), 3) 136 | 137 | def test_permission_with_complex_compositions_01(self): 138 | TrueComponent = create_component(True) 139 | FalseComponent = create_component(False) 140 | 141 | permissions_set = (TrueComponent() & TrueComponent()) | FalseComponent() 142 | permission = create_permission(lambda: permissions_set)() 143 | 144 | self.assertTrue(permission.has_permission(None, None)) 145 | 146 | def test_permission_with_complex_compositions_02(self): 147 | TrueComponent = create_component(True) 148 | FalseComponent = create_component(False) 149 | 150 | permissions_set = ((TrueComponent() & TrueComponent()) & 151 | (FalseComponent() | (TrueComponent() & TrueComponent()))) 152 | permission = create_permission(lambda: permissions_set)() 153 | 154 | self.assertTrue(permission.has_permission(None, None)) 155 | 156 | def test_permission_with_complex_compositions_03(self): 157 | TrueComponent = create_component(True) 158 | FalseComponent = create_component(False) 159 | 160 | permissions_set = ((TrueComponent() & TrueComponent()) & 161 | (FalseComponent() | (FalseComponent() & TrueComponent()))) 162 | permission = create_permission(lambda: permissions_set)() 163 | 164 | self.assertFalse(permission.has_permission(None, None)) 165 | 166 | def test_rest_permission_components(self): 167 | TrueComponent = create_rest_component(True) 168 | FalseComponent = create_rest_component(False) 169 | 170 | permissions_set = Not((TrueComponent() & FalseComponent()) | TrueComponent()) 171 | permission = create_permission(lambda: permissions_set)() 172 | 173 | self.assertFalse(permission.has_permission(None, None)) 174 | 175 | def test_mixed_permission_components(self): 176 | TrueComponent = create_component(True) 177 | FalseComponent = create_rest_component(False) 178 | 179 | permissions_set = (TrueComponent() & FalseComponent()) 180 | permission = create_permission(lambda: permissions_set)() 181 | 182 | self.assertFalse(permission.has_permission(None, None)) 183 | 184 | def test_not_permissions(self): 185 | TrueComponent = create_component(True) 186 | FalseComponent = create_component(False) 187 | 188 | permissions_set = Not(TrueComponent() & FalseComponent()) 189 | permission = create_permission(lambda: permissions_set)() 190 | 191 | self.assertTrue(permission.has_permission(None, None)) 192 | 193 | 194 | class GenericComponentsTests(TestCase): 195 | def make_mock(self): 196 | class Mock(object): 197 | pass 198 | 199 | return Mock() 200 | 201 | def make_request(self): 202 | 203 | request = self.make_mock() 204 | request.user = self.make_mock() 205 | return request 206 | 207 | def test_allow_all(self): 208 | instance = components.AllowAll() 209 | self.assertTrue(instance.has_permission(None, None, None)) 210 | 211 | def test_allow_only_anonymous(self): 212 | request = self.make_request() 213 | request.user.is_anonymous = True 214 | 215 | instance = components.AllowOnlyAnonymous() 216 | self.assertTrue(instance.has_permission(None, request, None)) 217 | 218 | def test_allow_authenticated(self): 219 | request = self.make_request() 220 | request.user.is_anonymous = False 221 | 222 | instance = components.AllowOnlyAuthenticated() 223 | self.assertTrue(instance.has_permission(None, request, None)) 224 | 225 | def test_allow_safe_method_only(self): 226 | request = self.make_request() 227 | request.method = "GET" 228 | 229 | instance = components.AllowOnlySafeHttpMethod() 230 | self.assertTrue(instance.has_permission(None, request, None)) 231 | 232 | def test_obj_attr_equality(self): 233 | obj = self.make_mock() 234 | obj.x = 1 235 | obj.y = 1 236 | 237 | instance = components.ObjectAttrEqualToObjectAttr("obj.x", "obj.y") 238 | self.assertTrue(instance.has_object_permission(None, None, None, obj)) 239 | --------------------------------------------------------------------------------