pax_global_header00006660000000000000000000000064145262141160014514gustar00rootroot0000000000000052 comment=bb4d699b3cc42dccd7b889ff0aad243ad80e37a5 aiohttp-security-0.5.0/000077500000000000000000000000001452621411600150335ustar00rootroot00000000000000aiohttp-security-0.5.0/.coveragerc000066400000000000000000000001461452621411600171550ustar00rootroot00000000000000[run] branch = True source = aiohttp_security, tests omit = site-packages [html] directory = coverageaiohttp-security-0.5.0/.flake8000066400000000000000000000012471452621411600162120ustar00rootroot00000000000000[flake8] enable-extensions = G extend-exclude = build/ max-doc-length = 90 max-line-length = 90 select = A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,B901,B902,B903,B950 # E226: Missing whitespace around arithmetic operators can help group things together. # E501: Superseeded by B950 (from Bugbear) # E722: Superseeded by B001 (from Bugbear) # W503: Mutually exclusive with W504. ignore = E226,E501,E722,W503 per-file-ignores = # S101: Pytest uses assert tests/*:S101 # flake8-import-order application-import-names = aiohttp_security import-order-style = pycharm # flake8-quotes inline-quotes = " # flake8-requirements requirements-file = requirements-dev.txt aiohttp-security-0.5.0/.github/000077500000000000000000000000001452621411600163735ustar00rootroot00000000000000aiohttp-security-0.5.0/.github/dependabot.yml000066400000000000000000000003531452621411600212240ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: pip directory: "/" schedule: interval: daily open-pull-requests-limit: 10 - package-ecosystem: "github-actions" directory: "/" schedule: interval: "monthly" aiohttp-security-0.5.0/.github/workflows/000077500000000000000000000000001452621411600204305ustar00rootroot00000000000000aiohttp-security-0.5.0/.github/workflows/auto-merge.yml000066400000000000000000000011401452621411600232140ustar00rootroot00000000000000name: Dependabot auto-merge on: pull_request_target permissions: pull-requests: write contents: write jobs: dependabot: runs-on: ubuntu-latest if: ${{ github.actor == 'dependabot[bot]' }} steps: - name: Dependabot metadata id: metadata uses: dependabot/fetch-metadata@v1.6.0 with: github-token: "${{ secrets.GITHUB_TOKEN }}" - name: Enable auto-merge for Dependabot PRs run: gh pr merge --auto --squash "$PR_URL" env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} aiohttp-security-0.5.0/.github/workflows/ci.yaml000066400000000000000000000060101452621411600217040ustar00rootroot00000000000000name: CI on: push: branches: - master - '[0-9].[0-9]+' tags: [ 'v*' ] pull_request: branches: - master - '[0-9].[0-9]+' jobs: lint: name: Linter runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Checkout uses: actions/checkout@v4 - name: Setup Python uses: actions/setup-python@v4 with: python-version: '3.10' cache: 'pip' cache-dependency-path: '**/requirements*.txt' - name: Install dependencies uses: py-actions/py-dependency-install@v4 with: path: requirements-dev.txt - name: Install itself run: | pip install . - name: Mypy run: mypy - name: Flake8 run: flake8 - name: Prepare twine checker run: | pip install -U build twine python -m build - name: Run twine checker run: | twine check --strict dist/* test: name: Tests runs-on: ubuntu-latest strategy: matrix: pyver: ['pypy-3.8', '3.8', '3.9', '3.10', '3.11', '3.12'] timeout-minutes: 15 steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.pyver }} cache: 'pip' cache-dependency-path: '**/requirements*.txt' - name: Install dependencies uses: py-actions/py-dependency-install@v4 with: path: requirements.txt - name: Run unittests env: COLOR: 'yes' run: | pytest tests --cov-report xml python -m coverage xml - name: Upload coverage uses: codecov/codecov-action@v3 with: file: ./coverage.xml flags: unit fail_ci_if_error: false check: # This job does nothing and is only used for the branch protection if: always() needs: [lint, test] runs-on: ubuntu-latest steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} deploy: name: Deploy environment: release if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') needs: [check] runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Setup Python uses: actions/setup-python@v4 with: python-version: 3.8 - name: Install dependencies run: python -m pip install -U pip wheel setuptools build twine - name: Build dists run: | python -m build - name: Make Release uses: aio-libs/create-release@v1.6.6 with: changes_file: CHANGES.rst name: aiohttp-security version_file: aiohttp_security/__init__.py github_token: ${{ secrets.GITHUB_TOKEN }} pypi_token: ${{ secrets.PYPI_API_TOKEN }} dist_dir: dist fix_issue_regex: "`#(\\d+) `" fix_issue_repl: "(#\\1)" aiohttp-security-0.5.0/.github/workflows/codeql.yml000066400000000000000000000044471452621411600224330ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [ 'master' ] pull_request: # The branches below must be a subset of the branches above branches: [ 'master' ] schedule: - cron: '6 6 * * 5' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'python' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs # queries: security-extended,security-and-quality # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # If the Autobuild fails above, remove it and uncomment the following three lines. # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | # echo "Run, Build Application using script" # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 with: category: "/language:${{matrix.language}}" aiohttp-security-0.5.0/.gitignore000066400000000000000000000013101452621411600170160ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ bin/ build/ develop-eggs/ dist/ downloads/ eggs/ include/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ coverage .pytest_cacheaiohttp-security-0.5.0/.mypy.ini000066400000000000000000000014231452621411600166100ustar00rootroot00000000000000[mypy] files = aiohttp_security, demo, tests check_untyped_defs = True follow_imports_for_stubs = True disallow_any_decorated = True disallow_any_generics = True disallow_any_unimported = True disallow_incomplete_defs = True disallow_subclassing_any = True disallow_untyped_calls = True disallow_untyped_decorators = True disallow_untyped_defs = True enable_error_code = redundant-expr, truthy-bool, ignore-without-code, unused-awaitable implicit_reexport = False no_implicit_optional = True pretty = True show_column_numbers = True show_error_codes = True strict_equality = True warn_incomplete_stub = True warn_redundant_casts = True warn_return_any = True warn_unreachable = True warn_unused_ignores = True [mypy-tests.*] disallow_any_decorated = False disallow_untyped_defs = False aiohttp-security-0.5.0/CHANGES.rst000066400000000000000000000020461452621411600166370ustar00rootroot00000000000000======= CHANGES ======= .. towncrier release notes start 0.5.0 (2023-11-18) ================== - Added type annotations. - Added a reason message when permission is rejected. - Switched to ``aiohttp.web.AppKey``. - Reverted change in ``JWTIdentityPolicy`` so identity returns ``str``. 0.4.0 (2018-09-27) ================== - Bump minimal supported ``aiohttp`` version to 3.2. - Use ``request.config_dict`` for accessing ``jinja2`` environment. It allows to reuse jinja rendering engine from parent application. 0.3.0 (2018-09-06) ================== - Deprecate ``login_required`` and ``has_permission`` decorators. Use ``check_authorized`` and ``check_permission`` helper functions instead. - Bump supported ``aiohttp`` version to 3.0+. - Enable strong warnings mode for test suite, clean-up all deprecation warnings. - Polish documentation 0.2.0 (2017-11-17) ================== - Add ``is_anonymous``, ``login_required``, ``has_permission`` helpers. (#114) 0.1.2 (2017-10-17) ================== - Make aiohttp-session optional dependency. (#107) aiohttp-security-0.5.0/LICENSE000066400000000000000000000261101452621411600160400ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015-2018 Andrew Svetlov and aio-libs team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. aiohttp-security-0.5.0/MANIFEST.in000066400000000000000000000002321452621411600165660ustar00rootroot00000000000000include LICENSE include CHANGES.rst include README.rst include Makefile graft aiohttp_security graft docs graft examples graft tests global-exclude *.pyc aiohttp-security-0.5.0/Makefile000066400000000000000000000014441452621411600164760ustar00rootroot00000000000000# Some simple testing tasks (sorry, UNIX only). lint: flake8 test: flake pytest -s -q ./tests/ vtest: flake pytest -s ./tests/ cov cover coverage: flake pytest -s ./tests/ --cov-report=term @echo "open file://`pwd`/coverage/index.html" clean: rm -rf `find . -name __pycache__` rm -f `find . -type f -name '*.py[co]' ` rm -f `find . -type f -name '*~' ` rm -f `find . -type f -name '.*~' ` rm -f `find . -type f -name '@*' ` rm -f `find . -type f -name '#*#' ` rm -f `find . -type f -name '*.orig' ` rm -f `find . -type f -name '*.rej' ` rm -f .coverage rm -rf coverage rm -rf build rm -rf cover make -C docs clean python setup.py clean doc: make -C docs html @echo "open file://`pwd`/docs/_build/html/index.html" .PHONY: all build venv flake test vtest testloop cov clean doc aiohttp-security-0.5.0/README.rst000066400000000000000000000025051452621411600165240ustar00rootroot00000000000000aiohttp_security ================ .. image:: https://travis-ci.com/aio-libs/aiohttp-security.svg?branch=master :target: https://travis-ci.com/aio-libs/aiohttp-security .. image:: https://codecov.io/github/aio-libs/aiohttp-security/coverage.svg?branch=master :target: https://codecov.io/github/aio-libs/aiohttp-security .. image:: https://readthedocs.org/projects/aiohttp-security/badge/?version=latest :target: https://aiohttp-security.readthedocs.io/ .. image:: https://img.shields.io/pypi/v/aiohttp-security.svg :target: https://pypi.python.org/pypi/aiohttp-security The library provides identity and authorization for `aiohttp.web`__. .. _aiohttp_web: http://aiohttp.readthedocs.org/en/latest/web.html __ aiohttp_web_ Installation ------------ Simplest case (authorization via cookies) :: $ pip install aiohttp_security With `aiohttp-session` support :: $ pip install aiohttp_security[session] Examples -------- Take a look at examples: `Basic example`_ `Example with DB auth`_ .. _`Basic example`: docs/example.rst .. _`Example with db auth`: docs/example_db_auth.rst and demos at **demo** directory. Documentation ------------- https://aiohttp-security.readthedocs.io/ Develop ------- ``pip install -r requirements-dev.txt`` License ------- ``aiohttp_security`` is offered under the Apache 2 license. aiohttp-security-0.5.0/aiohttp_security/000077500000000000000000000000001452621411600204325ustar00rootroot00000000000000aiohttp-security-0.5.0/aiohttp_security/__init__.py000066400000000000000000000012661452621411600225500ustar00rootroot00000000000000from .abc import AbstractAuthorizationPolicy, AbstractIdentityPolicy from .api import (authorized_userid, check_authorized, check_permission, forget, is_anonymous, permits, remember, setup) from .cookies_identity import CookiesIdentityPolicy from .jwt_identity import JWTIdentityPolicy from .session_identity import SessionIdentityPolicy __version__ = '0.5.0' __all__ = ('AbstractIdentityPolicy', 'AbstractAuthorizationPolicy', 'CookiesIdentityPolicy', 'SessionIdentityPolicy', 'JWTIdentityPolicy', 'remember', 'forget', 'authorized_userid', 'permits', 'setup', 'is_anonymous', 'check_authorized', 'check_permission') aiohttp-security-0.5.0/aiohttp_security/abc.py000066400000000000000000000035011452621411600215300ustar00rootroot00000000000000import abc from enum import Enum from typing import Any, Optional, Union from aiohttp import web # see http://plope.com/pyramid_auth_design_api_postmortem class AbstractIdentityPolicy(metaclass=abc.ABCMeta): @abc.abstractmethod async def identify(self, request: web.Request) -> Optional[str]: """Return the claimed identity of the user associated request or ``None`` if no identity can be found associated with the request.""" pass @abc.abstractmethod async def remember(self, request: web.Request, # type: ignore[misc] response: web.StreamResponse, identity: str, **kwargs: Any) -> None: """Remember identity. Modify response object by filling it's headers with remembered user. An individual identity policy and its consumers can decide on the composition and meaning of **kwargs. """ pass @abc.abstractmethod async def forget(self, request: web.Request, response: web.StreamResponse) -> None: """ Modify response which can be used to 'forget' the current identity on subsequent requests.""" pass class AbstractAuthorizationPolicy(metaclass=abc.ABCMeta): @abc.abstractmethod async def permits(self, identity: Optional[str], # type: ignore[misc] permission: Union[str, Enum], context: Any = None) -> bool: """Check user permissions. Return True if the identity is allowed the permission in the current context, else return False. """ pass @abc.abstractmethod async def authorized_userid(self, identity: str) -> Optional[str]: """Retrieve authorized user id. Return the user_id of the user identified by the identity or 'None' if no user exists related to the identity. """ pass aiohttp-security-0.5.0/aiohttp_security/api.py000066400000000000000000000117041452621411600215600ustar00rootroot00000000000000import enum from typing import Any, Optional, Union from aiohttp import web from aiohttp_security.abc import AbstractAuthorizationPolicy, AbstractIdentityPolicy IDENTITY_KEY = web.AppKey("IDENTITY_KEY", AbstractIdentityPolicy) AUTZ_KEY = web.AppKey("AUTZ_KEY", AbstractAuthorizationPolicy) # _AIP/_AAP are shorthand for Optional[policy] when we retrieve from request. _AAP = Optional[AbstractAuthorizationPolicy] _AIP = Optional[AbstractIdentityPolicy] async def remember(request: web.Request, response: web.StreamResponse, identity: str, **kwargs: Any) -> None: """Remember identity into response. The action is performed by identity_policy.remember() Usually the identity is stored in user cookies somehow but may be pushed into custom header also. """ if not identity or not isinstance(identity, str): raise ValueError("Identity should be a str value.") identity_policy = request.config_dict.get(IDENTITY_KEY) if identity_policy is None: text = ("Security subsystem is not initialized, " "call aiohttp_security.setup(...) first") # in order to see meaningful exception message both: on console # output and rendered page we add same message to *reason* and # *text* arguments. raise web.HTTPInternalServerError(reason=text, text=text) await identity_policy.remember(request, response, identity, **kwargs) async def forget(request: web.Request, response: web.StreamResponse) -> None: """Forget previously remembered identity. Usually it clears cookie or server-side storage to forget user session. """ identity_policy = request.config_dict.get(IDENTITY_KEY) if identity_policy is None: text = ("Security subsystem is not initialized, " "call aiohttp_security.setup(...) first") # in order to see meaningful exception message both: on console # output and rendered page we add same message to *reason* and # *text* arguments. raise web.HTTPInternalServerError(reason=text, text=text) await identity_policy.forget(request, response) async def authorized_userid(request: web.Request) -> Optional[str]: identity_policy: _AIP = request.config_dict.get(IDENTITY_KEY) autz_policy: _AAP = request.config_dict.get(AUTZ_KEY) if identity_policy is None or autz_policy is None: return None identity = await identity_policy.identify(request) if identity is None: return None # non-registered user has None user_id user_id = await autz_policy.authorized_userid(identity) return user_id async def permits(request: web.Request, permission: Union[str, enum.Enum], context: Any = None) -> bool: if not permission or not isinstance(permission, (str, enum.Enum)): raise ValueError("Permission should be a str or enum value.") identity_policy: _AIP = request.config_dict.get(IDENTITY_KEY) autz_policy: _AAP = request.config_dict.get(AUTZ_KEY) if identity_policy is None or autz_policy is None: return True identity = await identity_policy.identify(request) # non-registered user still may have some permissions access = await autz_policy.permits(identity, permission, context) return access async def is_anonymous(request: web.Request) -> bool: """Check if user is anonymous. User is considered anonymous if there is not identity in request. """ identity_policy = request.config_dict.get(IDENTITY_KEY) if identity_policy is None: return True identity = await identity_policy.identify(request) if identity is None: return True return False async def check_authorized(request: web.Request) -> str: """Checker that raises HTTPUnauthorized for anonymous users. """ userid = await authorized_userid(request) if userid is None: raise web.HTTPUnauthorized() return userid async def check_permission(request: web.Request, permission: Union[str, enum.Enum], context: Any = None) -> None: """Checker that passes only to authoraised users with given permission. If user is not authorized - raises HTTPUnauthorized, if user is authorized and does not have permission - raises HTTPForbidden. """ await check_authorized(request) allowed = await permits(request, permission, context) if not allowed: raise web.HTTPForbidden(reason="User does not have '{}' permission".format(permission)) def setup(app: web.Application, identity_policy: AbstractIdentityPolicy, autz_policy: AbstractAuthorizationPolicy) -> None: if not isinstance(identity_policy, AbstractIdentityPolicy): raise ValueError("Identity policy is not subclass of AbstractIdentityPolicy") if not isinstance(autz_policy, AbstractAuthorizationPolicy): raise ValueError("Authentication policy is not subclass of AbstractAuthorizationPolicy") app[IDENTITY_KEY] = identity_policy app[AUTZ_KEY] = autz_policy aiohttp-security-0.5.0/aiohttp_security/cookies_identity.py000066400000000000000000000023121452621411600243470ustar00rootroot00000000000000"""Identity policy for storing info directly into HTTP cookie. Use mostly for demonstration purposes, SessionIdentityPolicy is much more handy. """ from typing import Any, NewType, Optional, Union, cast from aiohttp import web from .abc import AbstractIdentityPolicy _Sentinel = NewType("_Sentinel", object) sentinel = _Sentinel(object()) class CookiesIdentityPolicy(AbstractIdentityPolicy): def __init__(self) -> None: self._cookie_name = 'AIOHTTP_SECURITY' self._max_age = 30 * 24 * 3600 async def identify(self, request: web.Request) -> Optional[str]: return request.cookies.get(self._cookie_name) async def remember(self, request: web.Request, response: web.StreamResponse, identity: str, max_age: Union[_Sentinel, Optional[int]] = sentinel, **kwargs: Any) -> None: if max_age is sentinel: max_age = self._max_age max_age = cast(Optional[int], max_age) response.set_cookie(self._cookie_name, identity, max_age=max_age, **kwargs) async def forget(self, request: web.Request, response: web.StreamResponse) -> None: response.del_cookie(self._cookie_name) aiohttp-security-0.5.0/aiohttp_security/jwt_identity.py000066400000000000000000000027731452621411600235320ustar00rootroot00000000000000"""Identity policy for storing info in the jwt token. """ from typing import Optional from aiohttp import web from .abc import AbstractIdentityPolicy try: import jwt HAS_JWT = True except ImportError: # pragma: no cover HAS_JWT = False AUTH_HEADER_NAME = 'Authorization' AUTH_SCHEME = 'Bearer ' class JWTIdentityPolicy(AbstractIdentityPolicy): def __init__(self, secret: str, algorithm: str = "HS256", key: str = "login"): if not HAS_JWT: raise RuntimeError('Please install `PyJWT`') self.secret = secret self.algorithm = algorithm self.key = key async def identify(self, request: web.Request) -> Optional[str]: header_identity = request.headers.get(AUTH_HEADER_NAME) if header_identity is None: return None if not header_identity.startswith(AUTH_SCHEME): raise ValueError("Invalid authorization scheme. " + "Should be `{}`".format(AUTH_SCHEME)) token = header_identity.split(' ')[1].strip() identity = jwt.decode(token, self.secret, algorithms=[self.algorithm]) return identity.get(self.key) # type: ignore[no-any-return] async def remember(self, request: web.Request, response: web.StreamResponse, identity: str, **kwargs: None) -> None: pass async def forget(self, request: web.Request, response: web.StreamResponse) -> None: pass aiohttp-security-0.5.0/aiohttp_security/py.typed000066400000000000000000000000001452621411600221170ustar00rootroot00000000000000aiohttp-security-0.5.0/aiohttp_security/session_identity.py000066400000000000000000000024471452621411600244070ustar00rootroot00000000000000"""Identity policy for storing info into aiohttp_session session. aiohttp_session.setup() should be called on application initialization to configure aiohttp_session properly. """ from typing import Optional from aiohttp import web try: from aiohttp_session import get_session HAS_AIOHTTP_SESSION = True except ImportError: # pragma: no cover HAS_AIOHTTP_SESSION = False from .abc import AbstractIdentityPolicy class SessionIdentityPolicy(AbstractIdentityPolicy): def __init__(self, session_key: str = 'AIOHTTP_SECURITY'): self._session_key = session_key if not HAS_AIOHTTP_SESSION: # pragma: no cover raise ImportError( 'SessionIdentityPolicy requires `aiohttp_session`') async def identify(self, request: web.Request) -> Optional[str]: session = await get_session(request) return session.get(self._session_key) async def remember(self, request: web.Request, response: web.StreamResponse, identity: str, **kwargs: None) -> None: session = await get_session(request) session[self._session_key] = identity async def forget(self, request: web.Request, response: web.StreamResponse) -> None: session = await get_session(request) session.pop(self._session_key, None) aiohttp-security-0.5.0/demo/000077500000000000000000000000001452621411600157575ustar00rootroot00000000000000aiohttp-security-0.5.0/demo/__init__.py000066400000000000000000000000001452621411600200560ustar00rootroot00000000000000aiohttp-security-0.5.0/demo/database_auth/000077500000000000000000000000001452621411600205445ustar00rootroot00000000000000aiohttp-security-0.5.0/demo/database_auth/__init__.py000066400000000000000000000000001452621411600226430ustar00rootroot00000000000000aiohttp-security-0.5.0/demo/database_auth/__main__.py000066400000000000000000000001601452621411600226330ustar00rootroot00000000000000from aiohttp.web import run_app from .main import init_app if __name__ == "__main__": run_app(init_app()) aiohttp-security-0.5.0/demo/database_auth/db.py000066400000000000000000000024601452621411600215050ustar00rootroot00000000000000import sqlalchemy as sa from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship class Base(DeclarativeBase): metadata = sa.MetaData(naming_convention={ "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(column_0_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" }) class User(Base): """A user and their credentials.""" __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) username: Mapped[str] = mapped_column(sa.String(256), unique=True, index=True) password: Mapped[str] = mapped_column(sa.String(256)) is_superuser: Mapped[bool] = mapped_column( default=False, server_default=sa.sql.expression.false()) disabled: Mapped[bool] = mapped_column( default=False, server_default=sa.sql.expression.false()) permissions = relationship("Permission", cascade="all, delete") class Permission(Base): """A permission that grants a user access to something.""" __tablename__ = "permissions" user_id: Mapped[int] = mapped_column( sa.ForeignKey(User.id, ondelete="CASCADE"), primary_key=True) name: Mapped[str] = mapped_column(sa.String(64), primary_key=True) aiohttp-security-0.5.0/demo/database_auth/db_auth.py000066400000000000000000000034711452621411600225310ustar00rootroot00000000000000from enum import Enum import sqlalchemy as sa from passlib.hash import sha256_crypt from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from sqlalchemy.orm import selectinload from aiohttp_security.abc import AbstractAuthorizationPolicy from .db import User def _where_authorized(identity: str) -> tuple[sa.sql.ColumnElement[bool], ...]: return (User.username == identity, ~User.disabled) class DBAuthorizationPolicy(AbstractAuthorizationPolicy): def __init__(self, dbsession: async_sessionmaker[AsyncSession]): self.dbsession = dbsession async def authorized_userid(self, identity: str) -> str | None: where = _where_authorized(identity) async with self.dbsession() as sess: user_id = await sess.scalar(sa.select(User.id).where(*where)) return str(user_id) if user_id else None async def permits(self, identity: str | None, permission: str | Enum, context: dict[str, object] | None = None) -> bool: if identity is None: return False where = _where_authorized(identity) stmt = sa.select(User).options(selectinload(User.permissions)).where(*where) async with self.dbsession() as sess: user = await sess.scalar(stmt) if user is None: return False if user.is_superuser: return True return any(p.name == permission for p in user.permissions) async def check_credentials(db_session: async_sessionmaker[AsyncSession], username: str, password: str) -> bool: where = _where_authorized(username) async with db_session() as sess: hashed_pw = await sess.scalar(sa.select(User.password).where(*where)) if hashed_pw is None: return False return sha256_crypt.verify(password, hashed_pw) aiohttp-security-0.5.0/demo/database_auth/handlers.py000066400000000000000000000054671452621411600227320ustar00rootroot00000000000000from textwrap import dedent from typing import NoReturn from aiohttp import web from aiohttp_security import (authorized_userid, check_authorized, check_permission, forget, remember) from .db_auth import check_credentials class Web: index_template = dedent("""

