pax_global_header00006660000000000000000000000064133531034120014505gustar00rootroot0000000000000052 comment=fdf8a39607e86e003524d5ced987aaec688d3b35 aiohttp-security-0.4.0/000077500000000000000000000000001335310341200150235ustar00rootroot00000000000000aiohttp-security-0.4.0/.coveragerc000066400000000000000000000001461335310341200171450ustar00rootroot00000000000000[run] branch = True source = aiohttp_security, tests omit = site-packages [html] directory = coverageaiohttp-security-0.4.0/.gitignore000066400000000000000000000013101335310341200170060ustar00rootroot00000000000000# 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.4.0/.pyup.yml000066400000000000000000000001221335310341200166140ustar00rootroot00000000000000# Label PRs with `deps-update` label label_prs: deps-update schedule: every week aiohttp-security-0.4.0/.travis.yml000066400000000000000000000023301335310341200171320ustar00rootroot00000000000000language: python python: - 3.5 - 3.6 - 3.7-dev - nightly matrix: allow_failures: - python: 3.7-dev - python: nightly install: - pip install --upgrade pip - pip install -r requirements-dev.txt - pip install codecov script: - make coverage after_success: - codecov env: matrix: - PYTHONASYNCIODEBUG=x - PYTHONASYNCIODEBUG= deploy: provider: pypi user: aio-libs-bot password: secure: "fHbpT6AuRM+K6hg0nWT7ov/qJAAFJ7N5Mot1Z02QVHv9+XXJsqSmzJHMyv4FNWSO+IG9ulJ/wrVpQ/wr5S1FiCVJYpMFJP/71fqT7MbrgUg+ovbGrs1AfJHHQtVc91Az9Yl2nP+wzJCplJIuxO8IVjKHS87QxupzMHapo97ItYM6yvCNzIP+3JjvZyl5/ocqdUpl4KiS/tzXbiaBSlVgmI/013EbD5U36wcz2AAszTcBzKTDJh0BF4wr4brHnVPKr4gRSZPZRYduZ7WXh0rJt/aGyNGm9siYkKhuE+pzd/6vIbN3keKEhAjafCl4+Z3a0eL0ACyt8CBCBHf9/n4KYm+KPwLe3NYWKkO6qCJpZ+bMNfQInKiEoWJx9KDaKjdCVivlKY+abaJiF/thO4udunn3PfPz2O8MlkZRoTVqASN1sP60cULTlxfLi8x0RVqMKIHejNQi/AN8/4poCPFfFOOia/WQqq1pD45vJh8pNxsc6IEAjhHUgvMDnK0DBkEs4i2catZKc2YPEjgAkvplvTE4tH8Tzyj5EvMwM56h2zfByeKs9ojkvzyhPLhWq7d8JTPWPAyj72FsrpGm12cLU/E9g9KKj6Hg5E3F0+V2Zs7wXc+fT1ovC5/NRL2WpT2+k1wF/9Q7ZrbQ9InunHXYU7GJCFzRE8XlcRsBGPcR3Ls=" distributions: "sdist bdist_wheel" on: tags: true all_branches: true python: 3.6 condition: $PYTHONASYNCIODEBUG = ""aiohttp-security-0.4.0/CHANGES.txt000066400000000000000000000014301335310341200166320ustar00rootroot00000000000000Changes ======= 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.4.0/LICENSE000066400000000000000000000261101335310341200160300ustar00rootroot00000000000000Apache 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.4.0/MANIFEST.in000066400000000000000000000002321335310341200165560ustar00rootroot00000000000000include LICENSE include CHANGES.txt include README.rst include Makefile graft aiohttp_security graft docs graft examples graft tests global-exclude *.pyc aiohttp-security-0.4.0/Makefile000066400000000000000000000015661335310341200164730ustar00rootroot00000000000000# Some simple testing tasks (sorry, UNIX only). flake: flake8 aiohttp_security tests test: flake py.test -s -q ./tests/ vtest: flake py.test -s ./tests/ cov cover coverage: flake py.test -s ./tests/ --cov=aiohttp_security --cov=tests --cov-report=html --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.4.0/README.rst000066400000000000000000000025051335310341200165140ustar00rootroot00000000000000aiohttp_security ================ .. image:: https://travis-ci.org/aio-libs/aiohttp-security.svg?branch=master :target: https://travis-ci.org/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.4.0/aiohttp_security/000077500000000000000000000000001335310341200204225ustar00rootroot00000000000000aiohttp-security-0.4.0/aiohttp_security/__init__.py000066400000000000000000000014271335310341200225370ustar00rootroot00000000000000from .abc import AbstractAuthorizationPolicy, AbstractIdentityPolicy from .api import (authorized_userid, forget, has_permission, is_anonymous, login_required, permits, remember, setup, check_authorized, check_permission) from .cookies_identity import CookiesIdentityPolicy from .session_identity import SessionIdentityPolicy from .jwt_identity import JWTIdentityPolicy __version__ = '0.4.0' __all__ = ('AbstractIdentityPolicy', 'AbstractAuthorizationPolicy', 'CookiesIdentityPolicy', 'SessionIdentityPolicy', 'JWTIdentityPolicy', 'remember', 'forget', 'authorized_userid', 'permits', 'setup', 'is_anonymous', 'login_required', 'has_permission', 'check_authorized', 'check_permission') aiohttp-security-0.4.0/aiohttp_security/abc.py000066400000000000000000000027211335310341200215230ustar00rootroot00000000000000import abc # see http://plope.com/pyramid_auth_design_api_postmortem class AbstractIdentityPolicy(metaclass=abc.ABCMeta): @abc.abstractmethod async def identify(self, request): """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, response, identity, **kwargs): """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, response): """ 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, permission, context=None): """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): """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.4.0/aiohttp_security/api.py000066400000000000000000000133761335310341200215570ustar00rootroot00000000000000import enum import warnings from aiohttp import web from aiohttp_security.abc import (AbstractIdentityPolicy, AbstractAuthorizationPolicy) from functools import wraps IDENTITY_KEY = 'aiohttp_security_identity_policy' AUTZ_KEY = 'aiohttp_security_autz_policy' async def remember(request, response, identity, **kwargs): """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. """ assert isinstance(identity, str), identity assert identity 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, response): """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): identity_policy = request.config_dict.get(IDENTITY_KEY) autz_policy = 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, permission, context=None): assert isinstance(permission, (str, enum.Enum)), permission assert permission identity_policy = request.config_dict.get(IDENTITY_KEY) autz_policy = 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 has some permissions access = await autz_policy.permits(identity, permission, context) return access async def is_anonymous(request): """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): """Checker that raises HTTPUnauthorized for anonymous users. """ userid = await authorized_userid(request) if userid is None: raise web.HTTPUnauthorized() return userid def login_required(fn): """Decorator that restrict access only for authorized users. User is considered authorized if authorized_userid returns some value. """ @wraps(fn) async def wrapped(*args, **kwargs): request = args[-1] if not isinstance(request, web.BaseRequest): msg = ("Incorrect decorator usage. " "Expecting `def handler(request)` " "or `def handler(self, request)`.") raise RuntimeError(msg) await check_authorized(request) return await fn(*args, **kwargs) warnings.warn("login_required decorator is deprecated, " "use check_authorized instead", DeprecationWarning) return wrapped async def check_permission(request, permission, context=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() def has_permission( permission, context=None, ): """Decorator that restricts access only for authorized users with correct permissions. If user is not authorized - raises HTTPUnauthorized, if user is authorized and does not have permission - raises HTTPForbidden. """ def wrapper(fn): @wraps(fn) async def wrapped(*args, **kwargs): request = args[-1] if not isinstance(request, web.BaseRequest): msg = ("Incorrect decorator usage. " "Expecting `def handler(request)` " "or `def handler(self, request)`.") raise RuntimeError(msg) await check_permission(request, permission, context) return await fn(*args, **kwargs) return wrapped warnings.warn("has_permission decorator is deprecated, " "use check_permission instead", DeprecationWarning) return wrapper def setup(app, identity_policy, autz_policy): assert isinstance(identity_policy, AbstractIdentityPolicy), identity_policy assert isinstance(autz_policy, AbstractAuthorizationPolicy), autz_policy app[IDENTITY_KEY] = identity_policy app[AUTZ_KEY] = autz_policy aiohttp-security-0.4.0/aiohttp_security/cookies_identity.py000066400000000000000000000015671335310341200243520ustar00rootroot00000000000000"""Identity policy for storing info directly into HTTP cookie. Use mostly for demonstration purposes, SessionIdentityPolicy is much more handy. """ from .abc import AbstractIdentityPolicy sentinel = object() class CookiesIdentityPolicy(AbstractIdentityPolicy): def __init__(self): self._cookie_name = 'AIOHTTP_SECURITY' self._max_age = 30 * 24 * 3600 async def identify(self, request): identity = request.cookies.get(self._cookie_name) return identity async def remember(self, request, response, identity, max_age=sentinel, **kwargs): if max_age is sentinel: max_age = self._max_age response.set_cookie(self._cookie_name, identity, max_age=max_age, **kwargs) async def forget(self, request, response): response.del_cookie(self._cookie_name) aiohttp-security-0.4.0/aiohttp_security/jwt_identity.py000066400000000000000000000022651335310341200235160ustar00rootroot00000000000000"""Identity policy for storing info in the jwt token. """ from .abc import AbstractIdentityPolicy try: import jwt except ImportError: # pragma: no cover jwt = None AUTH_HEADER_NAME = 'Authorization' AUTH_SCHEME = 'Bearer ' class JWTIdentityPolicy(AbstractIdentityPolicy): def __init__(self, secret, algorithm='HS256'): if jwt is None: raise RuntimeError('Please install `PyJWT`') self.secret = secret self.algorithm = algorithm async def identify(self, request): header_identity = request.headers.get(AUTH_HEADER_NAME) if header_identity is None: return if not header_identity.startswith(AUTH_SCHEME): raise ValueError('Invalid authorization scheme. ' + 'Should be `Bearer `') token = header_identity.split(' ')[1].strip() identity = jwt.decode(token, self.secret, algorithms=[self.algorithm]) return identity async def remember(self, *args, **kwargs): # pragma: no cover pass async def forget(self, request, response): # pragma: no cover pass aiohttp-security-0.4.0/aiohttp_security/session_identity.py000066400000000000000000000021311335310341200243650ustar00rootroot00000000000000"""Identity policy for storing info into aiohttp_session session. aiohttp_session.setup() should be called on application initialization to configure aiohttp_session properly. """ 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='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): session = await get_session(request) return session.get(self._session_key) async def remember(self, request, response, identity, **kwargs): session = await get_session(request) session[self._session_key] = identity async def forget(self, request, response): session = await get_session(request) session.pop(self._session_key, None) aiohttp-security-0.4.0/demo/000077500000000000000000000000001335310341200157475ustar00rootroot00000000000000aiohttp-security-0.4.0/demo/database_auth/000077500000000000000000000000001335310341200205345ustar00rootroot00000000000000aiohttp-security-0.4.0/demo/database_auth/db.py000066400000000000000000000020031335310341200214660ustar00rootroot00000000000000import sqlalchemy as sa metadata = sa.MetaData() users = sa.Table( 'users', metadata, sa.Column('id', sa.Integer, nullable=False), sa.Column('login', sa.String(256), nullable=False), sa.Column('passwd', sa.String(256), nullable=False), sa.Column('is_superuser', sa.Boolean, nullable=False, server_default='FALSE'), sa.Column('disabled', sa.Boolean, nullable=False, server_default='FALSE'), # indices sa.PrimaryKeyConstraint('id', name='user_pkey'), sa.UniqueConstraint('login', name='user_login_key'), ) permissions = sa.Table( 'permissions', metadata, sa.Column('id', sa.Integer, nullable=False), sa.Column('user_id', sa.Integer, nullable=False), sa.Column('perm_name', sa.String(64), nullable=False), # indices sa.PrimaryKeyConstraint('id', name='permission_pkey'), sa.ForeignKeyConstraint(['user_id'], [users.c.id], name='user_permission_fkey', ondelete='CASCADE'), ) aiohttp-security-0.4.0/demo/database_auth/db_auth.py000066400000000000000000000041551335310341200225210ustar00rootroot00000000000000import sqlalchemy as sa from aiohttp_security.abc import AbstractAuthorizationPolicy from passlib.hash import sha256_crypt from . import db class DBAuthorizationPolicy(AbstractAuthorizationPolicy): def __init__(self, dbengine): self.dbengine = dbengine async def authorized_userid(self, identity): async with self.dbengine.acquire() as conn: where = sa.and_(db.users.c.login == identity, sa.not_(db.users.c.disabled)) query = db.users.count().where(where) ret = await conn.scalar(query) if ret: return identity else: return None async def permits(self, identity, permission, context=None): if identity is None: return False async with self.dbengine.acquire() as conn: where = sa.and_(db.users.c.login == identity, sa.not_(db.users.c.disabled)) query = db.users.select().where(where) ret = await conn.execute(query) user = await ret.fetchone() if user is not None: user_id = user[0] is_superuser = user[3] if is_superuser: return True where = db.permissions.c.user_id == user_id query = db.permissions.select().where(where) ret = await conn.execute(query) result = await ret.fetchall() if ret is not None: for record in result: if record.perm_name == permission: return True return False async def check_credentials(db_engine, username, password): async with db_engine.acquire() as conn: where = sa.and_(db.users.c.login == username, sa.not_(db.users.c.disabled)) query = db.users.select().where(where) ret = await conn.execute(query) user = await ret.fetchone() if user is not None: hash = user[2] return sha256_crypt.verify(password, hash) return False aiohttp-security-0.4.0/demo/database_auth/handlers.py000066400000000000000000000051561335310341200227150ustar00rootroot00000000000000from textwrap import dedent from aiohttp import web from aiohttp_security import ( remember, forget, authorized_userid, check_permission, check_authorized, ) from .db_auth import check_credentials class Web(object): index_template = dedent("""

{message}

Login: Password:
Logout """) async def index(self, request): 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') response = web.Response(body=template.encode()) return response async def login(self, request): response = web.HTTPFound('/') form = await request.post() login = form.get('login') password = form.get('password') db_engine = request.app.db_engine if await check_credentials(db_engine, login, password): await remember(request, response, login) raise response raise web.HTTPUnauthorized( body=b'Invalid username/password combination') async def logout(self, request): await check_authorized(request) response = web.Response(body=b'You have been logged out') await forget(request, response) return response async def internal_page(self, request): await check_permission(request, 'public') response = web.Response( body=b'This page is visible for all registered users') return response async def protected_page(self, request): await check_permission(request, 'protected') response = web.Response(body=b'You are on protected page') return response def configure(self, app): 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.4.0/demo/database_auth/main.py000066400000000000000000000033021335310341200220300ustar00rootroot00000000000000import asyncio from aiohttp import web from aiohttp_session import setup as setup_session from aiohttp_session.redis_storage import RedisStorage from aiohttp_security import setup as setup_security from aiohttp_security import SessionIdentityPolicy from aiopg.sa import create_engine from aioredis import create_pool from demo.database_auth.db_auth import DBAuthorizationPolicy from demo.database_auth.handlers import Web async def init(loop): redis_pool = await create_pool(('localhost', 6379)) db_engine = await create_engine(user='aiohttp_security', password='aiohttp_security', database='aiohttp_security', host='127.0.0.1') app = web.Application() app.db_engine = db_engine setup_session(app, RedisStorage(redis_pool)) setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy(db_engine)) web_handlers = Web() web_handlers.configure(app) handler = app.make_handler() srv = await loop.create_server(handler, '127.0.0.1', 8080) print('Server started at http://127.0.0.1:8080') return srv, app, handler async def finalize(srv, app, handler): sock = srv.sockets[0] app.loop.remove_reader(sock.fileno()) sock.close() await handler.finish_connections(1.0) srv.close() await srv.wait_closed() await app.finish() def main(): loop = asyncio.get_event_loop() srv, app, handler = loop.run_until_complete(init(loop)) try: loop.run_forever() except KeyboardInterrupt: loop.run_until_complete((finalize(srv, app, handler))) if __name__ == '__main__': main() aiohttp-security-0.4.0/demo/database_auth/sql/000077500000000000000000000000001335310341200213335ustar00rootroot00000000000000aiohttp-security-0.4.0/demo/database_auth/sql/init_db.sql000066400000000000000000000004151335310341200234640ustar00rootroot00000000000000CREATE USER aiohttp_security WITH PASSWORD 'aiohttp_security'; DROP DATABASE IF EXISTS aiohttp_security; CREATE DATABASE aiohttp_security; ALTER DATABASE aiohttp_security OWNER TO aiohttp_security; GRANT ALL PRIVILEGES ON DATABASE aiohttp_security TO aiohttp_security; aiohttp-security-0.4.0/demo/database_auth/sql/sample_data.sql000066400000000000000000000027011335310341200243260ustar00rootroot00000000000000-- create users table CREATE TABLE IF NOT EXISTS users ( id integer NOT NULL, login character varying(256) NOT NULL, passwd character varying(256) NOT NULL, is_superuser boolean NOT NULL DEFAULT false, disabled boolean NOT NULL DEFAULT false, CONSTRAINT user_pkey PRIMARY KEY (id), CONSTRAINT user_login_key UNIQUE (login) ); -- and permissions for them CREATE TABLE IF NOT EXISTS permissions ( id integer NOT NULL, user_id integer NOT NULL, perm_name character varying(64) NOT NULL, CONSTRAINT permission_pkey PRIMARY KEY (id), CONSTRAINT user_permission_fkey FOREIGN KEY (user_id) REFERENCES users (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE ); -- insert some data INSERT INTO users(id, login, passwd, is_superuser, disabled) VALUES (1, 'admin', '$5$rounds=535000$2kqN9fxCY6Xt5/pi$tVnh0xX87g/IsnOSuorZG608CZDFbWIWBr58ay6S4pD', TRUE, FALSE); INSERT INTO users(id, login, passwd, is_superuser, disabled) VALUES (2, 'moderator', '$5$rounds=535000$2kqN9fxCY6Xt5/pi$tVnh0xX87g/IsnOSuorZG608CZDFbWIWBr58ay6S4pD', FALSE, FALSE); INSERT INTO users(id, login, passwd, is_superuser, disabled) VALUES (3, 'user', '$5$rounds=535000$2kqN9fxCY6Xt5/pi$tVnh0xX87g/IsnOSuorZG608CZDFbWIWBr58ay6S4pD', FALSE, FALSE); INSERT INTO permissions(id, user_id, perm_name) VALUES (1, 2, 'protected'); INSERT INTO permissions(id, user_id, perm_name) VALUES (2, 2, 'public'); INSERT INTO permissions(id, user_id, perm_name) VALUES (3, 3, 'public'); aiohttp-security-0.4.0/demo/dictionary_auth/000077500000000000000000000000001335310341200211355ustar00rootroot00000000000000aiohttp-security-0.4.0/demo/dictionary_auth/authz.py000066400000000000000000000021041335310341200226370ustar00rootroot00000000000000from aiohttp_security.abc import AbstractAuthorizationPolicy class DictionaryAuthorizationPolicy(AbstractAuthorizationPolicy): def __init__(self, user_map): super().__init__() self.user_map = user_map 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 in self.user_map: 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. """ # pylint: disable=unused-argument user = self.user_map.get(identity) if not user: return False return permission in user.permissions async def check_credentials(user_map, username, password): user = user_map.get(username) if not user: return False return user.password == password aiohttp-security-0.4.0/demo/dictionary_auth/handlers.py000066400000000000000000000046541335310341200233200ustar00rootroot00000000000000from textwrap import dedent from aiohttp import web from aiohttp_security import ( remember, forget, authorized_userid, check_permission, check_authorized, ) from .authz import check_credentials index_template = dedent("""

{message}