{message}

Login: Password:
Logout """) async def index(self, request: web.Request) -> web.Response: username = await authorized_userid(request) if username: template = self.index_template.format( message='Hello, {username}!'.format(username=username)) else: template = self.index_template.format(message='You need to login') return web.Response(text=template, content_type="text/html") async def login(self, request: web.Request) -> NoReturn: invalid_resp = web.HTTPUnauthorized(body=b"Invalid username/password combination") form = await request.post() login = form.get('login') password = form.get('password') if not (isinstance(login, str) and isinstance(password, str)): raise invalid_resp if await check_credentials(request.app["db_session"], login, password): response = web.HTTPFound("/") await remember(request, response, login) raise response raise invalid_resp async def logout(self, request: web.Request) -> web.Response: await check_authorized(request) response = web.Response(text="You have been logged out") await forget(request, response) return response async def internal_page(self, request: web.Request) -> web.Response: await check_permission(request, 'public') return web.Response(text="This page is visible for all registered users") async def protected_page(self, request: web.Request) -> web.Response: await check_permission(request, 'protected') return web.Response(text="You are on protected page") def configure(self, app: web.Application) -> None: router = app.router router.add_route('GET', '/', self.index, name='index') router.add_route('POST', '/login', self.login, name='login') router.add_route('GET', '/logout', self.logout, name='logout') router.add_route('GET', '/public', self.internal_page, name='public') router.add_route('GET', '/protected', self.protected_page, name='protected') aiohttp-security-0.5.0/demo/database_auth/main.py000066400000000000000000000034471452621411600220520ustar00rootroot00000000000000from aiohttp import web from aiohttp_session import SimpleCookieStorage, setup as setup_session from sqlalchemy.ext.asyncio import (AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine) from aiohttp_security import SessionIdentityPolicy from aiohttp_security import setup as setup_security from .db import Base, Permission, User from .db_auth import DBAuthorizationPolicy from .handlers import Web async def init_db(db_engine: AsyncEngine, db_session: async_sessionmaker[AsyncSession]) -> None: """Initialise DB with sample data.""" async with db_engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async with db_session.begin() as sess: pw = "$5$rounds=535000$2kqN9fxCY6Xt5/pi$tVnh0xX87g/IsnOSuorZG608CZDFbWIWBr58ay6S4pD" sess.add(User(username="admin", password=pw, is_superuser=True)) moderator = User(username="moderator", password=pw) user = User(username="user", password=pw) sess.add(moderator) sess.add(user) async with db_session.begin() as sess: sess.add(Permission(user_id=moderator.id, name="protected")) sess.add(Permission(user_id=moderator.id, name="public")) sess.add(Permission(user_id=user.id, name="public")) async def init_app() -> web.Application: app = web.Application() db_engine = create_async_engine("sqlite+aiosqlite:///:memory:") app["db_session"] = async_sessionmaker(db_engine, expire_on_commit=False) await init_db(db_engine, app["db_session"]) setup_session(app, SimpleCookieStorage()) setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy(app["db_session"])) web_handlers = Web() web_handlers.configure(app) return app if __name__ == "__main__": web.run_app(init_app()) aiohttp-security-0.5.0/demo/dictionary_auth/000077500000000000000000000000001452621411600211455ustar00rootroot00000000000000aiohttp-security-0.5.0/demo/dictionary_auth/__init__.py000066400000000000000000000000001452621411600232440ustar00rootroot00000000000000aiohttp-security-0.5.0/demo/dictionary_auth/authz.py000066400000000000000000000024711452621411600226560ustar00rootroot00000000000000from enum import Enum from typing import Mapping, Optional, Union from aiohttp_security.abc import AbstractAuthorizationPolicy from .users import User class DictionaryAuthorizationPolicy(AbstractAuthorizationPolicy): def __init__(self, user_map: Mapping[Optional[str], User]): super().__init__() self.user_map = user_map async def authorized_userid(self, identity: str) -> Optional[str]: """Retrieve authorized user id. Return the user_id of the user identified by the identity or 'None' if no user exists related to the identity. """ return identity if identity in self.user_map else None async def permits(self, identity: Optional[str], permission: Union[str, Enum], context: None = None) -> bool: """Check user permissions. Return True if the identity is allowed the permission in the current context, else return False. """ user = self.user_map.get(identity) if not user: return False return permission in user.permissions async def check_credentials(user_map: Mapping[Optional[str], User], username: str, password: str) -> bool: user = user_map.get(username) if not user: return False return user.password == password aiohttp-security-0.5.0/demo/dictionary_auth/handlers.py000066400000000000000000000055451452621411600233300ustar00rootroot00000000000000from textwrap import dedent from typing import Dict, NoReturn, Optional from aiohttp import web from aiohttp_security import (authorized_userid, check_authorized, check_permission, forget, remember) from .authz import check_credentials from .users import User index_template = dedent("""

{message}

Login: Password:
Logout """) async def index(request: web.Request) -> web.Response: username = await authorized_userid(request) if username: template = index_template.format( message='Hello, {username}!'.format(username=username)) else: template = index_template.format(message='You need to login') return web.Response( text=template, content_type='text/html', ) async def login(request: web.Request) -> NoReturn: user_map: Dict[Optional[str], User] = request.app["user_map"] invalid_response = web.HTTPUnauthorized(body="Invalid username / password combination") form = await request.post() username = form.get('username') password = form.get('password') if not (isinstance(username, str) and isinstance(password, str)): raise invalid_response verified = await check_credentials(user_map, username, password) if verified: response = web.HTTPFound("/") await remember(request, response, username) raise response raise invalid_response async def logout(request: web.Request) -> web.Response: await check_authorized(request) response = web.Response( text='You have been logged out', content_type='text/html', ) await forget(request, response) return response async def internal_page(request: web.Request) -> web.Response: await check_permission(request, 'public') response = web.Response( text='This page is visible for all registered users', content_type='text/html', ) return response async def protected_page(request: web.Request) -> web.Response: await check_permission(request, 'protected') response = web.Response( text='You are on protected page', content_type='text/html', ) return response def configure_handlers(app: web.Application) -> None: router = app.router router.add_get('/', index, name='index') router.add_post('/login', login, name='login') router.add_get('/logout', logout, name='logout') router.add_get('/public', internal_page, name='public') router.add_get('/protected', protected_page, name='protected') aiohttp-security-0.5.0/demo/dictionary_auth/main.py000066400000000000000000000017461452621411600224530ustar00rootroot00000000000000import base64 from aiohttp import web from aiohttp_session import setup as setup_session from aiohttp_session.cookie_storage import EncryptedCookieStorage from cryptography import fernet from aiohttp_security import SessionIdentityPolicy from aiohttp_security import setup as setup_security from .authz import DictionaryAuthorizationPolicy from .handlers import configure_handlers from .users import user_map def make_app() -> web.Application: app = web.Application() app["user_map"] = user_map configure_handlers(app) # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) storage = EncryptedCookieStorage(secret_key, cookie_name='API_SESSION') setup_session(app, storage) policy = SessionIdentityPolicy() setup_security(app, policy, DictionaryAuthorizationPolicy(user_map)) return app if __name__ == '__main__': web.run_app(make_app(), port=9000) aiohttp-security-0.5.0/demo/dictionary_auth/users.py000066400000000000000000000005301452621411600226560ustar00rootroot00000000000000from typing import Dict, NamedTuple, Optional, Tuple class User(NamedTuple): username: str password: str permissions: Tuple[str, ...] user_map: Dict[Optional[str], User] = { user.username: user for user in [ User('devin', 'password', ('public',)), User('jack', 'password', ('public', 'protected',)), ] } aiohttp-security-0.5.0/demo/simple_example_auth.py000066400000000000000000000064541452621411600223670ustar00rootroot00000000000000from enum import Enum from typing import NoReturn, Optional, Union from aiohttp import web from aiohttp_session import SimpleCookieStorage, session_middleware from aiohttp_security import (SessionIdentityPolicy, check_permission, forget, is_anonymous, remember, setup as setup_security) from aiohttp_security.abc import AbstractAuthorizationPolicy # Demo authorization policy for only one user. # User 'jack' has only 'listen' permission. # For more complicated authorization policies see examples # in the 'demo' directory. class SimpleJack_AuthorizationPolicy(AbstractAuthorizationPolicy): async def authorized_userid(self, identity: str) -> Optional[str]: """Retrieve authorized user id. Return the user_id of the user identified by the identity or 'None' if no user exists related to the identity. """ return identity if identity == "jack" else None async def permits(self, identity: Optional[str], permission: Union[str, Enum], context: None = None) -> bool: """Check user permissions. Return True if the identity is allowed the permission in the current context, else return False. """ return identity == 'jack' and permission in ('listen',) async def handler_root(request: web.Request) -> web.Response: tmpl = """ Hello, I'm Jack, I'm {} logged in.