Login: Password:
Logout """) async def index(request): 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): response = web.HTTPFound('/') form = await request.post() username = form.get('username') password = form.get('password') verified = await check_credentials( request.app.user_map, username, password) if verified: await remember(request, response, username) return response return web.HTTPUnauthorized(body='Invalid username / password combination') async def logout(request): 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): 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): await check_permission(request, 'protected') response = web.Response( text='You are on protected page', content_type='text/html', ) return response def configure_handlers(app): 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.4.0/demo/dictionary_auth/main.py000066400000000000000000000020131335310341200224270ustar00rootroot00000000000000import base64 from cryptography import fernet from aiohttp import web from aiohttp_session import setup as setup_session from aiohttp_session.cookie_storage import EncryptedCookieStorage from aiohttp_security import setup as setup_security from aiohttp_security import SessionIdentityPolicy from demo.dictionary_auth.authz import DictionaryAuthorizationPolicy from demo.dictionary_auth.handlers import configure_handlers from demo.dictionary_auth.users import user_map def make_app(): 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.4.0/demo/dictionary_auth/users.py000066400000000000000000000004171335310341200226520ustar00rootroot00000000000000from collections import namedtuple User = namedtuple('User', ['username', 'password', 'permissions']) user_map = { user.username: user for user in [ User('devin', 'password', ('public',)), User('jack', 'password', ('public', 'protected',)), ] } aiohttp-security-0.4.0/demo/simple_example_auth.py000066400000000000000000000060311335310341200223460ustar00rootroot00000000000000from 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.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.4.0/docs/000077500000000000000000000000001335310341200157535ustar00rootroot00000000000000aiohttp-security-0.4.0/docs/Makefile000066400000000000000000000164311335310341200174200ustar00rootroot00000000000000# 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.4.0/docs/_static/000077500000000000000000000000001335310341200174015ustar00rootroot00000000000000aiohttp-security-0.4.0/docs/_static/aiohttp-icon-128x128.png000066400000000000000000000456661335310341200234610ustar00rootroot00000000000000‰PNG  IHDR€€Ã>aËbKGDÿÿÿ ½§“ pHYs  šœtIMEß `)b' IDATxÚì½ù³$×ußù¹7—Úë-ýºûõ t7Ðh,@‚«¸H¦D‚ZL),ɦeY¶#&1óƒÿùyÆaO83ÏØQ -’²%ÑW€$€Ø»Ñè}y{í•˽g~¸™Y•¯ª^7@J¤.DF?ô«®Ê¼çܳ|Ï÷œ«DDø;þÚÿˆ‹Y)uàÿÿ]|ù× 7ÿÙZ[ü<}-R€éKk=ów×Cým¶ÓBÎ/cLñó~áæ'ÄýŠ3­(¹ð=ÏCk]ü¹_1þ‡ü <zš¦c0Æ "…pòKk]ú{ù¾iÅšþ®\¡|ß/¾ïo£2ü­P€\ÆÒ4%MS¬µ…‚ (þ7ñÊï%IÒ4-”Ï÷ýB!þ¶(ÃϬä;=z’$…ÐÃ0,„þ³ðÊ•aúƒ À÷ý ýx»=_T¥a†á{ºX’hD0IŒM¬MA\€ˆÒhí£|í…a…°RÇóƒ÷¤ q“$ "B…²þ,Z…Ÿ˜|E¤iŠïûT*Â0¼oA›¨O:Ú#éïÒÛÛ »·ÍÖÝëlooÑëI’”4M°™/ŸŠQÚ#êµí¥e:Ê¡ÃÇh®fií8Ac/l€¾¿ä)I¢(ƒïû…ÿ,)ÂO]æ >ªÕ*¾¯…ÌpxïÑö;Øá&Ãáí½7îlrýÖ[[›t:»ôC·+ñ°"Ø9­4Ïó¨T*4êMZk«ËŽc¢(Â÷}ÆÂNû›ô/“øæ xã-*¶‡ß¿çùÈÚ£\î·ùÚ ïðÊ+¯píúug°½|g ØÄ,4ÉJ{ˆò¦”%uî!\‚ÚØF›HÒQ€W¸ñœòh¥XY]å}O<Î'>øUƒ«¤)DRÁT®?Aóῇß:ºpC ‡CŒ1?kð7¢¹¯Ç$IB½^_¸ëÍh—þ¥¯3ºôßð·¨7ÚTª5ÔÞ;ˆ5pâc|çˆÿòß¾ÉÛ—/EQÙ¿{H‚Ø$3ú :pï° *hBý(à ˆ{ÈÄž D¼Y÷á{>§Nâ3Ÿþ$ŸxôíñEÔÝd¸{Óákçç+K÷a¼“Y µÈd8W1GéJJpèŸû̧ùÕœ¤Þ} ¢‚ ‰adCôɲôäo®>8# ]ÊZ«Õ —ð·JrEãñ˜z½N­V›}_:¦÷ÚW¾øŽnSÀ÷*¨Cójù jå4që ßyé ôÅ?à‹¯ Iä=OX•%Tc‚†2‚¤cd¸åv¸5îóë‡Q€Œw2s…Â"X”±ÜkÉŽ­¯óËÏ~Šg?pŒp÷-TÒwÏ«4©h†‘!®¡þø? õð§Q~eæ3Æã1£ÑˆjµúÞП†ˆišEQÑjµæ"yI÷{ßûwØKNÃO©x 0(ç{E@[ìá ¼Ø?Ãÿ÷Õçxóê&¢+.¸K†nçš(óÕ ÇЭ ½y7†Œ¶!€_…¨‹J‡ˆ’N¥€ÌˆÀ¸o#Sñ³®BYΜyÏîøäù6zçu0±S8¢4Q ƒT£O|„åü.Aûø¬eŒcƒ•J¥ˆ ~¦ ~ìµZ­9¹½0¼ñº?ø7½·iØß&n‡É>{Þ^ãjð>~ÿÏ^äÛßþ6¢”®:†Mðk¼‰»ˆ®à-=0_øÓß>î@çòÄ d÷I2«2O¨¦$pe±v¡²ˆr¿{òÉ'øG¿úó<¶ÁÞ¥’’šT` Hšgh?ó/©Ÿ|fƪ¥iJ¿ß/ÐÑŸt†ðS€\ø9ÒÕn·g=± ½7¾ÌðGÿ'5éP :‰Q£h6@ ú‡žâ+¯¾øÅ?`4eù{uÊûÔ±a]?<×”N|ív›Õå­tƒj¨ ü€ ð±Ö’Äñx@0`oo¢(rÅÌîò9®Àí~SÎo~úiŽ˜k0Þ)+аXF±0RKÔŸü=Züª þ†”ÀÿI ?I–––f„o“!{/þG’‹_¤¤T<…¾߇4ÄìÊBû(×Gk<÷Ü3ÝÞAI‚¨Ì¥ˆq»ßh®Ïz¥Rayy™õõuΟ?ÏûÞ÷>δÇ4í6ÊZDRÑbR®ß¼É¯ðÊ—¸rí»»›ôŒ1S6 ”V8½˜.(Ù’"Çq /¾Â™SÇùÅÇŽD=ü9S”$x@=ôðLÁÿ i“å§ÿ :˜ÄL¾ïÓjµèv»E†ð“rþOÚìϾ‰ºì~ïßb¯þWZµuÐk.ðÐc)|@Ð Oñü‹ïpéÒÛû¾Ï ”EÐqhß¡wS¯0 Y[[ãÂ… |ö³ŸåÑGÜÏ¥?…Kì²…iˆØÄœ´–“NñKþevÇð_ÿê;<ÿƒ—¹}ç.ãñ¸ š‰R(5¹eg)fé^g—^»È£|„êk0¸“}c\¼[‹¡êi´Jé¿õûìD]V>ô?áUÚÅçxžG«Õ¢×ëŠý“PÿÇ~íGQ4_ø£=v¾û¿¡nýwÚU…¯Ò,ЛúO£‰S'Üö).õ×øÆ_ýÑÜ`›€Îͽu–)òýF£Á3Ï<Ãç>÷9yä‘YW”Œ§¤>ÙÕx!*íb7^FmüåjÈ?úÔ|âCóÕ¯¿À·¿ó<»»»“J¢V`Äýk5?&H“”Ko_æµ+ç8öh›Pm¡dXr+’Õ"B-´«>ý«_e'³ú±ÿ¯Ú.Y‚f³I¿ß/8?®üX fžçÇ㹟wÙùî¿FÝúï4«8ác²ºÿ }”§ 0Oòú[—ÙÚÚ^TFI:1¿éØaöÀ‘#Gø­ßú-þù?ÿç<öØcø¾_öÕ6Ez7\¹ï”62H9‚x¹õ-ŽŸçwùI~ç ¿É±ãÇ&÷¡œ+PjqVÐétyùõ·¹;ôP•&¨dæ»E9+â«”fUУ[ì^ûfÜ+}V4ÂâZk: ãúÃáz½N¥RÀl<`ï…ÿ}ç9šµ_{(„ Î\¢+P `ù$7Òüå×¾î"úy—ò²ŸfiY„‰z9r„ßøßàÙgŸåСCsÀf´‡Z=jŸÊ„&û|»‡ò|§ Tœ‘íÞý.Ÿz¤Á?þ‡¿Å©ÓdK§Akg Ý«öHŒåúÍ;\º;$öëHb Ng.‰SˆÆËÑ~øYÔ›ÿ‰½þ#6̸·jµZÜ?N¯ßëÎσ¾0 ©×ëûžˆ½—¿7¾ACø¢QfÂ_p‰’úƒ¼sc“­='èEârwQxušÕ€O}ôý|⟠ÑhÌ¿ïá6éþ/¼Î%8ý ¨ÓŸF…-È«€€ØnCªË÷—ü­Wùð™¿òÙÏräè1·|y,£<‡<W]îÿw:=Þºr‡ž­£lQ2{ǨÖÃèÓ¿Œ~ë‹4ÆWàÎsì½üE$-W6s”ðÇUý^ýþx<.°ýò ׿‚½þMf?飒ѽ‘6ÓC£Ï?ÿ½{ râ‚A/€öi<ßç©ÓM>v|De÷$!Ùx•èûÿ;þÞ¨­Wà⻈ü¡Ï£¿o‚·‘¨‡J†Îº”ú`çe~îñu>üÁg¨U+ˆd¾\y ¦…_þ9ŠS®^¿Ím,OGź©•sèG~ûÖAç ¾§ièöÆ·è¼þÕ¬º9y5 D„(ŠÞ³+ðߋ颈8ŽYYY™ÉG{—¿Mrù/hI?é °ŒP~˜Õàç1¤]XzœëÛ ¯½öêÁJhS”_‡æIˆ:¬5=>ù¡Çx@.1úÚ—ˆÖžÀ[¯¾†Ø»÷6jëG„v€n É®ÿªyŽ –Ï"WþldV,F¥cöAØÑíè>þ \~ç2¯½öÊtÞ¹H¶–ÍM.ßpîÑ“TƈF. ‹jž@?úìå¯ Ûo «.&1M¿JïòŸÓ«¯Ò:÷ÉRšÛl6év»íÝÖ ü÷júÆLt=Þx“Ñë_¢¥GøýÍ,ÕSGPmÍÁïÒâŒô W¯ßÀ¤ÉT„$¥zbPaë0¼‹Š;<ý‰Ïðä©zóeê:Âl>¹û¼CëmBÏC{žKÛ’T–]îHÿêÒ—àÈ“ðà³®ì{ó;ˆ5H<ÊŠJÞ$YÔŒ÷8»vŒgž~Œk×®Ðï÷ÝîU¤–³™‹¡×ëqùê-zž$¬µPF(¿‚~âwßBn¿µ%DùÙæ°ø¦O#é¿þ%‚ÖªG)eµZñxŒç9R뻉ô»1ý¹ð}ߟñûé`›îË@A´ípö©0WÒ•&sLÿ1¨¬°9ªñÚëoaAæNQbîTW ¾ý›Èx—V«Å§>úÍÑÛHÜs<>ϧøTM°‚çù(”ÃáÓ1”ü©v™Á•¿À¾üïQë@½ï÷Pµ‡ß'£‰‰êHØD‚Þ<}~Ó§O;Š™WCü&.#•U¤zÈ]•U$l#A“ÄzlítØX$¨!Ê"•%ÔÿÙ»‚½þMTP…):™ P6!”!uút_þ"é`g&ÐZ,«¿– úÓ4ñûbSº¯ý)Áð:UF¨ÑÖ¬Ï ñ ¸²O…tÏý]Ф3V\¿q +ëÜG¾ Tm *ËлŠÄ=PŠ .pöˆý+…WüüJçK¡È›ô³ÏŸ~v°…ì]ÆþðßÀhýþ‰Z{‰®¤4¯êè‚iÞa}%ä±§?Šß:ŽT× …xUDWºKW¯Ž„ËØÊ!¶šk{ií¢ êÌgtŒ½þ-[H¥9c%PÉ€ª— ®Ñ}íOgŠWÍf³Ô@óU€iÓ_¯×gLÿàêó˜Ûߣ*ÔàŽ»9¥öåº ±‰ó«yÞmúˆŒA¿ÅÝí.QM[L&|õ£Ž´Ñ½‚˜qáoþS§2¸ˆH¥­ûl­‘°Žh=‹7(…ØI‡“|¼ã\ƒöa/þ öí/£Ïÿ:ê쳈 ª™H„h9ôþÊ9Ξœ¥•µ²¢OÔ­ôÿ‚b¯7æÖž­~þMhÁ^úSD R[†ê²K-÷ãTÚ¥QÕ˜ÛÏ3¸ú|IžçQ­V +p¿Y¾ß¨?Š"”R3¦?éÜbðêÐð-~¼ q÷€`H\@h JH;îï¼ ý´Êíí2æ.Ö•bëë.Âî]ÉHîÕj¶xøÌIè]q¸€ŽÝ2ûUgz®t€H긃­r¬¡4²ñ2æGÿÖC?üë  µÃˆß$<úÕCgX^]›¬šKFÈþÔàW‰&Š x5@cE0A {ø)ðªÎ:YãîÅÚ©ûNAF(³‡ï¥Ô¼„Þk‚‡¥¯{7V@ßïÏûÙJßÍ—QËg¨6Ûh=v,Óu Î¼bO~™bLjŒP¶çþΈSGG‘ѳ=ÜuM›Êaíjßg]?ŠŠ;Y!G@Eˆ’¬°äàŠx)¢ bG(Ó+‰±D”`ý²rQ obw_‡æ ª'ž!lÅó<ÚKK4›M$ޱ»{˜;w17nbnÞÂÞÝÀîudB8M“ëÕVϺXEY¬L} 9ü¾¢uM´ï,TvÏJ[ðƒNw¨ v^cpõ»3µÏóî+Ð÷³û÷cëfÔaøü¿¦–nœû´«n¡IÀt»Iâ—'fiÇ<ðˆ“„Ô¨vÜþÁmPº m¹È¸lÎõ:¤Y¡D¥iQ«§²˜¾² “‰I5]”’øYÔnÛg±~µ€|­I¨T«øõ—ÿ5k©vºpårý&llÂÎ.lï w7k×±ï\ÅnnaãÁ1¦ýú*áÚÃ…k¦u iž˜T½JQû@'þ£àÙUß0¼øU̸;c¦X¼+˜¦tçci÷¿ó Ôî›7ÿµô¬>^táˆé£Ìhn Ò"ñ’L ÄqŠTVÝ÷oO„^`p™Èkþõ::ëûsxAÙWŠï9+0OþzšÿçÒB—‘8N–`ƒe¤~ÔõV<ÂÃâW[Žå¿y‰ðÕ7¨ôú$óc‘Û·±×®cŒµ€ÅoÅ_z°xNëÈÊàCGdUž»'e•L­¦ Ò]*žEu/3¸öÜŒÐZÇñV@ߋٻ?í³QŸÑ›_¡ê¼d¹ö§èÍaóyäî¡öóèìL®ß3FêG]à5¸í”IçèÝ¢tAú¬Õëh»ÅU ¡?gô›5ËÓw*ߢ°ˆÊ¦•X‹n'lÇu¢ˆùâãu»÷ÑÊž½ú}ìõØ^Ï±Š€`é”C8q[;„Ô8«cmfý"W¼*.‹˜^ºCÕ3ŒÞþË™²qµZ%Žãq‘ùÏ'sìüG7~;oR©€Ò)²ùC8ò!Ô‰ŸG®~Å¥cvŒJûà/çzíðþ™ŽåÚ²–N¢Ò#п˜ÄUù”žïH”‡RÖaÞ’¢Hd¾Çñ4*ð!žú}aF÷…ëb;È÷Ö«:P&ãðYR[=ƒR‚ܺù£/¡z}t»ý®ðw3’\zóñàÕ«h/ hŸ"Žºî¹ý:~ ÔQ~å+°=·$Èlì`m›P¡Íh¸ÁèÎk4N¨” ‡ÃbØÆ¼{ôqÏT—Ħ /þáy`+påËèGÿjãÈ8cñ¤]”WGTÅ•zÍh6DƒZyuì£È¥o &v€òJe $ª¢ÜT.Äf»_XèðC•ZÄZ§°j¶a4çë#Ìt#ƒu}·Þ"¨Ú!üªSh“¦¤ßø6ܺ´ZxJá½ ¦®ˆ`·w±o¾|ðiW¿hŸ$µ‡uHëªqÒ>0vn5sEŽ{ ½¼ × Œ¢„ºØ"nÊç)Åq\¸„{*@üåÔîéW¼ûfëešá©Q)¤wÙ{uòÓÈÅÿ”> *í¢ü¥ âWÚqÕ8Ž>ÿ17¿ã§áÚ5E˜¼hÏ €4‹)+€(G:UQ*>£È;Ós¾_Íâ Á#®£!½³¼üzê>ß|ìÜ‘Ç. êU eØŽC5­M0W¿†^Eé•3e˜Ê5ó Y‡•Ó e•xeÊÚù’èt:cæ6œêyÁ_’$Ť«ðsãûzä2/t@‰ç5äö·P‡ž@µpA‹Wu¦9ÙCŒ€“Ëz¨`}áŸ!7ŸCv.¹b›Þ»±£´cm¦ÃAöç‚+¨@¨?˜ÜóÔ%Ù3àלB§}ÉŠFÐ^u©øþô«¨N×e¹Y·ö¾ñ÷$MI­E¶61ׯ94O Ú«"Æ V@} ÏÝWØ¿‘]uwyUD‡’J6ð÷^ctå›åž™þEE"‘T«Õ’¶ØxH|ë%êžq˜Œ×ÞgÍGH÷ÔéÏ ïd”k›@4[)—t•‡zøw‘î]ìõï@û,žW§R­Q«Æè†0If¥jÕU; ößüØ~AÓíòyŸª|·È($®9šš Dû57vÀXäæ”1E–‚Ö„YûVn òa’Ók«”*†bxaÆbïn çB è *t1 ñ|WÖ¡[ËS¥c*žaxýûØ'ÿ:l÷†!I’Ì¥’ûó¢ÿyæ?ڽݷ è¡’ÄåÊʟέ»Ï¡ù§¨ê!³¦#„¥5bƒ"%Rg~ å×°¯ÿ¿EµïСžx솃!:¨ÎdS q kMÊÚRP%n²Ç½lFÚAÌȱ}½ê’Y†™(˲(D@´ÎÚÎòÑ”b”Zpîôiˆc´RN1æ ¡Ê ÕnsxyEH¯?ù ‘Q%ÃL°ŽñLP°yifŠ2C߃ÎÛD[oS;þd)ÌA¡ýŠéÏóÿyðPbûÜ~?ÙÀ §#ZåEm"ýë¨Ã@®üÄD€¡ÄwØ‘§QGžÂ¾ô¸(Vi<3äôªæ×>~1©3y:˜U€¼ýb¸‹§Rjãu!¬-Œ” f˜)Â¥ƒb2Èœ\Ð-¸dýJ˜" ,ªTÞ£>ð±cÇx:Û4‹bU„0-ßGíì”ÜÈäK¬Ã&Èæ™dbmæ6ŒÀ¦x|:Œo¾PR€Ü•çÙÀ´ðç™ÿý´"Icâ;? ®†Ef.&By•ÌM=ÂÆ÷.påO‹èÜUý"Tã4úܯ`ßú"2Úš {IŸZïujYDIˆöW²”«¼ƒ$ê`Ç×]JÙ7ngk¯€o÷ï I;“j *9W0×RŒ3“¯3“k³i †òÞ´”þm½N¶,cí¸n_e"g²‹#wŸGù ²ñƒ¡SþŠ‹®¯<ß¹JG Ò̪|SòP ©´QÊŸDþã=ì’W6˜™[Ta-KÝ&LcIv2 Ÿ™õB¶d¯$ºæå»]X=õ5”€—‚IòB¼ #O_Fw:¥Ý~?‰ ÊÐ?¬ENÀ?~©œX̸ƒ’ÌmJ i/ Z•S†œj^˜þqÆePÅ÷{t´K¼óVI‚ `0,V€|Sn.Ê ð:> j&$eXµ+X(3Æn½'? Oþ+—§F»Ð<¼úo‘ö lã4Ûa³gÙÙ²ô†’tN»µÞͰyåvhÔ›—Ô0 IDATáÆOU(À¯Lb³Ý4÷M\01¢³r¶Ö»õ!(ÿ aë°ÃLJÚï¢ïÜy·M“³|Ÿàð!Z/üÕåeÖV—i^µåÈ­Ñ*éM”ÊÆîÊ2ĸµß‡(%ø$Ä›¯Á¹Ï”(c9·szý|÷çÀþYubbÒ݋Ժ‹œÕðJ)ö>ÌqÖ>MAÏ‹A€TjGÁöĹ¿¶R¤£©§Q½žCßü ”ZÁÛ¸‹ÞÚÄó4žШ¼uñïò1>pÚg½}ºW@â¢M¥#çõL4—= ‚§=lÿfÜÁo.BûËÃ31À ߸‹²>º²ŽRéâôƯcŒ×&hŸ)a W®\áë_ÿ:ßÿúKÜ~û ’¬lzßýlJ-ì*šw3Bp»R& ØÌg8»Ò¨Ê2´-KŒ fM‚‡x•†ã”4˜ãëÈÆ&z0¼¿çXj£ŽAgѸµ–dÔEÒƒììvÙ¸}‹ÍÇNó©gÎñà¡Ãx;¯g©.Å4Ec¡,´ï£3Ú+)€çyÄq\X|¥TÙˆÈlÿ`…Bûõ©éû^^€®­ q"ƒw  ðêÕ«|ùË_æ¹ç¾Ëî;—!±ÎüJ>âüA¬Ë"t%Ëßåàèãº~DßKÅnW6É„/®Uw\D5ÜpÙBÐʈ¾‚‰û®TÐJ¡š Lb÷º¨NâµÏ¢‰çAµËËèåe´ï)¡IÆH:vîN)Ò$áú;oÑÙ¼Fo0æWþýœkŸ¬F Â*l`G».Mœ[ÕðQ ¤ý-*k—,Àþó”f`?T˜6ð²E]´*l8¤,hà7_ú*Áê9¶÷züÙŸýßúÖ·èm]CâÚQ-@+7(BÔ¼ é·”ËåÅÜ¢è_1ù<¥Ý.×¾k9‹ îf±„qÃ(üÐm%û¦TÜ.ªT°G`—ÛÈxŒD±ãï¡ ðQÕ*ªREûy1ÆEÓ&aã>¥Âw:›Ðë&|çÛ߯×ðÛŸy?‡k]T´ëJÄÚC… ïÍåŸ(%xXÒ¬Ïq ¸Ðä!•é_wÑ:u}lj°á×PžOXkbã=:7~Ä·Ÿ•ï|óëto¿‰ 7ÝL éIZ»Ñ0,¦nM¸%ÞBO劕#Ê’Ï÷}¯ÊÆÊdŸ­=7pªqÔ›£íÌ(×ߘtA/$KÙÄ6ðÂJûŽ®†H–'ŠeWûªÖÄeá+ÀŒPé 6ãñˆçŸû.ÇŽ¬òkzˆŠºèfʯº´7™ B‚Ö)ft·l2Ùک•ÎX¤v¼ƒÖñ-m"6¦ OA5S;÷‹l\~çþü÷Ù½ó 7Ð’d³}¦2d6 Tf8…‹ ÅûÌnf •“ó{vn¿‚j‡¤ïJlñyJeÝËqÇUí” LµlÔ#îaÒÔYŠŒoª•*®Rg£L2"í"6E{S4w¡â®»gEÑÐévùösßãZ/D5•x:·¼3‹'hcÇ»³™O^Ϙ.O›„lS$âÙï êT™.Õý i<àëw¸rù"b Úkwžð´š‰×Ô‚™;"v. °sX>û»§Ó?oJ‰¨q$£½I^7d`Øâ½¢*§”ÂÓÎØdL2Ø!uYOc¬IÜ•F˜xH:î’÷°Qß1™Lœ>•CTãNF£³Uvïwnßá¯\a䯰˜iÔæhxŒV‰{N1§A¨,ƒ),À~0¦Ã¬—v™Ò>*¬O™6‹ª¯Có£Î]Þzû ÃáÀ-˜WAæ ){ýVà ™;’”vöü1ÐùgÛ’ÅP¥,ßE¾c!'ý¬¥Í+kI …+” ÚÍ`ÙÌ™x4- ’°ã=ÒÑép›t¸íb£='d,ZåPp2Q°Bø“Ætí`8æÒ•ëôM½T$Säñ—_¶„*vϘŒ¼¿ž28èé3gOÓt-Tîïm¦Σ©°Q*Ö(åÃú‡a÷u:cÅ•«×Ý4o9š÷Ñ»(5ßɉù}–Ê8 ‰i%ÈH¥’cõîw ×߈Êw¡˜É™l`4ñžû7’•Åmš¹Ogö=EqéÌ%(•…¤9œšatíe3.Æk¹ ÊØÐ{{{ìŽ(AÁùs¨°1QÜl£*¥\ƒ‰˜ƒ`ÚÌá.Mº €0àWœù/ZW–v7·{‰±­º _9)¤¸é:F”Îjþ÷ÑÒEŠÊÚ»'|Àù—–@AœBAuÍÁ¿Q§àL¿g¢82£Z6Cד`bg=$ê/Ýׄ’¯¥3W³ƒŠ÷ÐIÏmÊÒ„ì)S-ñE¼¢ GtúQ68¢üŒ*¨;3EUû>¯¼‰ryûó‚„’Ï5©ËkÓlŸŠÐáá)ʶ ü~ n±)©Òî|íeé›ç¬…Üà Â×÷T‡Ix÷À¦Þ¯]³©ªºš‘vJXzN=•BÓ÷Q,¤k"Uàü¯aãíòŒ ,ƒ(m"›f€R¾r*gÚ êǵ=I‹LfÒ ã”c¬”„–÷Lè Ž5]/ÿ·LbY$c¹Çˆ¢¢´ëÕ'ô]]Ý›J=Qé]¿æ*[&Ó>“Õ× 2 rÐ+-/ÞÁÌÊlQïã½JÎݰ傯áÝ6±*¹˜¬Å»4ÈiŠ•¨<”×@â]´Î­M:ãsK©§Êý{ö¹"Ίø=T°„ÄwÊð®Wä)ŽHjÍ|…W¸A‰Éf©lÍ+³pñ>W?C Áá3&lQl ªEo½R‚ª´`å$X¤®kÖÏm#„u×gÓL Öž„ád´Y^Ðüó‡VÞˆŸÍHÙ,`îQÈÉFÊ’{º·™)­®:K5§¢ —g½6[ÌY–K&Bw‰f´­h¼=u‰j‰‰3¡ÇS.E¹‰'fäN0ÉÆá8vt|OÅóŒ´ 6³&‘ì… ÷l=–±RSø®cÜØ™Êšò«îyahL±vü:´€Í—fRÒ([HG~8X i9ò_dêò¨*²u€PLÃÚ!×Mí-.)›x’7Ë=îï9¡å#`$còH榯\øä#or¤ršt¹ a ¥}DyÅ0ìÂ%É‚’vÜGFSC£’1¤®¶¡¼ê P4ã¦ÍÔþl@iÔ±h·ûÕt—AVqçúD;åE5ɾ3zìdÚÅŒŒLV×Þ—¿Ï-ç Êš{¢€¥r¯R¨ ãÒ6‹[íßý6-æ —kQYÙ \D?íØ¬™©@(È2[Þµ%ÅUHâˆTÚû YÚ&³gˆ5ØÁF19¥ˆ’¡Ãu‚z #˜Æ{r%˜±å•5ºº„õ+¥Ý®UJµO#w¿_øF¥Ü88r6p±Ë$-)Ï Ï‚&™kæ÷þnîàœ´FÉŒPJe¿çR¾ñ¶s]BáW'eÉLÿœû°sîCeKg¢Â.çéf1:¶”±˜…PUéçh*+sý¶HêEÓ¥åñD=fú-Ó›DèJ«¼i§ßR ×r )…#X¿æ’©¼Vý Ò½‚í]ËR– ½mOš@Õ¾U³âƯæ væ4Ži81Scå@’‡([ŽsÓW]qŒŸ¤?  ¦üj)^™sŠë™º›-ªK9“Ü%ÚeU…ÈS8ÞŸ—uUí›f.n6²äý&F†›Y€XÆDÇèJ{nþ ì4èµaU@yXã2jé,r÷n¼Y2p_õœV@ÛràDÝãpÇé@L‰]hê‹ûR¶È^Di”WqµüÑö̾ó=E{©Íòò­zxàõ"fâ $qæß.:c¨|Ï÷d&);EMUέ„í)Ü” ·Û˜?“k-^µ|lm.Ûé#güRª2õ¦"Öia¬|¬˜ 6´¨µ§þMd¼éؼÉÑv°éº…çÐ4 ÂR.TY¼û÷+Œ*Ѷz÷=C)õ'=õ+—ÆÕuÖbýèÖÖá+K4ì³×°±¹Åööng¾+ÐâL±W3fQSªS˜y.oÑ=‹c?k që.œyfÁ&CÄŽÜDóEa²(¬ ð›Gæ*À´¼ýéZqÞDXR€ú!¬dÔ•¢‚ª}{ñ‹0î9@°Y1…jËѾ=reÈÓ‘¼üY`ó•ûq”º2ÈÔF±Æ5EèlÔŒu±‡â± çyô¡Óœ\«²Rw– 1šîX¸±=æòµ»¼üÊܾs›4M'Áqn…TÅeQ'»µ˜pr¿Heæâ0)bR7ÀÊ«¸ïÈ?ߦ)í`ÍÖ€Ú‹åcý~«|ŽRÞô;]ò÷§]@Î+¹€ú2Êo`Fwðu‚^{Ú»—J ‘rHT>Ó_Û ¬gåòçBÔÁ‹¤½ ŸïÁ!Ì¡dƒ2Öùþñ®›Q¬4gxO}ü#|ø‘#ö·ÐÃËm¢¼©a}©ÉÙëE:¸D%¬¢Ž~{ý/3ô+ ´tì`Ü´ƒ’Cs PU•”˜Â´)e2ìšÅ ™“7´‡2R³êd¼9tÑ-PŠsã·?ÿ,8©ðw^€ñ6JD£P¢oˆ?ÚâPØä“œemõsüAòÒK/¹À5óùÂFºx3Oß³Ü6É)rY¾‘ô¡ºêšYKв€N!Ífksï 5‚^9†6f,Àþ¶¿R˜Ó†Kq€Ò‡"5K9aî^š”M‹™;ÊqñçÌÊOÖ(|âþ‚@WŸ×9mgÆ ¨)?šÿ‡•ˆ;ˆM9~ì8¿öìßãÇbüÍça¼AÖñ$oN;Hc!îâwÞàÑÕ.¿ñ¹ŸçÜÙse JM“Eq ½,ˆ×" 3†žt\agJi¹GæŠé£ìh^(Lj!X9S‚1¥!sqÏs»ýn <ü©®"G?ˆl¾4R•¸¹uj’óKÚsä5½ phù´¬ìð'5ogd¡ò•TÎã›´Aå¬jGQKgPK£Úç\mGøÏûßÿ4Ožðñ;oÀÍdTL´d3òû0cüÁUί%|òc`©Ý˜Ü¢Î2€ ÿŸµX~6Æf’Ž.Âãg)rÊQäDœZSC&¥¬,’MZÇ–ê/V % \=;³ûsÒï1€RŠñx\:ì9\yÖÅ„+è­H•[Ètšnã\Áô‰^y>.)Jæ˜ð‚ì©÷‘6Ë£b$¯MˆÎÐC·ÓUë„+Gï#«Jë 'Wá™ÇN²*·Z©Ü¢OfN™VÓAùµÉ¡”fHÝÞå‘SmŽŸ8F§»7)(Ù8+sï#Ê*wˆTy²Yæ l™å´É”ÏȶP^æ2mù¤3”riûˆ×ά¤Æ ááòÉÒÇFQ„çy3cbf,@Åy@Ø{ïܯテDWS2g!ó0<¤@ÊŸLµš‡âe§͘Ñ9dGç_}—8…K¨¥f…Ÿ™iUYæèÃ?Ç‘µd8ÅŽÕóò÷lÈå¾YFjp‹cÍž:>Á 2 €$¥3…&d’ìŒXL‘SJOª¨~•Ò¬‚RŠl‘x% *l£–ÏcŽ~ÿÜçñ÷€Qáûþ̱³%Èçåsf'ïò©:O¼õª« ,XȼL+yÝ\ùîÌØ Z´¤Å !“Lë&…§]A7—ʧ3µßgõè)jÇŸ.°¥ÍÄbÍQ/1ƒÌ¯fÍ—Ñ]ZþˆÃ‡ÚYËœrÏd³²µ$%!Ï !Óát7òA´7­œ[MG.˜.e¥CTëAôÉ_D?üÛèó_@Ž|˜8îSi*)œ1†$I (­Ó~ÈZÌ5&UBÄí£eŒRI Qˆë¢]z ê£VŸ@×iC܃ …dÝ®2—Ôñ ½J1'°È râI{õŒ’¶8{ðB°tªôQÃá° ³Ðäh çyÅ4‰ƒÆ$ØÞU^{±Ã_VT?zŠcÉeÔæ÷áð3èõÃá`ï|é¼åн4KëÇÙ«<Æ7x‹W^ýéœ/÷ジ¡•^0›é˜¤DWJ¹Quµµ ('ÙîÇEò‰asžQá®G)þ‰Q9t¾ôû~¿_¸t½`˜õBÈ­@¯×ciii27@y4þ<[EÕÄÇ>+OMƼßKö6EÌxB±.دûÒ&›ÎúU“Q¶ƒé\!zèÖ t~Ì‹$î#£ T´ÅËwŸÿ"–_úÐYN×=ØxÛy µú8úÄ/"kÏ Wÿï"“Üåa¾ùÂ_ÿæóìlof.cN‰z?Û!oÉGàå !M˜8AÓTm9Œd|’´4V_¬u©£ògÒG±)iš©6KÿýÒ†±Ö2 ¨V« Íÿ\È•`Ú ôû}–––ŠßW¾Á¿FV[mäê×W©}ÿ½ îC2̲:½°ß_Ä@%C×Dʼ=xÊ"ãM$¨“F G´ÄåL±±±É·¾ó=Z­6«8ASßu³·^Dí½‰:ü!ôÿ‹l|ѰNjoYþòëßæöí;Ùn¶Î[*߇•å‚Û/6žJ ³{ö¼²é·Æ¨Q_s‚oCÜÍØÖÁÔî6s?¹i¡J7ÊGÄa³ÝoðŽœêÑ'gv¿ˆóM3×ó1ˆI:X©Tèt:%® ÒÍ'~q÷Ñ«ÿ/þg×{ðMìFÉJv²¨žís+\ÐÇršNq•×Z‡q›>ž¢Ið”uõ‚©&нN‡‹o_fw¤ÝP‹lL­˜1öê—°oþ;ÔòyâõÏqõÖ·oß.°H‚´Ï ]@Õ¡—B¯œG­<‚ZzÈ¥¥ydžw,åŸàN(owGçvݱsÏ`z]íT]ez°€‰²s-*k/“¤†È[¡uá7gR¿^¯G¥R)òÿw¥ÓÁ`µZ%MSz½^é÷Õæ*~µÍh¡±øÛÏÑûÞÿJÚ»± Raö.A¼“!½…©ÐŸw¡LqáfR«¬óX‰;pZeýÙáÝcÐbc”»QlbÁ ì[ÿÝÁT£*Ën·6N¡VŸ@·²T²8ÔCy!ª²„nŸF-?a;s4hBë”SŠîUd¼íª¡ª\ q´ñt1EÎÆÙ¸<²¹À ÖÄŒbKpúYªGž˜‰ü1…ù?è,ÿ^pjnöööh6›S±€¦ýØØÞ|•ØÜ¡Z Q›ßeð\‡tå Ø¸Í&gH܃ñ&ÊŒ2ü^ðï=_†,âÖ³úš¨AŒs%*§ŽÏ‰š•FëŠï-ƒ?ž0zül4œ®"Ý+0ÞBªëÐЕ•û £)§í3îß§#¨v*:º›‘7q4¹¹Zœ!žóF¹/Ñè*è:b±õIëzô·K÷g­¥ÓéP­V þî[‚  V«±··G§Ó)eÁÒ)ê~‡á«ÿJm‰Šß!C”‰°{—°q”Q²Ó¿u>MÄd>ôÞSœ©”®ÎfJ Ó8‰Ê ö½Z¡<·€øK(?AU3öí¸ë¾Ç«¢¼’^C¬Ák¬¿«äFy!´t”®ñ]H®Ãç `KZ ÙQYF¤«A”0w¨_øØ·Ûíb­½gðwO0íÂ0,”`?e¬yæ“èõ3J5M¼ÃO¡í­$’ ˜4EgE•†9¨ 4Ÿó³¯ò¶]Ì@%ôåJp— üjvÐtPŠÚů¡ë‡y//å…ÎbE;ÙÔï{ÙŽI¥s!Ž(6³>„ F©F¯˜æ™OÎäýÝn—Z­v_»ÿž +AÅ "ÛÛe:²j´ý=ø ‡Cêõ:Aù¿+ŠX Z­R©TØÚÚ*F€æ?‡>òA†¯»1&ó&ÍÛ•Z-8oy6>˜&Ž”@™E ûS²‘°*¨Ï6p†É™}:äÇ})¿‘-¯LмûYf7ÇAR«Ð‡Ÿ¤yú£å8Ùvvv ùÜïî¿o˜Îêõ:ÖZ¶¶¶öÙ>K‡ õ–7`& ·s÷£äCwîkq(S±ò©›²¸¿pºiTë¬â¨½ým™E'4:t‡Bü¸¯©lG²u–¶ )د¸Jc¬ ~‹ÖÙOï› æªž"Røþ{ÿ®`:¨T*4 z½N¹…Ê«¶i]øûXbñ&³t'yMÂÜôÛÅeU±LFÍì«Î-ôŸY­ÇX×縨Ô1¢°Æüø –r‡tZúÿ×#Ïœ2%·xk šGŠãëòW¯×+È;}~lȹaR­V©ÕjlmmÍH+K'ñ›Ç1XtàÜ«Ar*î=õ£­2E 8p1•E:½;½ã5æÖUØ¢7LØÝÙúñå_j‘Ï­@šmˆû „eÁ¡EcT€_[AïÛÙQ±½½M½^/åýïÊP½«7ga¥R¡^¯ãywïÞí(®¶ñÇœÈTÓæA –sâïkLœ889_È"Õ¹—ãð+înlqéê]z¶U:8Ê!ŠU†ú0?ºt›7_ÿÑ+~$éÍ*gÆ––\©$ +IDAT÷™_Jœ…°†¯y ¯Òšñû›››ø¾_2ýê]^á¿ÛGË›GªÕj:ݽ{—cÇŽ•¾Ü«-ãÅë¤Ý«øÚÏ&d<ÒÑi½Ïýq¬Ü;G°{ V !Žc¾õçYZ^æ—>ú­ð6飼*ƒàß¿¸Ç×þò/énîâ/=pÿ ©3°÷Ø5vè°¤úNq°ê@\H”r Já·×ñkË3…²ÍÍMŒ1,--†á=!ߟ˜ìÏ Œ1t»]6779r¤ÜŽì×¹’eÿ&¾¦“:·¿OL6yì^5&eÒûq LÖ«¿¹¹ÉŸ|éË\¿~ƒG/œ§V[&Žb.]~îÿ/ïÚz¢Ø²ð·wÝûF7Ç£xc0a0<¨1¾ùHâ“¿Ô'ÿ‚“ñhLfœÄ3Éƃ7šKWuÕ¾ÌÃÞkwuu àÀ9•Tš‘êZßÞ벿õ-üúò6?}€Î‡ÑÔDsåq¹jð LåN—pô•ÍDxížH#q•vwwÑn·¿ÛïŸå2qENZfsss2a AkŒ{»ïá¡€ÇÜøgG­¦Ža#Ì$ÇÇÒVýk9t@8ìAKŒ%jêdÒ45j¦å|B€àq›Ûÿ:óf¦ï1V¾Ì6¡÷‡œ$ˆêѰ&MZ¾š•ª¥ R!üîüæ• @E~¿f³‰$I¾+ê?3Ô€|Sõ¼`ð3`ÜG±û_h•ÁãÌUëüÚªjÕ¹V~‘Úž6s€NÜ.`käz¬Ð¢14Åñ4øþïf–@µ®Á‹{õŒ'­¡ÄÀ0•6ÀU1Ñ#P/£ÀàŒ¯å%º‹ð*>0½ýÔ³Ùh4ÎÄø§Ååà„1†¯_¿¢(Љ‡óâ)0/@ÑQìÂç @M©Ô¹‚qѵÉiUƸ‡Éùy¬–ovaƳ—³‘:v?º§ÁŽra‘¥ñYæ‰ß1=´Ï)ÐìA -‡¦N¢5 Á[W4®€ûa- …ÈóŒ1·ÕsΑ$ nÞ¼‰v»}æ¶âç€(а¼¼ŒÅÅEw~@_h8Öºà~ˆ°s áôÏAÀ‡Ðž9T²Ê UB&¶Ýv5uÑ53’q ù³‘\Ë>óp†Ù:¾Ñ뮬 ™Ú %¯„éJò›šCÀâ9„ÓK;?ן¶|’q¡º>Qº®^½ŠÕÕÕ1Ùž ½À7pÿþ}lll`gÇô Pô*„À`0péÌxºÈÀƒáÔ Hq2ÝÈwÁ”×l$÷‹ÒÙñæip¤íw¨LkcÎüÛôßð(ÑJ¢¦†@ípb`„¨wb’Z3¨|´ÁâYIžŸÔÆ$åU`lÕS Ç1îÞ½‹¥¥¥Sçü?I’àÁƒxÿþ=ž={†,ËÆ&hH)‘e™#ÖU½ /H Ä äp2݆ûàPv—eÉ zö‘8•ÕÝ+¤×,š6)ßþF’kZÍŸ̴¶|Dª3`Bצ®X%3(x`~<ê»öø¶ÞhRJäyî4hÅW…ïÝ»‡‡މu\ Àõë×±¶¶†4MñòåKçßè¦Ý MS„ɇû¸? ô 󨬑ï*7`Cp0CåR¹«0ÎÀ(Ђ†M÷Ö­f;‹`v ÔÄꯌ±Ñ¶ ¥èa íuÀý6ü¸ /lÕOó,m÷EQ¸BY9Ð+¿ß÷±²²‚µµ5,,,œ›˜>ö ÷ï¿Þ¾}‹'Ožàõë×®gn)%”RŽSÁ1r] -dq5܃*öÀ‚ vÁŠ]û©¾¯¬D½ÖþnAç[õ+“…cÁ ‰/†öYG5{ °+G]xaÃÒÈØ‘†B8½>r‡åUO™T’$X^^ÆãÇqûöíQ¼.$àãÇxúô)ž?Ž~¿ï^ © Ppx< PJo¦|+‘B ûÐT›×…™0¢$Xò“ ö² [+•‚í©¢æ¡ùì` ˜:ƒƒ Sü š¦§à'…´â…N¨ñ°:îܹƒGëÊÿá zÀ›7oðêÕ+¼{÷ëëëØÛÛsF§£å2èÅœhh#ë®ean% yd›5†£Y@Ur)÷lny¾!Šz!˜³aRJ!{š²¡ªá9çh6›˜ŸŸÇÒÒVWW±²²‚8ŽˆM~((ò-ŠÛÛÛVÄ)s'·@@ [kíH©uJW§xšr¢wê‹À+„p®wôìôI»^¯‡n·‹(ŠÎ%Ú¿0(¡<£¨l|6¦”繫‹3Æ3™ÎÄä «ó`0À`0pz|Äž&7F‚€²¿w¢ÍÇhãúCà8à(üh ô²éŒœKÎ+h"ÅÍ,Ë¡„@Y5:ÕðËú¼ÿ/ ^:”PÍhW PÐMYUÒ¢(reçje­ÎåÌ„þýßyž»cYú;d`údìrZWÍé/âu¡Põ¯åø€v‡ò.QH9®p¥æ”ç%Voú àÈèå•]¾/‹Ñ/%Ê+µÕ ¢î®3ð¨ð8™u×v—Éè—‡¹‰ê]gðÃŒ_‚* ê~¦ß¹Ì×¥ÀQ (ïÕÏC_HŰ$cÿip\7r˜ñÿL×ÿíï#Õ>O}SIEND®B`‚aiohttp-security-0.4.0/docs/aiohttp-icon.ico000066400000000000000000000060441335310341200210510ustar00rootroot00000000000000 & ï5‰PNG  IHDR­¿œóÖIDATH‰µTAKA}³Ù¤šÄ¤Ê¶µˆ±…XR#ԤŢ)âÅÜôd/ö/Ôƒ ^—Z((¨)ØŠYH½,Ô¢ ¶P¨±M îª,.1Ÿ5DcÜMµ>v˜ù¾÷ÞÌ~3 % ª*¼^/ˆH˜˜˜xÇïêºî§Ó¹‡•‘‘‘·Œ±1VŠê|‘khhèu}}=87|>E£Ñ"ºÑÚÚjÂáðÇææf…çùÜÊÊJƒ¢(Ö××óµ¢(fWWWí¦Ç599ù¼Ð]GGÇ/"òžÍ#"¾¿¿ÿ[aîÌÌÌÓãéîîÞCÁ‘`FQÞìì,ˆÈò~¿¿8±ÀˆèNuuu¾ §§ç³™!I’ÞŸä;ŽÝ*\çNŒ1lmm š¦å#‘Èw3Ab&á\0 ƒã8<Ï8êw3žçµã/l6²Ù¬»pýlÝÔ4íÇqàv»ør?ðíìì„ØÈårÅc¿O Ȳ|O’¤WËËË º®›™¾•••hjjúÑ××÷´½½]ÆÆÆÆýššKªœ`ŒQ2™|hËd2/‰DðR¶KÀn·÷r»»»®ÿA™LÆÉ•ó z<x½E—º$c§Ûô"ŒŽŽÆUU½¾½½ígY¥««ëL~X(ú äo;`ppP3«ÈYÚa<$“I0Æ@D6UUíVj- ¬­­y†‡‡¿ƒAÆÆÆ>MOOW\™ÌÏÏއ޹¹¹ˆÕ:Ëÿ Þjb:®PåÙâââ¦,ËW/ ë:_XfÆQ×q‚ ü)§¨ÔÕÕm‚ˆü¢(^ùcWUUu@D·Y*•Bmmíµ©©)iiiéI.—»”kŽã¨¥¥e!öîïTy@ª*tIEND®B`‚‰PNG  IHDR szzô¶IDATX…¥—Y¬^UÇkŸ}¦oºßw§¶ôRÚ2Ë<•9„DÐ`|И˜hãƒ/>ˆ1F} M|ðÅÄ$&`BH1†A@ HÓÚ2µRzïíï÷Ýo8ã^>ÚR¡Pã~ÚÉY{­ÿYÓ-QUå ªR§{""ø¾¦ê°g"”ç9Î9Œçáû~¤{—vÁ„Mlk+b<ò¼À¹Ïó°öÃÕËy ,Kò<'Œ"Êá:éÞÑÙ=˜ä~z‰'Eó!EóJJ¿‰œu á®;ðj²4ÅZ‹çyÿ;€4Mñ<Ñ’dïï°À}T,x”#°!2u9¤ëèÊmF ç‘_J|ãwQ[£, Â0ˆC%Ck!b Ô(š-ú%þK?¤ÿò}DQD’$ IâZÁ¾?½þGÄGýj-¨O¡ÖáÞ~žbãåÊk0ZA[ -0M´Q‡æ ·ÑQÉ ñâó ö?DEdYöþ!(Ë’¢(`ýæ±o .‡æ4Œƒ1Ð܆Øö£eÍ)Lm0¨£ƒ9Ô÷)ZÛÐÚ ’÷ðº¯ã›ÑÕý¨â®ýÒ9k-ƘSôû}ÃßßA Ãê£q¨à71ÜÊ~ƒh€ŠAD@UÅm¿¬>ƒßílEÓYw sô)ìâ HÖ#3 jŸ{˜ÑhDÇ'CPA1xåAÂz>D5(— žÁtvcT ˜B‚Ø’>d˨ pÍ­¤ááy·àÿ£»î!ýéo íVÜ–«qµ³ ïæ¯Òù~¬ïS–åII’øöþ ¢)4ƒl5&n i¶PÔ³Hà¡^åO`ZÛ(žx†òñ'!IÑÙ9F?þ áÌU”37 ›wÃÄ嘅gð­=‘ ª::²‡(*Ðá²ùH‡Èäõ¸ÅWAˆ@²4@ZàåP›†Æ‡ Ç)^}ÞÝtÖÖ¡Ÿáò!:šG“eÂ2ú÷Ó'« ( ¬àŽþ\ .¿9ÿ6˜ꓸt\†.AÚ×GÝÉûõ _¥Ì¼‹vÁ;®`¼ƒÆÉ!ïE¥gî <[…ÁfYF\«‘÷æÐ`+F<Êó¾„mnE< £5pé*Ô&E(Ð`+)slãòÞÛø¿Žru·çydbœøëw’ξ‚®€é ÆGƒºóø¾%MlQ Éxu¤1z„"ï!µú)B†–#ˆwVw\Œ‰ÛÈÔe¸£ÏâH\޽ù2짯EŠœ¤7‡·üÞð(ŽáEãó."€s{¢çëxcÛ‘±Øµ×)ƒU‰=4OAB¤XE¥¢[ã9dÓèêkxž"£yÌòS”é,¥+—ãf±qÒ¼öE(àEc0˜*z?É—¹à\Їâ².˜IÜ øØÒ5$)Pô¬ ÝÃ޲·ÍilØÆ›}âÍUwm z ê ®"~·1[é=@D*ííÐÚ„®ÀußFL q Z¬Ð2[ v ø1:8†WAIû/A1¬.ëQtý2s=®û&ž+Ñl‚:Ç«Ïú¾O^*m¬P®„æ&hLÂÒ›Ÿ(&hàLŠ!2¶ wäiÔRkCkÍÖ0þ$_€ ›•,‚¸ ®Bw–2ò‘Öh_AQjÕ’ƒ ö‘]_€Õ}`FEŠ.Zv¡ÜÀu$l@k'Þí@®º Œ›¢ùRå¡bu}ÄFHÜÆ„-µ€dà+ËHc3²åc¤É °žç‘ç9µÉóɽoüì ¿‚d³ç¨XLgàmŸB‚&MäœkÑÅ¿VÜC5†l„ «øJÔ‚lÔ‚g0;?‰çÈ–ö^s7ý¼@DªNhŒÁDmŠÎ¥Èw"^€ÔgÐ` ŽáV÷Á`Žâ•_T=a¸„v`¦®F¢i´ì#>.냴{ 7!W¢ýÃhÿÚ‹¢} ¦6q*:çèv»4‚‚üïß&ºé^t´€>þ5ˆÆ@#®÷Ú¾¬ÜŠ ³Q!Û>ƒ9ëFtþYdöIœtíb-Z, Ý”«¯ÂÍ22“´Z­* {@UñjSd›oÅýí;Ð;‚„ÝX¬J&tÐÚ‚iM€›D‰?FÔ¡;>·ãöêÎý,®XC? µq`þHx6ùy··ÏE6z¯¾Q§ÓaiqúÅ_$!B|‡EB¿J¶r€¸è•(ñ¢&ÄÈønN9c é<")JȈ‘´¨_úeVW–iµZ'ÉèøEDèt:,//S¿îFt©CCT‡xud0LQT<ÄF” ÏŸbß-ÿ b®#£ŒQPûè·X[[£ÝnŸ"{ÊLq³¶Þ£që/†; [ªXÒ ï0¨1P&¨+1oý™t߯ɗö’¼Ž>R½¡Ï0ØIãöèöúDQôžeå}ÇòÁ`À`0`zzšÁ¾û0¯ÿ†0®ãò>¦s1ÚEE¼inÇ-¾ˆØimB×b¦®&™ wþW¨_üÕÊ«õú‰1ìC@µŽ---1>1Ih£7Å~˜¨=¬¿R…aË•èú>6Az'M²æeÈÖ›ˆÏ¾žL-ëk«LLLœvMûÀÕLUév»$IBklŒZ“õf)–žCÓÖ_ª&¥ÚN$láM_E8~!£QÂÆF0 ;úðn ý~Ÿ~¿÷΂ê!ÖVÔ\9y–Q9eYÒh4¨×ë'Jíÿðß`Š¢ Ïó“íqPÖÚ32úîó¨ a Ði,IEND®B`‚aiohttp-security-0.4.0/docs/aiohttp_doctools.py000066400000000000000000000015611335310341200217060ustar00rootroot00000000000000from sphinx.domains.python import PyModulelevel, PyClassmember from sphinx import addnodes 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.4.0/docs/conf.py000066400000000000000000000255611335310341200172630ustar00rootroot00000000000000#!/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 sys import os import codecs import re _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.4.0/docs/example.rst000066400000000000000000000067121335310341200201460ustar00rootroot00000000000000.. _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.4.0/docs/example_db_auth.rst000066400000000000000000000136451335310341200216370ustar00rootroot00000000000000.. _aiohttp-security-example-db-auth: =========================================== Permissions with PostgreSQL-based storage =========================================== Make sure that you have PostgreSQL and Redis servers up and running. 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 -------- Launch these sql scripts to init database and fill it with sample data: ``psql template1 < demo/sql/init_db.sql`` and ``psql template1 < demo/sql/sample_data.sql`` Now you have two tables: - for storing users +--------------+ | users | +==============+ | id | +--------------+ | login | +--------------+ | passwd | +--------------+ | is_superuser | +--------------+ | disabled | +--------------+ - for storing their permissions +-----------------+ | permissions | +=================+ | id | +-----------------+ | user_id | +-----------------+ | permission_name | +-----------------+ Writing policies ---------------- You need to implement two entities: *IdentityPolicy* and *AuthorizationPolicy*. First one should have these methods: *identify*, *remember* and *forget*. For second one: *authorized_userid* and *permits*. We will use built-in *SessionIdentityPolicy* and write our own database-based authorization policy. In our example we will lookup database by user login and if presents then return this identity:: async def authorized_userid(self, identity): async with self.dbengine as conn: where = sa.and_(db.users.c.login == identity, sa.not_(db.users.c.disabled)) query = db.users.count().where(where) ret = await conn.scalar(query) if ret: return identity else: return None For permission checking we will fetch the user first, check if he is superuser (all permissions are allowed), otherwise check if permission is explicitly set for that user:: async def permits(self, identity, permission, context=None): if identity is None: return False async with self.dbengine as conn: where = sa.and_(db.users.c.login == identity, sa.not_(db.users.c.disabled)) query = db.users.select().where(where) ret = await conn.execute(query) user = await ret.fetchone() if user is not None: user_id = user[0] is_superuser = user[3] if is_superuser: return True where = db.permissions.c.user_id == user_id query = db.permissions.select().where(where) ret = await conn.execute(query) result = await ret.fetchall() if ret is not None: for record in result: if record.perm_name == permission: return True return False Setup ----- Once we have all the code in place we can install it for our application:: from aiohttp_session.redis_storage import RedisStorage from aiohttp_security import setup as setup_security from aiohttp_security import SessionIdentityPolicy from aiopg.sa import create_engine from aioredis import create_pool from .db_auth import DBAuthorizationPolicy async def init(loop): redis_pool = await create_pool(('localhost', 6379)) dbengine = await create_engine(user='aiohttp_security', password='aiohttp_security', database='aiohttp_security', host='127.0.0.1') app = web.Application() setup_session(app, RedisStorage(redis_pool)) setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy(dbengine)) return app Now we have authorization and can decorate every other view with access rights based on permissions. There are already implemented two helpers:: from aiohttp_security import check_authorized, check_permission For each view you need to protect - just apply the decorator on it:: class Web: async def protected_page(self, request): await check_permission(request, 'protected') response = web.Response(body=b'You are on protected page') return response or:: class Web: async def logout(self, request): await check_authorized(request) response = web.Response(body=b'You have been logged out') await forget(request, response) return response If someone try to access that protected page he will see:: 403: Forbidden The best part of it - you can implement any logic you want until it follows 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. Similar function may do what you are trying to accomplish:: from passlib.hash import sha256_crypt async def check_credentials(db_engine, username, password): async with db_engine as conn: where = sa.and_(db.users.c.login == username, sa.not_(db.users.c.disabled)) query = db.users.select().where(where) ret = await conn.execute(query) user = await ret.fetchone() if user is not None: hash = user[2] return sha256_crypt.verify(password, hash) return False Final step is to launch your application:: python demo/database_auth/main.py Try to login with admin/moderator/user accounts (with **password** password) and access **/public** or **/protected** endpoints. aiohttp-security-0.4.0/docs/glossary.rst000066400000000000000000000032201335310341200203450ustar00rootroot00000000000000.. _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.4.0/docs/index.rst000066400000000000000000000006441335310341200176200ustar00rootroot00000000000000aiohttp_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.4.0/docs/make.bat000066400000000000000000000161401335310341200173620ustar00rootroot00000000000000@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.4.0/docs/reference.rst000066400000000000000000000177371335310341200204620ustar00rootroot00000000000000.. _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. .. decorator:: login_required Decorator for handlers that checks if user is authorized. Raises :class:`aiohttp.web.HTTPUnauthorized` if user is not authorized. .. deprecated:: 0.3 Use :func:`check_authorized` async function. .. decorator:: has_permission(permission) Decorator for handlers that checks if user is authorized and has correct permission. Raises :class:`aiohttp.web.HTTPUnauthorized` if user is not authorized. Raises :class:`aiohttp.web.HTTPForbidden` if user is authorized but has no access rights. :param str permission: requested :term:`permission`. .. deprecated:: 0.3 Use :func:`check_authorized` async function. 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.4.0/docs/usage.rst000066400000000000000000000121071335310341200176120ustar00rootroot00000000000000.. _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.4.0/requirements-dev.txt000066400000000000000000000004431335310341200210640ustar00rootroot00000000000000-e . flake8==3.5.0 async-timeout==3.0 pytest==3.7.4 pytest-cov==2.5.1 pytest-mock==1.10.0 coverage==4.5.1 sphinx==1.7.8 pep257==0.7.0 aiohttp-session==2.5.1 aiopg[sa]==0.15.0 aioredis==1.1.0 hiredis==0.2.0 passlib==1.7.1 cryptography==2.3.1 aiohttp==3.4.2 pytest-aiohttp==0.3.0 pyjwt==1.6.4 aiohttp-security-0.4.0/setup.cfg000066400000000000000000000000721335310341200166430ustar00rootroot00000000000000[tool:pytest] testpaths = tests filterwarnings= error aiohttp-security-0.4.0/setup.py000066400000000000000000000035351335310341200165430ustar00rootroot00000000000000from setuptools import setup, find_packages import os import re import subprocess import sys from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [] def run(self): errno = subprocess.call([sys.executable, '-m', 'pytest', 'tests']) raise SystemExit(errno) 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.2.0'] 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.txt'))), classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', '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, cmdclass={'test': PyTest}, include_package_data=True, extras_require=extras_require) aiohttp-security-0.4.0/tests/000077500000000000000000000000001335310341200161655ustar00rootroot00000000000000aiohttp-security-0.4.0/tests/conftest.py000066400000000000000000000000201335310341200203540ustar00rootroot00000000000000# nothing to do aiohttp-security-0.4.0/tests/test_cookies_identity.py000066400000000000000000000054431335310341200231510ustar00rootroot00000000000000from aiohttp import web from aiohttp_security import (remember, forget, AbstractAuthorizationPolicy) from aiohttp_security import setup as _setup from aiohttp_security.cookies_identity import CookiesIdentityPolicy from aiohttp_security.api import IDENTITY_KEY class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): pass async def authorized_userid(self, identity): pass async def test_remember(loop, 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(loop, 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(loop, 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.4.0/tests/test_dict_autz.py000066400000000000000000000265301335310341200215720ustar00rootroot00000000000000import enum import pytest from aiohttp import web from aiohttp_security import setup as _setup from aiohttp_security import (AbstractAuthorizationPolicy, authorized_userid, forget, has_permission, is_anonymous, login_required, permits, remember, check_authorized, check_permission) 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(loop, 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(loop, 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(loop, 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(loop, 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(loop, 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_login_required(loop, aiohttp_client): with pytest.raises(DeprecationWarning): @login_required async def index(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_authorized(loop, 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_has_permission(loop, aiohttp_client): with pytest.warns(DeprecationWarning): @has_permission('read') async def index_read(request): return web.Response() @has_permission('write') async def index_write(request): return web.Response() @has_permission('forbid') async def index_forbid(request): return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') return 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 async def test_check_permission(loop, 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.4.0/tests/test_jwt_identity.py000066400000000000000000000043571335310341200223240ustar00rootroot00000000000000import jwt import pytest from aiohttp import web from aiohttp_security import setup as _setup from aiohttp_security import AbstractAuthorizationPolicy 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.jwt', None) with pytest.raises(RuntimeError): JWTIdentityPolicy('secret') async def test_identify(loop, make_token, aiohttp_client): kwt_secret_key = 'Key' 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['login'] 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.decode('utf-8'))} resp = await client.get('/', headers=headers) assert 200 == resp.status async def test_identify_broken_scheme(loop, make_token, aiohttp_client): kwt_secret_key = 'Key' 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=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.decode('utf-8'))} resp = await client.get('/', headers=headers) assert 400 == resp.status assert 'Invalid authorization scheme' in resp.reason aiohttp-security-0.4.0/tests/test_no_auth.py000066400000000000000000000016461335310341200212420ustar00rootroot00000000000000from aiohttp import web from aiohttp_security import authorized_userid, permits async def test_authorized_userid(loop, 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(loop, 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.4.0/tests/test_no_identity.py000066400000000000000000000020161335310341200221220ustar00rootroot00000000000000from aiohttp import web from aiohttp_security import remember, forget async def test_remember(loop, 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 assert (('Security subsystem is not initialized, ' 'call aiohttp_security.setup(...) first') == resp.reason) async def test_forget(loop, 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 assert (('Security subsystem is not initialized, ' 'call aiohttp_security.setup(...) first') == resp.reason) aiohttp-security-0.4.0/tests/test_session_identity.py000066400000000000000000000060471335310341200232010ustar00rootroot00000000000000import pytest from aiohttp import web from aiohttp_security import (remember, forget, AbstractAuthorizationPolicy) from aiohttp_security import setup as setup_security from aiohttp_security.session_identity import SessionIdentityPolicy from aiohttp_security.api import IDENTITY_KEY from aiohttp_session import SimpleCookieStorage, get_session from aiohttp_session import setup as setup_session 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