Log me in
Log me out

Check my permissions, when I'm logged in and logged out.
Can I listen?
Can I speak?
""" is_logged = not await is_anonymous(request) return web.Response(text=tmpl.format("" if is_logged else "NOT"), content_type="text/html") async def handler_login_jack(request: web.Request) -> NoReturn: redirect_response = web.HTTPFound('/') await remember(request, redirect_response, 'jack') raise redirect_response async def handler_logout(request: web.Request) -> NoReturn: redirect_response = web.HTTPFound('/') await forget(request, redirect_response) raise redirect_response async def handler_listen(request: web.Request) -> web.Response: await check_permission(request, 'listen') return web.Response(body="I can listen!") async def handler_speak(request: web.Request) -> web.Response: await check_permission(request, 'speak') return web.Response(body="I can speak!") async def make_app() -> web.Application: # # WARNING!!! # Never use SimpleCookieStorage on production!!! # It’s highly insecure!!! # # make app middleware = session_middleware(SimpleCookieStorage()) app = web.Application(middlewares=[middleware]) # add the routes app.router.add_route('GET', '/', handler_root) app.router.add_route('GET', '/login', handler_login_jack) app.router.add_route('GET', '/logout', handler_logout) app.router.add_route('GET', '/listen', handler_listen) app.router.add_route('GET', '/speak', handler_speak) # set up policies policy = SessionIdentityPolicy() setup_security(app, policy, SimpleJack_AuthorizationPolicy()) return app if __name__ == '__main__': web.run_app(make_app(), port=9000) aiohttp-security-0.5.0/docs/000077500000000000000000000000001452621411600157635ustar00rootroot00000000000000aiohttp-security-0.5.0/docs/Makefile000066400000000000000000000164311452621411600174300ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(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/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aiohttp_security.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aiohttp_security.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/aiohttp_security" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aiohttp_security" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." aiohttp-security-0.5.0/docs/_static/000077500000000000000000000000001452621411600174115ustar00rootroot00000000000000aiohttp-security-0.5.0/docs/_static/aiohttp-icon-128x128.png000066400000000000000000000425241452621411600234570ustar00rootroot00000000000000PNG  IHDRL\gAMA a cHRMz&u0`:pQ<bKGD pHYs  tIME `)b'DCIDATx\u';yߎI"%j%QeYѶ퉘pḊ{1n.w˖i .A_w3֭[D-=37nUw9Y$13;9ʏhϿu&ZN_gЯ (hcLeG YUQ_J)pY3`Zkc1!(~,XX\1O)k‰_%1Zky/5ͅރw/?3,<!TU՜vXux6s-&c52۝`& ̙?sz.7 Տ4G Tk\`F?#]l6-۬wnW|YJQ2f9}7^7O>(p8 l6f S)km&iۛIaƄ}\2߾Ƨ?{}x\A9%6J9V̟4m*EC,ZV6lO=HlCZ4\{Q; Θ| ֠oLeC;vUZLGS/=[[[ &w/ySM։c]f}aXzd5qgK7B&X&|$!s\\_ߘd- aRKKKOVJxj5w| "_#|}?3ۻo0D4#nw^=@RPe3t=dغ򚉻=ϫjN+XkI}`0m~?!)`(@HX_'/8ra|W}sVka0=N9E6eXF+[v!%@ k쟓bc`ة39?[ߌ+SE?c$߽Aw/_VKVꓸ b` 0YonVI֖}STV|~ 8t7[̓ h16jǎԾ/, 8DB Os?o\յUlcj~Kd-[m$Qօ3{Rܽy٫?M(vHMjT9{]BVf6$=4I:T(zu\VH^[:qWh}٭j̜$+"u'I4Mgggˋ{76"HVEBwкFoR֤@^?r0_~d.Mo8?Q}}3G uJ:WJ$O>r{|·)յN66[f/~7ޢuv/[k{pzqѻIW>ZīoG[J#CYz|дH}!2+W"1kgYUBJ"pG0C p]'4 d х>|ʕK^l;1v/^=yƯ4tB*_{oJI2}k,KNQRXJy˘K)UVyUtdpGX'q#]*o{CQ=+Euo5Oz.])OR*g@Y)_W*0)eQj*u{ݷ>|!Ųª ss8Mꙕ;ed9h/٫?&/İ~ σ*zWͲ1Bk磵.~wEdߴ~W]: 5?f=qkva$.C?3hd#8{/ a6\A8'aҝZ(ͳgG޽aEp{H1%7o|Jv2F5t`ȠÛ [ R^bkFqt/"T5źϬY_YypZ]d61{3BCTD[v,ϘuLб2ljYZ'IRGĚ})-TMM.$P ]a pcGԁ@ɒ$xa.;N6'r Sc{9ߵs7kNfW!)*2'*"9Α߀􍵽^Է5ݾU[ 2ru[m\oT>|v- vj P@gnfA(Bax^ ?P e|s /DĪ x~m_ QXTw *9u۬2UTX ōxND#$cޓf} (MS~+zK{Vȶq);I.LjfUjfA$Q 0X) 8r^vP 0ԓLv! !Y(Sg6yEVuhPajD ,v!ȐM@xv$VRWd}6""9_#a)Dda:)&n4]1sD jk%DiI/YCi"%L _AjmD;2*VxqfΡ?#lZznm[+us]Ymʾ2++Q(d-.B cz7-ҥ6_Ø=8o+z;YPsӞ8Nng f6EH ᪉ ժU>fQ J@"&R;vynn*tk UuB1P6lwp _5lnacWVUenӔZU;%8y&U.Elӗ*38}wʋh 3 GޏhmS0wP56=2$hP<.c4A!*8`e%i%Qm 7=)_<t$ӷ/ot{ȲIŒ87핫7V=ix8f& S6Lz+:W+/!DS Pv=mҋ^(Vw=_&U͝MҫazY&VUo\2$\R .TA遳\Tlm?\㙨0?5O~Cv:zvLD:H, l00̝{'hJir Xk+' @&6ixu) 8 *`6/T k,_E8 BA|<"r=H߇veOK UA>`b !|lj8fp{_s7}?˲ &Ou w=t) \_Q8&tH=򘟟}}@xaY\(VէE2&"X57AKc$S Sc!MpF % w{ׄ 1|T..҄dh[w0."+\Mg.FelUzXCGwָwKfX0-=d_?X !М'OPh٦æ0uB;R؝/T,5U4iz* %MB2`1b>/2][P8%ΓQn֫tU&%\8N6l3l"'Yo ^}fj$%uqbZ9Fv:@4y%hM &3L wD) <㕗XJDJ)&UP1+\zxk0CG{<]`^|m8YxQϞ=e17 oZm.q#!.G^6-\6)Iͥ9?p EYfH `-HFqV{WW*VCGeC` ؓtg["*T9pΖD.&|&@Uy,-}W_t+%=@Dm A#XM";?m"w_a 6yO!}V f=`"GuRdCዢ.|?4oWٚM ]zZr-"J7)y^ߟ_H21:]Ll_/̿!HPo%7ڡ>uڙ-H XI )OPAN,f;>@&c!$,%H`cuĭ[w )-7^La.%۔u 76up +dڛ82P/Z[a٤z|E>"Ӥ#dRc;Q,鹇]7\vkcAimu9Bx I#,Դ&ᑜӕIc*PUːg$ ^A 2YosګFUgS;dijb HG.T.˓m]`:4nm۶wC L&!AGByߟ<._ǙLOG[»P@lwҡu8CFel@UfnՈfX_RHӯUwЙӏRc\H:"M2X i{7LV""+lgEV`HOqTlz#.]SO+7}+2L6A?yDƖ@p((al6DMfӁ jDٷ̫k?SgIA:~[՛7N_WD JQ&M]0@J:D4ZtyK%F~F[0َ ,/V@y!JQ0aB«x-}ov~N̰D\%۵HޑW &X)*. !P[[" $M Hݳdgǜ0 xP(,#Mٴ' ج~3J>J-$$5k%!C[n]"&x8O T~nמ9O~Td=Kiր@$M`h/!9B1Y-Z!d$v jw:l$5$< HQ8"F*Nʋ92Mld ::x[Gz&ڲ6tD" ̩g q_tgEz cJzt1 b Z&#"w sɯI4"ǰuӥW0 7՟aVkQAHI"95b*bW.q3@Y^… :1@^6ƨGl`5ظ\&[T˴{cɒ$XVcU^՚C:Q8ۛ"HR0|f󧑴{l1` cxޅ|za5nB03߀ 0X)'hn 9H5NpKJcnjrSXD854Ho[cͤ8#3\eum/x0VK<)O40{k/#L -ʸ 'M9iXۨ)l!<-s`3baZ¬)y;n5 lm«Sai`"Xp|*MʃU \_::PnUïB(up[^={nSpM6]2kl̴[½IsH/f fKlǓb.a&0&)eJ'[Ia3h&cl^ҥR 3;:5Ey'D46_(R!3CV9@Uk?1dTt3 uiޠ!Z7sȕv >*{uZǩy ~6RЇ>_[.6*9Ĥ{]LO,dV636c')nCgwgfJ$zînq 6`ehxѲ;t@DqX8eYIhv94Q[gM079FMۤ*W3ڕ6l;51 !ܧ&$QnJm5qQ$Mϣ bl:6?s`Lbd[pɬ_0j4*3 Gu\ʻj|%8&ʊ$ep4i2 HuO) .S J^u$j}\_yq4C&kStFp ͲK"okjBn}3HPh>NcU{H,(m>/adRT/Dx=rT8`{W5ȉd%etk2@ 3(-a@Vv rUgAKԚnCɐ֎89b>rG]2@(TK3'š&گB &Z ל4ei\%2ZyT4.=ᱢ3~?bRPeȒmQڛy]VBeSE+$ =f6mHtkɫæ,})ۘ^c# \_Ͳl: LYv4o7 &T 0z̦ b Kn[a mz܂qNhG̽Kb`M2'!{ƍwxA8gtk:AnyM~2.^۲W\5%K幝 -%6]Aި4YL4|žkN ]ܠ#bafTI[Bxa͔9 md̼o`mqq_Cy>OFJեU^~wי1D\xLඩf""~s}stL2kYgq&gkG>W$3rOD^on.w`j*$Z|J,1(/^[M/OVLf|3~"G'Q{G~6cz7^#d7氙:* y-1kT[ĉV?̟(~z9X} "vV+ Y; M(f lNcJc*dƴ/+<ƆGa="GJ>gbo£|oq է~|vscH0T4/l^T*<aQl̺֒ 5Z,fBfmv*B zV~y˩&_۴:Ю H{N?35,Tz$Yثꤝ8,VWמFsu&imZ8Ǽ|4y Hx8t2YR5. fbn{6%Qͩ:#}2s,nW֩{ AFAn*1 ĝ[6r*°ft.R!=)4=i$K0m߽ $fN_|c͛jhT34{Ee)wZ^i˜BA g lCf$rqg Ewf@a0Zw: QX\Uwp"}&$O(}mXM0!XIDq Md5_qt˄()t Iҧ%h^M8\xGCSʫ6@n8DfM;D@183uH-w`{{^-h>=gfӞ՚ᴋxLDbXgv!Ƅ6L+ ! TWEȝK9\FN"\.huvM: "Ԫ<ZkvwWxWTvyՓ4xVڞI&ȋ Zh %OEc15A$C*TTFn+`ȐdF֖覑ѼI >c6v T9I"ă]=GCӱ~]~+R}ǃr~qX\|HHB b@'w\v⺶RzHlXpV^mnn:q_UUkzZCCaTl۝Nhܽ (,]3EIHݹ&I7uq`if&6c5SB$eN.:؂dEQʹ,zbhT9׹wY&鱛4 0 |5sX‘eYݮjJ.=n EDk/vN(=y=K'fΉu聭dfeЎF%KyK< ++YM[Vo`8q fMF/j5u `<h k3)雓۞23a~~zĂv/*Mx 2dijb0T>csz Ɵ9,ݥ]msz7AÐWgd`Un)pQsTCz bV) 8P_gcd`R%kzDDF8YA떥gDmkXIifYjf_?q[EbA^O4iUP[~ *+Ԥt$0yoAF"&\#$(/GF 3i -*j7sL}Ͳ3E\T]wMcTmɟ?bfC6pޮ|DDéBwpHve @9̚K% U'4n{n8~^8qDx~Hڒf`MGSA$ !d k0 `` nS*H6Y ]YF^3j7YxZk-U)9#T*ǎ+婠Q>.N:u2r$Ʉ: 7s.i(BPm"3j gS qugp}TnD2Vɬi ?woS;%y\qyy̙3EGׯf8xc=vƍmZ眕T^o4zD:eAImV '` Q@p3M5(\*3RMT>B G=~u?xT*}c׮]{8.f;,ҫJbI:&beÛbף[Lg`ޥ? 3XG9&oɷ&j"QጐrgiZ%ԗ?3)w+c?Q NQ-(}5*j+&۸l*`N‡.\}y**_ahYƶ%6 l8X6jpFut\Y⥔ROVt)Gji_G܆+-8(.:ןDZ+8~:_-0R%Ilx8EAF9 Tt ijR⅋YvǯeE\S:"Ǖ„2}YT5< Fyqf]cEjpZ6WN_/Nc;?23&~]lfuLGJN-Qg I9 B%tEXtdate:create2018-10-06T17:06:59+00:00%tEXtdate:modify2018-10-06T17:06:59+00:00OIENDB`aiohttp-security-0.5.0/docs/aiohttp-icon.ico000066400000000000000000000060441452621411600210610ustar00rootroot00000000000000 & 5PNG  IHDRIDATHTAKA}٤ĤʶXR#Ţ)d//ԃ ^Z(()YH,Ԣ PM ,.15DcM>v~3 %*^/Hxӹ1V|khhu}}=87|>E"jfJ((fWWW599]GG/"#"[aC`FQ,~8Nuuu糙!Iޟ;*\N1lmm #w3Ab&\0 8<8w3/l6٬pl4qvr?rcO Ȳ|OW hjj]K`Q2|hd2/DRKnrALɕ z<xE$c"UUgYL~X( o;`ppP3Yځa<$I0@D6UUVj- yA>MOOW\: jb:P,W/:_XfQq )m(^cWUUu@DY*Bmm)iiiI.k㨥e!Ty@*tIENDB`PNG  IHDR szzIDATXY^Uk}owR2<9D`|Иh/>1F} M|$&`BH1A@ H2Rzo8^>RP~Y{Y-QU R{""g"99~{vMlk+b<y,K<'":=~z'E!EJJu ;j4Zy;4M<ђd}T,x#!2u9mF 瑏_J|wQ[, 0C%Ck!b (-%K?}DQD$ IZ?GGj-O~bk0ZA[-0MQ Q ?DEdY!(˒(`o .41܆e)Lm09)Z 9k-ƘS}Aq71~hAD@Um>߁lEYw s) H#3 j{hD'CPA1xAz>D5( tvcT B>d˨ pͭy!o Vܖq ~SII )4l5&n iPԳH^O`Z(x'!I9F? U37 w嘅g= ::(*HWA@4@ZP )^}t֡!:Ge2'( \ .96ꓸt\.AG _v;`!Eg <[fYF\`+F.{ 7!Wh} 6q*:v4&^t>5@#ھ܊ Q!>9FtYdItb-Z, ݔ22Z* {@UjSdo;;XJ&tڂiMD?Fԡ;>,XC? q`Hx6yE6zQaiq_$!B|EBJr(&nN9c <")JȈ_eVWiZ'EDt:,//SFtCCTxud0LQTR0IDQe}``0`zz00>s1ڝEEin-imBb& wW_ʫ1C@---1>1Ih7~=Ra˕>6Az'Me֛ϾL-kLLLvMLUv$IBklZf)C_&N$lM_E8~!QF0 ;n ~~΂!V\9yQ9eYh4'J` qP32 a i,IENDB`aiohttp-security-0.5.0/docs/aiohttp_doctools.py000066400000000000000000000015611452621411600217160ustar00rootroot00000000000000from sphinx import addnodes from sphinx.domains.python import PyClassmember, PyModulelevel class PyCoroutineMixin(object): def handle_signature(self, sig, signode): ret = super(PyCoroutineMixin, self).handle_signature(sig, signode) signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine ')) return ret class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel): def run(self): self.name = 'py:function' return PyModulelevel.run(self) class PyCoroutineMethod(PyCoroutineMixin, PyClassmember): def run(self): self.name = 'py:method' return PyClassmember.run(self) def setup(app): app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction) app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod) return {'version': '1.0', 'parallel_read_safe': True} aiohttp-security-0.5.0/docs/conf.py000066400000000000000000000255611452621411600172730ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # aiohttp_security documentation build configuration file, created by # sphinx-quickstart on Tue Apr 14 11:54:09 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import codecs import os import re import sys _docs_path = os.path.dirname(__file__) _version_path = os.path.abspath(os.path.join(_docs_path, '..', 'aiohttp_security', '__init__.py')) with codecs.open(_version_path, 'r', 'latin1') as fp: try: _version_info = re.search(r"^__version__ = '" r"(?P\d+)" r"\.(?P\d+)" r"\.(?P\d+)" r"(?P.*)?'$", fp.read(), re.M).groupdict() except IndexError: raise RuntimeError('Unable to determine version.') # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'alabaster', 'aiohttp_doctools', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'aiohttp_security' copyright = '2015-2016 Andrew Svetlov' author = 'Andrew Svetlov' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '{major}.{minor}'.format(**_version_info) # The full version, including alpha/beta/rc tags. release = '{major}.{minor}.{patch}-{tag}'.format(**_version_info) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'logo': 'aiohttp-icon-128x128.png', 'description': 'Authorization and identity for aoihttp', 'github_user': 'aio-libs', 'github_repo': 'aiohttp-security', 'github_button': True, 'github_type': 'star', 'github_banner': True, 'travis_button': True, 'codecov_button': True, 'pre_bg': '#FFF6E5', 'note_bg': '#E5ECD1', 'note_border': '#BFCF8C', 'body_text': '#482C0A', 'sidebar_text': '#49443E', 'sidebar_header': '#4B4032', } # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [alabaster.get_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'aiohttp-icon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', ] } # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'aiohttp_securitydoc' # -- Options for LaTeX output --------------------------------------------- # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', # Latex figure (float) alignment # 'figure_align': 'htbp', latex_elements = { } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'aiohttp_security.tex', 'aiohttp\\_security Documentation', 'Andrew Svetlov', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'aiohttp_security', 'aiohttp_security Documentation', [author], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'aiohttp_security', 'aiohttp_security Documentation', author, 'aiohttp_security', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/3': None, 'http://aiohttp.readthedocs.org/en/stable': None} aiohttp-security-0.5.0/docs/example.rst000066400000000000000000000067121452621411600201560ustar00rootroot00000000000000.. _aiohttp-security-example: =============================================== How to Make a Simple Server With Authorization =============================================== Simple example:: from aiohttp import web from aiohttp_session import SimpleCookieStorage, session_middleware from aiohttp_security import check_permission, \ is_anonymous, remember, forget, \ setup as setup_security, SessionIdentityPolicy from aiohttp_security.abc import AbstractAuthorizationPolicy # Demo authorization policy for only one user. # User 'jack' has only 'listen' permission. # For more complicated authorization policies see examples # in the 'demo' directory. class SimpleJack_AuthorizationPolicy(AbstractAuthorizationPolicy): async def authorized_userid(self, identity): """Retrieve authorized user id. Return the user_id of the user identified by the identity or 'None' if no user exists related to the identity. """ if identity == 'jack': return identity async def permits(self, identity, permission, context=None): """Check user permissions. Return True if the identity is allowed the permission in the current context, else return False. """ return identity == 'jack' and permission in ('listen',) async def handler_root(request): is_logged = not await is_anonymous(request) return web.Response(text=''' Hello, I'm Jack, I'm {logged} logged in.

Log me in
Log me out

Check my permissions, when i'm logged in and logged out.
Can I listen?
Can I speak?
'''.format( logged='' if is_logged else 'NOT', ), content_type='text/html') async def handler_login_jack(request): redirect_response = web.HTTPFound('/') await remember(request, redirect_response, 'jack') raise redirect_response async def handler_logout(request): redirect_response = web.HTTPFound('/') await forget(request, redirect_response) raise redirect_response async def handler_listen(request): await check_permission(request, 'listen') return web.Response(body="I can listen!") async def handler_speak(request): await check_permission(request, 'speak') return web.Response(body="I can speak!") async def make_app(): # # WARNING!!! # Never use SimpleCookieStorage on production!!! # It’s highly insecure!!! # # make app middleware = session_middleware(SimpleCookieStorage()) app = web.Application(middlewares=[middleware]) # add the routes app.add_routes([ web.get('/', handler_root), web.get('/login', handler_login_jack), web.get('/logout', handler_logout), web.get('/listen', handler_listen), web.get('/speak', handler_speak)]) # set up policies policy = SessionIdentityPolicy() setup_security(app, policy, SimpleJack_AuthorizationPolicy()) return app if __name__ == '__main__': web.run_app(make_app(), port=9000) aiohttp-security-0.5.0/docs/example_db_auth.rst000066400000000000000000000071551452621411600216460ustar00rootroot00000000000000.. _aiohttp-security-example-db-auth: ======================================= Permissions with database-based storage ======================================= We use :class:`~aiohttp_session.SimpleCookieStorage` and an in-memory SQLite DB to make it easy to try out the demo. When developing an application, you should use :class:`~aiohttp_session.cookie_storage.EncryptedCookieStorage` or :class:`~aiohttp_session.redis_storage.RedisStorage` and a production-ready database. If you want the full source code in advance or for comparison, check out the `demo source`_. .. _demo source: https://github.com/aio-libs/aiohttp_security/tree/master/demo .. _passlib: https://passlib.readthedocs.io Database -------- When the application runs, we initialise the DB with sample data using SQLAlchemy ORM: .. literalinclude:: ../demo/database_auth/main.py :pyobject: init_db This will consist of 2 tables/models created in ``db.py``: Users: .. literalinclude:: ../demo/database_auth/db.py :pyobject: User And their permissions: .. literalinclude:: ../demo/database_auth/db.py :pyobject: Permission Writing policies ---------------- You need to implement two entities: :class:`IdentityPolicy` and :class:`AuthorizationPolicy`. First one should have these methods: :class:`~aiohttp_security.AbstractIdentityPolicy.identify`, :class:`~aiohttp_security.AbstractIdentityPolicy.remember` and :class:`~aiohttp_security.AbstractIdentityPolicy.forget`. For the second one: :class:`~aiohttp_security.AbstractAuthorizationPolicy.authorized_userid` and :class:`~aiohttp_security.AbstractAuthorizationPolicy.permits`. We will use the included :class:`~aiohttp_security.SessionIdentityPolicy` and write our own database-based authorization policy. In our example we will lookup a user login in the database and, if present, return the identity. .. literalinclude:: ../demo/database_auth/db_auth.py :pyobject: DBAuthorizationPolicy.authorized_userid For permission checking, we will fetch the user first, check if he is superuser (all permissions are allowed), otherwise check if the permission is explicitly set for that user. .. literalinclude:: ../demo/database_auth/db_auth.py :pyobject: DBAuthorizationPolicy.permits Setup ----- Once we have all the code in place we can install it for our application: .. literalinclude:: ../demo/database_auth/main.py :pyobject: init_app Now we have authorization and can decorate every other view with access rights based on permissions. There are two helpers included for this:: from aiohttp_security import check_authorized, check_permission For each view you need to protect - just apply the decorator on it. .. literalinclude:: ../demo/database_auth/handlers.py :pyobject: Web.protected_page or .. literalinclude:: ../demo/database_auth/handlers.py :pyobject: Web.logout If someone tries to access that protected page he will see:: 403: Forbidden The best part of it - you can implement any logic you want following the API conventions. Launch application ------------------ For working with passwords there is a good library passlib_. Once you've created some users you want to check their credentials on login. A similar function may do what you are trying to accomplish:: from passlib.hash import sha256_crypt .. literalinclude:: ../demo/database_auth/db_auth.py :pyobject: check_credentials Final step is to launch your application:: python -m database_auth Try to login with admin/moderator/user accounts (with **password** password) and access **/public** or **/protected** endpoints. aiohttp-security-0.5.0/docs/glossary.rst000066400000000000000000000032201452621411600203550ustar00rootroot00000000000000.. _aiohttp-security-glossary: ========== Glossary ========== .. if you add new entries, keep the alphabetical sorting! .. glossary:: aiohttp :term:`asyncio` based library for making web servers. asyncio The library for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers, and other related primitives. Reference implementation of :pep:`3156` https://pypi.python.org/pypi/asyncio/ authentication Actions related to retrieving, storing and removing user's :term:`identity`. Authenticated user has no access rights, the system even has no knowledge is there the user still registered in DB. If :class:`~aiohttp.web.Request` has an :term:`identity` it means the user has some ID that should be checked by :term:`authorization` policy. authorization Checking actual permissions for identified user along with getting :term:`userid`. identity Session-wide :class:`str` for identifying user. Stored in local storage (client-side cookie or server-side storage). Use :meth:`~aiohttp_session.remember` for saving *identity* (sign in) and :meth:`~aiohttp_session.forget` for dropping it (sign out). *identity* is used for getting :term:`userid` and :term:`permission`. permission Permission required for access to resource. Permissions are just strings, and they have no required composition: you can name permissions whatever you like. userid User's ID, most likely his *login* or *email* aiohttp-security-0.5.0/docs/index.rst000066400000000000000000000006441452621411600176300ustar00rootroot00000000000000aiohttp_security ================ The library provides security for :ref:`aiohttp.web`. The current version is |version| Contents -------- .. toctree:: :maxdepth: 2 usage reference example example_db_auth glossary License ------- ``aiohttp_security`` is offered under the Apache 2 license. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` aiohttp-security-0.5.0/docs/make.bat000066400000000000000000000161401452621411600173720ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\aiohttp_security.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\aiohttp_security.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end aiohttp-security-0.5.0/docs/reference.rst000066400000000000000000000164541452621411600204650ustar00rootroot00000000000000.. _aiohttp-security-reference: =========== Reference =========== .. module:: aiohttp_security .. currentmodule:: aiohttp_security .. highlight:: python Public API functions ==================== .. function:: setup(app, identity_policy, autz_policy) Setup :mod:`aiohttp` application with security policies. :param app: aiohttp :class:`aiohttp.web.Application` instance. :param identity_policy: indentification policy, an :class:`AbstractIdentityPolicy` instance. :param autz_policy: authorization policy, an :class:`AbstractAuthorizationPolicy` instance. .. coroutinefunction:: remember(request, response, identity, **kwargs) Remember *identity* in *response*, e.g. by storing a cookie or saving info into session. The action is performed by registered :meth:`AbstractIdentityPolicy.remember`. Usually the *identity* is stored in user cookies somehow for using by :func:`authorized_userid` and :func:`permits`. :param request: :class:`aiohttp.web.Request` object. :param response: :class:`aiohttp.web.StreamResponse` and descendants like :class:`aiohttp.web.Response`. :param str identity: :class:`aiohttp.web.Request` object. :param kwargs: additional arguments passed to :meth:`AbstractIdentityPolicy.remember`. They are policy-specific and may be used, e.g. for specifiying cookie lifetime. .. coroutinefunction:: forget(request, response) Forget previously remembered :term:`identity`. The action is performed by registered :meth:`AbstractIdentityPolicy.forget`. :param request: :class:`aiohttp.web.Request` object. :param response: :class:`aiohttp.web.StreamResponse` and descendants like :class:`aiohttp.web.Response`. .. coroutinefunction:: check_authorized(request) Checker that doesn't pass if user is not authorized by *request*. :param request: :class:`aiohttp.web.Request` object. :return str: authorized user ID if success :raise: :class:`aiohttp.web.HTTPUnauthorized` for anonymous users. Usage:: async def handler(request): await check_authorized(request) # this line is never executed for anonymous users .. coroutinefunction:: check_permission(request, permission) Checker that doesn't pass if user has no requested permission. :param request: :class:`aiohttp.web.Request` object. :raise: :class:`aiohttp.web.HTTPUnauthorized` for anonymous users. :raise: :class:`aiohttp.web.HTTPForbidden` if user is authorized but has no access rights. Usage:: async def handler(request): await check_permission(request, 'read') # this line is never executed if a user has no read permission .. coroutinefunction:: authorized_userid(request) Retrieve :term:`userid`. The user should be registered by :func:`remember` before the call. :param request: :class:`aiohttp.web.Request` object. :return: :class:`str` :term:`userid` or ``None`` for session without signed in user. .. coroutinefunction:: permits(request, permission, context=None) Check user's permission. Return ``True`` if user remembered in *request* has specified *permission*. Allowed permissions as well as *context* meaning are depends on :class:`AbstractAuthorizationPolicy` implementation. Actually it's a wrapper around :meth:`AbstractAuthorizationPolicy.permits` coroutine. The user should be registered by :func:`remember` before the call. :param request: :class:`aiohttp.web.Request` object. :param permission: Requested :term:`permission`. :class:`str` or :class:`enum.Enum` object. :param context: additional object may be passed into :meth:`AbstractAuthorizationPolicy.permission` coroutine. :return: ``True`` if registered user has requested *permission*, ``False`` otherwise. .. coroutinefunction:: is_anonymous(request) Checks if user is anonymous user. Return ``True`` if user is not remembered in request, otherwise returns ``False``. :param request: :class:`aiohttp.web.Request` object. Abstract policies ================= *aiohttp_security* is built on top of two *abstract policies* -- :class:`AbstractIdentityPolicy` and :class:`AbstractAuthorizationPolicy`. The first one responds on remembering, retrieving and forgetting :term:`identity` into some session storage, e.g. HTTP cookie or authorization token. The second is responsible to return persistent :term:`userid` for session-wide :term:`identity` and check user's permissions. Most likely sofware developer reuses one of pre-implemented *identity policies* from *aiohttp_security* but build *authorization policy* from scratch for every application/project. Identification policy --------------------- .. class:: AbstractIdentityPolicy .. coroutinemethod:: identify(request) Extract :term:`identity` from *request*. Abstract method, should be overriden by descendant. :param request: :class:`aiohttp.web.Request` object. :return: the claimed identity of the user associated request or ``None`` if no identity can be found associated with the request. .. coroutinemethod:: remember(request, response, identity, **kwargs) Remember *identity*. May use *request* for accessing required data and *response* for storing *identity* (e.g. updating HTTP response cookies). *kwargs* may be used by concrete implementation for passing additional data. Abstract method, should be overriden by descendant. :param request: :class:`aiohttp.web.Request` object. :param response: :class:`aiohttp.web.StreamResponse` object or derivative. :param identity: :term:`identity` to store. :param kwargs: optional additional arguments. An individual identity policy and its consumers can decide on the composition and meaning of the parameter. .. coroutinemethod:: forget(request, response) Forget previously stored :term:`identity`. May use *request* for accessing required data and *response* for dropping *identity* (e.g. updating HTTP response cookies). Abstract method, should be overriden by descendant. :param request: :class:`aiohttp.web.Request` object. :param response: :class:`aiohttp.web.StreamResponse` object or derivative. Authorization policy --------------------- .. class:: AbstractAuthorizationPolicy .. coroutinemethod:: authorized_userid(identity) Retrieve authorized user id. Abstract method, should be overriden by descendant. :param identity: an :term:`identity` used for authorization. :return: the :term:`userid` of the user identified by the *identity* or ``None`` if no user exists related to the identity. .. coroutinemethod:: permits(identity, permission, context=None) Check user permissions. Abstract method, should be overriden by descendant. :param identity: an :term:`identity` used for authorization. :param permission: requested permission. The type of parameter is not fixed and depends on implementation. aiohttp-security-0.5.0/docs/usage.rst000066400000000000000000000121071452621411600176220ustar00rootroot00000000000000.. _aiohttp-security-usage: ======= Usage ======= .. currentmodule:: aiohttp_security .. highlight:: python First of all, what is *aiohttp_security* about? *aiohttp-security* is a set of public API functions as well as a reference standard for implementation details for securing access to assets served by a wsgi server. Assets are secured using authentication and authorization as explained below. *aiohttp-security* is part of the `aio-libs `_ project which takes advantage of asynchronous processing using Python's asyncio library. Public API ========== The API is agnostic to the low level implementation details such that all client code only needs to implement the endpoints as provided by the API (instead of calling policy code directly (see explanation below)). Via the API an application can: (i) remember a user in a local session (:func:`remember`), (ii) forget a user in a local session (:func:`forget`), (iii) retrieve the :term:`userid` (:func:`authorized_userid`) of a remembered user from an :term:`identity` (discussed below), and (iv) check the :term:`permission` of a remembered user (:func:`permits`). The library internals are built on top of two concepts: 1) :term:`authentication`, and 2) :term:`authorization`. There are abstract base classes for both types as well as several pre-built implementations that are shipped with the library. However, the end user is free to build their own implementations. The library comes with two pre-built identity policies; one that uses cookies, and one that uses sessions [#f1]_. It is envisioned that in most use cases developers will use one of the provided identity policies (Cookie or Session) and implement their own authorization policy. The workflow is as follows: 1) User is authenticated. This has to be implemented by the developer. 2) Once user is authenticated an identity string has to be created for that user. This has to be implemented by the developer. 3) The identity string is passed to the Identity Policy's remember method and the user is now remembered (Cookie or Session if using built-in). *Only once a user is remembered can the other API methods:* :func:`permits`, :func:`forget`, *and* :func:`authorized_userid` *be invoked* . 4) If the user tries to access a restricted asset the :func:`permits` method is called. Usually assets are protected using the :func:`check_permission` helper. This should return True if permission is granted. The :func:`permits` method is implemented by the developer as part of the :class:`AbstractAuthorizationPolicy` and passed to the application at runtime via setup. In addition a :func:`check_authorized` also exists that requires no permissions (i.e. doesn't call :func:`permits` method) but only requires that the user is remembered (i.e. authenticated/logged in). Authentication ============== Authentication is the process where a user's identity is verified. It confirms who the user is. This is traditionally done using a user name and password (note: this is not the only way). A authenticated user has no access rights, rather an authenticated user merely confirms that the user exists and that the user is who they say they are. In *aiohttp_security* the developer is responsible for their own authentication mechanism. *aiohttp_security* only requires that the authentication result in a identity string which corresponds to a user's id in the underlying system. .. note:: :term:`identity` is a string that is shared between the browser and the server. Therefore it is recommended that a random string such as a uuid or hash is used rather than things like a database primary key, user login/email, etc. Identity Policy =============== Once a user is authenticated the *aiohttp_security* API is invoked for storing, retrieving, and removing a user's :term:`identity`. This is accommplished via AbstractIdentityPolicy's :func:`remember`, :func:`identify`, and :func:`forget` methods. The Identity Policy is therefore the mechanism by which a authenticated user is persisted in the system. *aiohttp_security* has two built in identity policy's for this purpose. :class:`CookiesIdentityPolicy` that uses cookies and :class:`SessionIdentityPolicy` that uses sessions via ``aiohttp-session`` library. Authorization ============== Once a user is authenticated (see above) it means that the user has an :term:`identity`. This :term:`identity` can now be used for checking access rights or :term:`permission` using a :term:`authorization` policy. The authorization policy's :func:`permits()` method is used for this purpose. When :class:`aiohttp.web.Request` has an :term:`identity` it means the user has been authenticated and therefore has an :term:`identity` that can be checked by the :term:`authorization` policy. As noted above, :term:`identity` is a string that is shared between the browser and the server. Therefore it is recommended that a random string such as a uuid or hash is used rather than things like a database primary key, user login/email, etc. .. rubric:: Footnotes .. [#f1] jwt - json web tokens in the works aiohttp-security-0.5.0/requirements-dev.txt000066400000000000000000000003071452621411600210730ustar00rootroot00000000000000-r requirements.txt flake8==6.1.0 flake8-bandit==4.1.1 flake8-bugbear==23.9.16 flake8-import-order==0.18.2 flake8-requirements==2.0.1 mypy==1.7.0 types-passlib==1.7.7.13 pep257==0.7.0 sphinx==7.2.6 aiohttp-security-0.5.0/requirements.txt000066400000000000000000000003561452621411600203230ustar00rootroot00000000000000-e . aiohttp==3.9.0 aiohttp-session==2.12.0 async-timeout==4.0.3 coverage==7.3.2 cryptography==41.0.5 hiredis==2.2.3 passlib==1.7.4 pyjwt==2.8.0 pytest==7.4.3 pytest-aiohttp==1.0.5 pytest-cov==4.1.0 pytest-mock==3.12.0 sqlalchemy==2.0.23 aiohttp-security-0.5.0/setup.cfg000066400000000000000000000002201452621411600166460ustar00rootroot00000000000000[tool:pytest] testpaths = tests/ addopts = --cov=aiohttp_security --cov=tests asyncio_mode = auto xfail_strict = true filterwarnings= error aiohttp-security-0.5.0/setup.py000066400000000000000000000033161452621411600165500ustar00rootroot00000000000000import os import re from setuptools import find_packages, setup with open(os.path.join(os.path.abspath(os.path.dirname( __file__)), 'aiohttp_security', '__init__.py'), 'r', encoding='latin1') as fp: try: version = re.findall(r"^__version__ = '([^']+)'$", fp.read(), re.M)[0] except IndexError: raise RuntimeError('Unable to determine version.') def read(f): return open(os.path.join(os.path.dirname(__file__), f)).read().strip() install_requires = ["aiohttp>=3.9"] tests_require = install_requires + ['pytest'] extras_require = {'session': 'aiohttp-session'} setup(name='aiohttp-security', version=version, description=("security for aiohttp.web"), long_description='\n\n'.join((read("README.rst"), read("CHANGES.rst"))), long_description_content_type="text/x-rst", classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', '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", 'Topic :: Internet :: WWW/HTTP', 'Framework :: AsyncIO', ], author='Andrew Svetlov', author_email='andrew.svetlov@gmail.com', url='https://github.com/aio-libs/aiohttp_security/', license='Apache 2', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, include_package_data=True, extras_require=extras_require) aiohttp-security-0.5.0/tests/000077500000000000000000000000001452621411600161755ustar00rootroot00000000000000aiohttp-security-0.5.0/tests/__init__.py000066400000000000000000000000001452621411600202740ustar00rootroot00000000000000aiohttp-security-0.5.0/tests/conftest.py000066400000000000000000000000201452621411600203640ustar00rootroot00000000000000# nothing to do aiohttp-security-0.5.0/tests/test_cookies_identity.py000066400000000000000000000053621452621411600231610ustar00rootroot00000000000000from aiohttp import web from aiohttp_security import AbstractAuthorizationPolicy, forget, remember from aiohttp_security import setup as _setup from aiohttp_security.api import IDENTITY_KEY from aiohttp_security.cookies_identity import CookiesIdentityPolicy class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): pass async def authorized_userid(self, identity): pass async def test_remember(aiohttp_client): async def handler(request): response = web.Response() await remember(request, response, 'Andrew') return response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', handler) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status assert 'Andrew' == resp.cookies['AIOHTTP_SECURITY'].value async def test_identify(aiohttp_client): async def create(request): response = web.Response() await remember(request, response, 'Andrew') return response async def check(request): policy = request.app[IDENTITY_KEY] user_id = await policy.identify(request) assert 'Andrew' == user_id return web.Response() app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', check) app.router.add_route('POST', '/', create) client = await aiohttp_client(app) resp = await client.post('/') assert 200 == resp.status await resp.release() resp = await client.get('/') assert 200 == resp.status async def test_forget(aiohttp_client): async def index(request): return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'Andrew') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status assert str(resp.url).endswith('/') cookies = client.session.cookie_jar.filter_cookies( client.make_url('/')) assert 'Andrew' == cookies['AIOHTTP_SECURITY'].value resp = await client.post('/logout') assert 200 == resp.status assert str(resp.url).endswith('/') cookies = client.session.cookie_jar.filter_cookies( client.make_url('/')) assert 'AIOHTTP_SECURITY' not in cookies aiohttp-security-0.5.0/tests/test_dict_autz.py000066400000000000000000000174431452621411600216050ustar00rootroot00000000000000import enum from aiohttp import web from aiohttp_security import ( AbstractAuthorizationPolicy, authorized_userid, check_authorized, check_permission, forget, is_anonymous, permits, remember) from aiohttp_security import setup as _setup from aiohttp_security.cookies_identity import CookiesIdentityPolicy class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): if identity == 'UserID': return permission in {'read', 'write'} else: return False async def authorized_userid(self, identity): if identity == 'UserID': return 'Andrew' else: return None async def test_authorized_userid(aiohttp_client): async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def check(request): userid = await authorized_userid(request) assert 'Andrew' == userid return web.Response(text=userid) app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', check) app.router.add_route('POST', '/login', login) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status txt = await resp.text() assert 'Andrew' == txt async def test_authorized_userid_not_authorized(aiohttp_client): async def check(request): userid = await authorized_userid(request) assert userid is None return web.Response() app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', check) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status async def test_permits_enum_permission(aiohttp_client): class Permission(enum.Enum): READ = '101' WRITE = '102' UNKNOWN = '103' class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): if identity == 'UserID': return permission in {Permission.READ, Permission.WRITE} else: return False async def authorized_userid(self, identity): if identity == 'UserID': return 'Andrew' else: return None async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def check(request): ret = await permits(request, Permission.READ) assert ret ret = await permits(request, Permission.WRITE) assert ret ret = await permits(request, Permission.UNKNOWN) assert not ret return web.Response() app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', check) app.router.add_route('POST', '/login', login) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status async def test_permits_unauthorized(aiohttp_client): async def check(request): ret = await permits(request, 'read') assert not ret ret = await permits(request, 'write') assert not ret ret = await permits(request, 'unknown') assert not ret return web.Response() app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', check) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status async def test_is_anonymous(aiohttp_client): async def index(request): is_anon = await is_anonymous(request) if is_anon: raise web.HTTPUnauthorized() return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/') assert web.HTTPOk.status_code == resp.status await client.post('/logout') resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status async def test_check_authorized(aiohttp_client): async def index(request): await check_authorized(request) return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/') assert web.HTTPOk.status_code == resp.status await client.post('/logout') resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status async def test_check_permission(aiohttp_client): async def index_read(request): await check_permission(request, 'read') return web.Response() async def index_write(request): await check_permission(request, 'write') return web.Response() async def index_forbid(request): await check_permission(request, 'forbid') return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/permission/read', index_read) app.router.add_route('GET', '/permission/write', index_write) app.router.add_route('GET', '/permission/forbid', index_forbid) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/permission/read') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/write') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/forbid') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/permission/read') assert web.HTTPOk.status_code == resp.status resp = await client.get('/permission/write') assert web.HTTPOk.status_code == resp.status resp = await client.get('/permission/forbid') assert web.HTTPForbidden.status_code == resp.status await client.post('/logout') resp = await client.get('/permission/read') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/write') assert web.HTTPUnauthorized.status_code == resp.status resp = await client.get('/permission/forbid') assert web.HTTPUnauthorized.status_code == resp.status aiohttp-security-0.5.0/tests/test_jwt_identity.py000066400000000000000000000043401452621411600223240ustar00rootroot00000000000000import jwt import pytest from aiohttp import web from aiohttp_security import AbstractAuthorizationPolicy from aiohttp_security import setup as _setup from aiohttp_security.api import IDENTITY_KEY from aiohttp_security.jwt_identity import JWTIdentityPolicy @pytest.fixture def make_token(): def factory(payload, secret): return jwt.encode( payload, secret, algorithm='HS256', ) return factory class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): pass async def authorized_userid(self, identity): pass async def test_no_pyjwt_installed(mocker): mocker.patch("aiohttp_security.jwt_identity.HAS_JWT", False) with pytest.raises(RuntimeError): JWTIdentityPolicy('secret') async def test_identify(make_token, aiohttp_client): kwt_secret_key = "Key" # noqa: S105 token = make_token({'login': 'Andrew'}, kwt_secret_key) async def check(request): policy = request.app[IDENTITY_KEY] identity = await policy.identify(request) assert "Andrew" == identity return web.Response() app = web.Application() _setup(app, JWTIdentityPolicy(kwt_secret_key), Autz()) app.router.add_route('GET', '/', check) client = await aiohttp_client(app) headers = {"Authorization": "Bearer {}".format(token)} resp = await client.get('/', headers=headers) assert 200 == resp.status async def test_identify_broken_scheme(make_token, aiohttp_client): kwt_secret_key = "Key" # noqa: S105 token = make_token({'login': 'Andrew'}, kwt_secret_key) async def check(request): policy = request.app[IDENTITY_KEY] try: await policy.identify(request) except ValueError as exc: raise web.HTTPBadRequest(reason=str(exc)) return web.Response() app = web.Application() _setup(app, JWTIdentityPolicy(kwt_secret_key), Autz()) app.router.add_route('GET', '/', check) client = await aiohttp_client(app) headers = {"Authorization": "Token {}".format(token)} resp = await client.get('/', headers=headers) assert 400 == resp.status assert 'Invalid authorization scheme' in resp.reason aiohttp-security-0.5.0/tests/test_no_auth.py000066400000000000000000000016331452621411600212460ustar00rootroot00000000000000from aiohttp import web from aiohttp_security import authorized_userid, permits async def test_authorized_userid(aiohttp_client): async def check(request): userid = await authorized_userid(request) assert userid is None return web.Response() app = web.Application() app.router.add_route('GET', '/', check) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status async def test_permits(aiohttp_client): async def check(request): ret = await permits(request, 'read') assert ret ret = await permits(request, 'write') assert ret ret = await permits(request, 'unknown') assert ret return web.Response() app = web.Application() app.router.add_route('GET', '/', check) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status aiohttp-security-0.5.0/tests/test_no_identity.py000066400000000000000000000017371452621411600221430ustar00rootroot00000000000000from aiohttp import web from aiohttp_security import forget, remember async def test_remember(aiohttp_client): async def do_remember(request): response = web.Response() await remember(request, response, 'Andrew') app = web.Application() app.router.add_route('POST', '/', do_remember) client = await aiohttp_client(app) resp = await client.post('/') assert 500 == resp.status exp = "Security subsystem is not initialized, call aiohttp_security.setup(...) first" assert exp == resp.reason async def test_forget(aiohttp_client): async def do_forget(request): response = web.Response() await forget(request, response) app = web.Application() app.router.add_route('POST', '/', do_forget) client = await aiohttp_client(app) resp = await client.post('/') assert 500 == resp.status exp = "Security subsystem is not initialized, call aiohttp_security.setup(...) first" assert exp == resp.reason aiohttp-security-0.5.0/tests/test_session_identity.py000066400000000000000000000060071452621411600232050ustar00rootroot00000000000000import pytest from aiohttp import web from aiohttp_session import SimpleCookieStorage, get_session from aiohttp_session import setup as setup_session from aiohttp_security import AbstractAuthorizationPolicy, forget, remember from aiohttp_security import setup as setup_security from aiohttp_security.api import IDENTITY_KEY from aiohttp_security.session_identity import SessionIdentityPolicy class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): pass async def authorized_userid(self, identity): pass @pytest.fixture def make_app(): app = web.Application() setup_session(app, SimpleCookieStorage()) setup_security(app, SessionIdentityPolicy(), Autz()) return app async def test_remember(make_app, aiohttp_client): async def handler(request): response = web.Response() await remember(request, response, 'Andrew') return response async def check(request): session = await get_session(request) assert session['AIOHTTP_SECURITY'] == 'Andrew' return web.Response() app = make_app() app.router.add_route('GET', '/', handler) app.router.add_route('GET', '/check', check) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status resp = await client.get('/check') assert 200 == resp.status async def test_identify(make_app, aiohttp_client): async def create(request): response = web.Response() await remember(request, response, 'Andrew') return response async def check(request): policy = request.app[IDENTITY_KEY] user_id = await policy.identify(request) assert 'Andrew' == user_id return web.Response() app = make_app() app.router.add_route('GET', '/', check) app.router.add_route('POST', '/', create) client = await aiohttp_client(app) resp = await client.post('/') assert 200 == resp.status resp = await client.get('/') assert 200 == resp.status async def test_forget(make_app, aiohttp_client): async def index(request): session = await get_session(request) return web.Response(text=session.get('AIOHTTP_SECURITY', '')) async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'Andrew') raise response async def logout(request): response = web.HTTPFound('/') await forget(request, response) raise response app = make_app() app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status assert str(resp.url).endswith('/') txt = await resp.text() assert 'Andrew' == txt resp = await client.post('/logout') assert 200 == resp.status assert str(resp.url).endswith('/') txt = await resp.text() assert '' == txt