pax_global_header00006660000000000000000000000064144224374660014526gustar00rootroot0000000000000052 comment=4d01283dff804b6eb92961f3a5188031476861b2 Flask-HTTPAuth-4.8.0/000077500000000000000000000000001442243746600141765ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/.github/000077500000000000000000000000001442243746600155365ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/.github/FUNDING.yml000066400000000000000000000001301442243746600173450ustar00rootroot00000000000000github: miguelgrinberg patreon: miguelgrinberg custom: https://paypal.me/miguelgrinberg Flask-HTTPAuth-4.8.0/.github/workflows/000077500000000000000000000000001442243746600175735ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/.github/workflows/tests.yml000066400000000000000000000024761442243746600214710ustar00rootroot00000000000000name: build on: push: branches: - main pull_request: branches: - main jobs: lint: name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: python -m pip install --upgrade pip wheel - run: pip install tox tox-gh-actions - run: tox -eflake8 - run: tox -edocs tests: name: tests strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] python: ['3.8', '3.9', '3.10', '3.11', 'pypy-3.8'] flask: ['flask<2.3', 'flask>=2.3'] fail-fast: false runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python }} - run: python -m pip install --upgrade pip wheel - run: pip install tox tox-gh-actions - run: tox env: FLASK_VERSION: ${{ matrix.flask }} coverage: name: coverage runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v3 - run: python -m pip install --upgrade pip wheel - run: pip install tox tox-gh-actions - run: tox - uses: codecov/codecov-action@v3 with: files: ./coverage.xml fail_ci_if_error: true Flask-HTTPAuth-4.8.0/.gitignore000066400000000000000000000004531442243746600161700ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject Flask-HTTPAuth-4.8.0/.travis.yml000066400000000000000000000010401442243746600163020ustar00rootroot00000000000000dist: xenial language: python matrix: include: - python: 3.8 env: TOXENV=flake8 - python: 2.7 env: TOXENV=py27 - python: 3.6 env: TOXENV=py36 - python: 3.7 env: TOXENV=py37 - python: 3.8 env: TOXENV=py38 - python: 3.9 env: TOXENV=py39 - python: pypy env: TOXENV=pypy - python: pypy3 env: TOXENV=pypy3 - python: 3.8 env: TOXENV=docs install: - pip install tox script: - tox Flask-HTTPAuth-4.8.0/AUTHORS000066400000000000000000000001401442243746600152410ustar00rootroot00000000000000Miguel Grinberg Henrique Carvalho Alves Flask-HTTPAuth-4.8.0/CHANGES.md000066400000000000000000000453701442243746600156010ustar00rootroot00000000000000# Flask-HTTPAuth change log **Release 4.8.0** - 2023-04-27 - Changes to handle breaking changes in Flask/Werkzeug 2.3 [#160](https://github.com/miguelgrinberg/flask-httpauth/issues/160) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/76548398847fcedc8421a8f4b4c2d12ee16270fe)) - Remove Python 3.6 and 3.7 from builds, add Python 3.11 ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/04399bd2e121f8f0bff34360af74978920ba9096)) - Replace itsdangerous with pyjwt in examples [#157](https://github.com/miguelgrinberg/flask-httpauth/issues/157) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/6f708b09f4d54e48ef1a3501c63867ffb1789077)) - Better documentation for the `get_user_roles` callback argument [#152](https://github.com/miguelgrinberg/flask-httpauth/issues/152) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/03ff9443114ac57cae34dcf0aae39e89985529b0)) (thanks **Taranjeet Singh**!) **Release 4.7.0** - 2022-05-29 - Fallback to latin-1 encoding for credentials when utf-8 fails [#151](https://github.com/miguelgrinberg/flask-httpauth/issues/151) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/4a92b75b79ea8e29ed76910792208d0a0a9e897a)) - Documentation updates ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/b42168ed174cde0a9404dbf0b05b5b5c5d6eb46d)) **Release 4.6.0** - 2022-04-21 - Add MD5-Sess algorithm for Digest auth ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/8a5d1eb87c9b3cb71cc6c5839a4a3411ede1f505)) - Add qop=auth option for Digest auth ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/d311fe5e996d43316989daf8a67ded22a6a567e2)) (thanks **Edward**!) - Add Python 3.10 and PyPy 3.8 to build ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/ffeab170a8230e4defb117f242937865072c8094)) **Release 4.5.0** - 2021-10-25 - Support for Flask 2 async views ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/dc6de2dc9e1203e42d2763a0914e16ce96b74035)) - Do not read the request body [#138](https://github.com/miguelgrinberg/flask-httpauth/issues/138) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/d8b5e37c960263717117ae469f083d65e0f50972)) - Remove unused `flask.g` import in token authentication example [#137](https://github.com/miguelgrinberg/flask-httpauth/issues/137) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/7e5f9cf8167086e23e2d26c5d083a88e2e3b01ac)) (thanks **Jonas Sandström**!) - Fixed documentation typo [#127](https://github.com/miguelgrinberg/flask-httpauth/issues/127) ([commit](https://github.com/miguelgrinberg/flask-httpauth/commit/14fb9d5692bcd04a5679c38b1a3cb54ae38ced21)) (thanks **Reggie V**!) **Release 4.4.0** - 2021-05-13 - Replace `safe_str_cmp` with `hmac.compare_digest` to avoid a deprecation warning from Werkzeug [#126](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/126) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/79e3ebf77f4ad6a56a02996a08c4517f61151d49)) (thanks **Federico Martinez**!) - Drop Python 2 support ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/e690ce56827de9d669718fa5d0fcda63112f8008)) **Release 4.3.0** - 2021-05-01 - Support token auth with custom header in MultiAuth class [#125](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/125) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/6509081c72a2f92c1500b3f09aa063441ea60031)) - Catch `UnicodeDecodeError` when passing malformed data in authorization header [#122](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/122) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/538569f5895834a9f7b8d4dcfd543be6fbfca37e)) (thanks **Bastian Raschke**!) - Fixes typo [#116](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/116) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/9b4659e47b7e05a630f91b7e9471feef5111b503)) (thanks **Renato Oliveira**!) - Move builds to GitHub actions ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/588b277cae820a680199e0acf5a97e2be50c6f6c)) **Release 4.2.0** - 2020-11-16 - Allow error response to return a 200 status code [#114](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/114) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/f3e6a5754e89cda30fa88ef8b9dfa31e1697a688)) - Add optional argument to MultiAuth class [#115](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/115) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/e3c6e5fb0481c14c326460408c2d0d038adf7ddc)) (thanks **pryankster** and **Michael Wright**!) - Remove python 3.5 and add python 3.9 to build ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/507a7c0bfdf7da3bfb6a0cff9624295cf1119986)) **Release 4.1.0** - 2020-06-04 - Basic authentication with custom scheme ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/1aaf872716cb46330fd49e89663da1a568e54f0b)) **Release 4.0.0** - 2020-04-26 - Return user object from verify callbacks ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/51748c24f5aa53175b0f2712b814f7ea581f04e4)) - New role authorization support ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/8178f6dd74dab47b993ba532dd12f0cfdb5799f1)) (thanks **gemerden**!) - Add a custom token authorization header option ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/575b46ade7188152e1b82de84be949bf3f8a300b)) (thanks **Mohamed Feddad**!) - Support an optional=True argument in `login_required` decorator ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/8ecbb1157822360f5bdb24231fd50f25a6247620)) (thanks **Saif Almansoori**!) - Pass HTTP status code to error callback ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/fc8bcd6772b53ef5cc14cd4c6199d63cd2c71f30)) - More secure example of basic auth in the documentation ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/0043e138cd99c7e9fa179ee30ad2283f9b8c704f)) - Fix broken links in CHANGES.md and changelog template [#85](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/85) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/96fafd43c2d0275f2d4042e95faefce24183ec02)) (thanks **Katie Smith**!) **Release 3.3.0** - 2019-05-19 - Use constant time string comparisons [#82](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/82) ([commit1](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/788d42ea9c4d536af628e0e7f4cb1fb84fc59a8e), [commit2](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/97f0e641a6d5eb34054de1ca255e932313d441ee)) (thanks **Brendan Long**!) - Edited and changed the usage of JWT, because in fact the code and documentation uses JWS tokens. [#79](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/79) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/3f743c661e281d728bd2f98af8cca000a975bb8a)) (thanks **unuseless**!) - Documentation fix [#78](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/78) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/c38c52326b78c91d4410f347abcd8bc49cc63ca4)) - Documentation improvements [#77](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/77) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/ce5e5b4c9e8b748eba886ded5180e1e5d5036528)) - helper release script ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/7276d8db4b695645b01f3275addbec10418da63d)) **Release 3.2.4** - 2018-06-17 - Refactored HTTPAuth login_required [#74](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/74) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/68ee1e7a92355ba0f3f9b48c9489a67ab762e106)) (thanks **nestedsoftware**!) - remove incorrect references to JWT in example application [#69](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/69) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/a310b78db2b947ab70f3fc35c1a586d822acc7ca)) - Fix typo in docs [#70](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/70) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/b6457ae5648a50df75f3c40af4b4b3f0155fc25f)) (thanks **Grey Li**!) - Fix documentation [#67](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/67) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/9bd8f4b4f3574c7ef3e2fb9596bc9e9981275011)) (thanks **Eugene Rymarev**!) - correct spelling mistake [#56](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/56) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/f7c5bbd1b3a53080171bbdc5f1f1842f7a825f6a)) (thanks **Edward Betts**!) - travis build fix for py36 ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/6e7f32984bda8b82200793c1b3ec44ff3df3ad2b)) **Release 3.2.3** - 2017-06-05 - Include docs and tests in pypi source tarball [#55](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/55) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/054810ee351148b14571ba0a89ec17a543c35078)) (thanks **Chandan Kumar**!) **Release 3.2.2** - 2017-01-30 - Validate authorization header in multi auth [#51](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/51) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/7a895d676a1b6998f58b61a177286b62dc2872f5)) - index.rst: Add a missing variable in a code snippet [#49](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/49) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/f7fe976bbdc699e8bafaed729dfdd74d2b27d7db)) (thanks **Baptiste Fontaine**!) **Release 3.2.1** - 2016-09-04 - add `__version__` to package ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/d188450987f226568fe0cdee0b6d480b375af64a)) - Add readme and license files to the built package [#45](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/45) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/1c35bec606f147bb23725d6ff3b0411f06828492)) **Release 3.2.0** - 2016-08-20 - Fix TCP Connection reset by peer error [#39](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/39) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/94f6c6d5a4866a43ff4f269eb351dce6232791a2)) (thanks **Joe Kemp**!) **Release 3.1.2** - 2016-04-21 - Add robustness to password check ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/051fd88ee36a21a13255b4ec69e172c9ae4ad46d)) **Release 3.1.1** - 2016-03-24 - pass params to view function in MultiAuth [#36](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/36) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/319974602e55529006b9a8a4fde04ef08e042e83)) (thanks **vovanz**!) - add examples to flake8 build ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/61b1b71b3b29f2936ac6a2077883da1faeaad09f)) - Added multi auth tests ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/c443e7ebcc227fd3690c2cf943d414087d7b931d)) - removed dead code ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/4d2232e2a77f5e10e1731936f4ac64439049b220)) **Release 3.1.0** - 2016-03-13 - examples ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/609806a1c10264818e08ba0ce9b7babeaf101656)) - Added support for multiple authentication methods ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/6c3f94d9eda85b78a8c36cd5e05d6d9836bee2d0)) - Added change log ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/8b427b962114a6ef13badaf8f2f1b396c540955a)) - Add additional token auth test ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/29edb1948f086babbd1a9e0c87a0a35c05f0a63b)) **Release 3.0.2** - 2016-03-12 - Let callback decide what to do when authentication type does not match ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/b942f980970d2e387a80f68de4ea2bb8728b149c)) **Release 3.0.1** - 2016-03-09 - Catching exception when Authorization header is empty ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/88d073e05b56b810feb447d1c9cee7a9a9ac9b1b)) (thanks **Kari Hreinsson**!) - Documentation fix, validate_token() -> verify_token() ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/f4b41d736311638978c95c9b5fd458063a009280)) (thanks **Kari Hreinsson**!) **Release 3.0.0** - 2016-03-07 - documentation for new token auth ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/c0ae42df517a45be87f419cbb7f8002228a1e83c)) - switch travis build to use tox ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/00fdebce667e1dbbc5b342a21804cb6ab3b4f417)) - token auth support, plus test reorg ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/aac866de14c68a4d17d3098f8e96102e837add1d)) - Added explicity Python 2 & 3 version classifiers to package ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/a6f50e7be6f13bb814c47fe8a3a44cd34138f87e)) **Release 2.7.1** - 2016-02-07 - Remove session dependency in authenticate_header [#31](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/31) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/8a84c52d2166e7fdfa26b89dfd2df3340787de94)) (thanks **Paweł Stiasny**!) - Add Install Notes ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/0ff88331c9724999d8f283d79fe95de949e64438)) (thanks **Michael Washburn Jr**!) - Add syntax highlighting to the README [#28](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/28) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/5c058b5165cdbc6a869d68410ef2d25e7802d602)) (thanks **Josh Friend**!) **Release 2.7.0** - 2015-09-20 - Support custom authentication scheme and realm ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/bf12f959bba24a2f3d7d799d1b57ef3a5f1001e8)) **Release 2.6.0** - 2015-08-23 - Added information on how to implement digest authentication securely ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/fb02625ca0f7694d8e744e0b3d2c8d4ffcc4d7cd)) - Allow for custom nonce/opaque generation [#24](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/24) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/ddaa3b6461705d107655c7f87f90d7ba962d2a84)) (thanks **Matt Haggard**!) - fixed tests to work with python 2.6 ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/5e85b27a06285fb5bd591f9f65a8a0bebc4a34f2)) - added travis ci badge ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/ef354fd07abd08137beba6362debdcb4ef23baf6)) **release 2.5.0** - 2015-04-26 - documentation changes ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/5c98ed8370355a60e22e017a79d5575adadb9c07)) - documentation for stored ha1 feature ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/37fd9288abb4f11abf9f93303d1bce4e6cfc3c19)) - Include notes for nginx ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/ed8b4a3c954240cde0c66af3d6dae37df48ba976)) (thanks **Erik Stephens**!) - Include notes for nginx as well ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/5bccbae862cbf1ca7d02f717b076aca86b1456e5)) (thanks **Erik Stephens**!) - Update docs with WSGI notes ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/9ddd55f0bcb793a49675274dc22ae15122a8a1ff)) (thanks **Erik Stephens**!) - Update README with WSGI notes ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/af5fa26dc73d401de7760ba3dcd61828c2e548dd)) (thanks **Erik Stephens**!) - Modified documents and readme for correct import statement [#19](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/19) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/b75737593f3d97b18620440e7e41ee9b71b23f11)) (thanks **Aayush Kasurde**!) **release 2.4.0** - 2015-03-02 - Support anonymous users in verify_password callback ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/5c5396bbb7af540a7aff786ce3282657566045f2)) - Add HA1 generation function to HTTPDigestAuth class ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/4f4aed3ed3fa5e96a1a052e4414f14d1fc49b8bb)) (thanks **Pawel Szczurko**!) - Fix unit test url routes ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/a490a521a17313ce82bfe886912b1620166eb6dd)) (thanks **Pawel Szczurko**!) - Add option to use ha1 combination as password instead of plain text password ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/c84429f541ed0069f40fb901dcb3df44b801c9a5)) (thanks **Pawel Szczurko**!) - removed extra strip() calls in unit tests ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/fc34cc5020168ca3824cc4a740b2010bb3132abf)) **release 2.3.0** - 2014-09-23 - pep8 ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/4657d5b37e50483ecccabf0887ea417d3b94ea0a)) - Fixed problem with couple of decorator that destroy function they decorate [#11](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/11) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/0adf45bec7e5fb04a0e14e13396fd867879026b4)) (thanks **Nemanja Trifunovic**!) - Ignore authentication headers for OPTIONS ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/044b7d4a44425a4b9d02280b80988e8986641a0d)) (thanks **Henrique Carvalho Alves**!) **release 2.2.1** - 2014-03-17 - [#5](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/5): correct handling of None return from get_password callback ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/b94dc8e5fb6c914fdf971085b329bf9ad848a8f5)) - [#5](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/5) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/051195d68d8aaf6d9e53d14d69a59afd84f24821)) - Fixed problem when get_password decorator destroys function it decorates [#4](https://github.com/miguelgrinberg/Flask-HTTPAuth/issues/4) ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/0cbee173e96f8e1a533e7d82b5b1fa1bfce3cd04)) (thanks **Nemanja Trifunovic**!) - custom password verification callback ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/33d60f21a6e64f1b2df24ea5035164110979d8ab)) **version 2.1.0** - 2013-09-28 - pass the username to the hash password callback ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/13075ec4dbe4cb733f4f433e1e25e8a180fce1f6)) **Release 2.0.0** - 2013-09-26 - changed auth.username to auth.username() ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/5168a5f703552ec092e3fef9e087052e35fb6ff0)) - 2.0 documentation update ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/e668f59cb674e45891b7d9548e5af3028f2fd22d)) **Release 1.1.0** - 2013-08-30 - python 3 support ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/c13ff0a4c1e5922a635ea7c877a2ef6079ddb4e6)) - documentation update ([commit](https://github.com/miguelgrinberg/Flask-HTTPAuth/commit/c468e1c084e5c25dcaa85b45e5abeb88fbc09420)) **Release 1.0.0** - 2013-07-27 - First official release! Flask-HTTPAuth-4.8.0/LICENSE000066400000000000000000000020721442243746600152040ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2013 Miguel Grinberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Flask-HTTPAuth-4.8.0/MANIFEST.in000066400000000000000000000001201442243746600157250ustar00rootroot00000000000000include README.md LICENSE recursive-include tests *.py recursive-include docs * Flask-HTTPAuth-4.8.0/README.md000066400000000000000000000041561442243746600154630ustar00rootroot00000000000000Flask-HTTPAuth ============== [![Build status](https://github.com/miguelgrinberg/Flask-HTTPAuth/workflows/build/badge.svg)](https://github.com/miguelgrinberg/Flask-HTTPAuth/actions) [![codecov](https://codecov.io/gh/miguelgrinberg/Flask-HTTPAuth/branch/master/graph/badge.svg?token=KeU2002DHo)](https://codecov.io/gh/miguelgrinberg/Flask-HTTPAuth) Simple extension that provides Basic and Digest HTTP authentication for Flask routes. Installation ------------ The easiest way to install this is through pip. ``` pip install Flask-HTTPAuth ``` Basic authentication example ---------------------------- ```python from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } @auth.verify_password def verify_password(username, password): if username in users and \ check_password_hash(users.get(username), password): return username @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.current_user() if __name__ == '__main__': app.run() ``` Note: See the [documentation](http://pythonhosted.org/Flask-HTTPAuth) for more complex examples that involve password hashing and custom verification callbacks. Digest authentication example ----------------------------- ```python from flask import Flask from flask_httpauth import HTTPDigestAuth app = Flask(__name__) app.config['SECRET_KEY'] = 'secret key here' auth = HTTPDigestAuth() users = { "john": "hello", "susan": "bye" } @auth.get_password def get_pw(username): if username in users: return users.get(username) return None @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.username() if __name__ == '__main__': app.run() ``` Resources --------- - [Documentation](http://flask-httpauth.readthedocs.io/en/latest/) - [PyPI](https://pypi.org/project/Flask-HTTPAuth) - [Change log](https://github.com/miguelgrinberg/Flask-HTTPAuth/blob/master/CHANGES.md) Flask-HTTPAuth-4.8.0/docs/000077500000000000000000000000001442243746600151265ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/Makefile000066400000000000000000000152121442243746600165670ustar00rootroot00000000000000# 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 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 " 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)" 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/Flask-HTTPAuth.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-HTTPAuth.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-HTTPAuth" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-HTTPAuth" @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." 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." Flask-HTTPAuth-4.8.0/docs/_static/000077500000000000000000000000001442243746600165545ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/_static/index.html000077500000000000000000000010461442243746600205550ustar00rootroot00000000000000 Flask-HTTPAuth documentation The Flask-HTTPAuth documentation is available at Read the Docs. If your browser does not automatically redirect you, please click here. Flask-HTTPAuth-4.8.0/docs/_static/logo.png000077500000000000000000000133301442243746600202250ustar00rootroot00000000000000PNG  IHDRx- pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-gAMA|Q cHRMz%u0`:o_F IDATxo!!0!!xB`B a:V>l~*jEeIj-1A > > > > > > > >@b2Y7=g/"'Ddk $&O=?_=?j:>/I&"۞qL)>Q g3X(uSG^GGXY5\f.>.NQZF3y8s`'\ݣ]kv7YL1 S]|ոrچv2k=W{wGxi`yfd|&,'JFqTgvF."?Edqweyt5 n|vTx>w)L)>Z%""R5P~{-8W,d dJY;ۉm]"Lo ^&VYXbϾ"~WJ^42u*fel@X4a}eBh+0bf^%z* |Yga(gF`uծZ,R쮱ux¾5gy g|*=$]{iЬ}:xD G !؀x3L,?;tLi1d|J·)%X64g G| 2֎-t9;ԏ6ҽ)cĢPj6s;@&q]BU8|@ ɮq3d8H1[x,nBj^npAh3I=';wA_s ـPbR=y ڂzD1澶J_(<{o!!<}_K+ -nj1&bhCg@x:9^ZYYN=Y<@/VOׄR&x+yt4Ճe%Ib!< LxcΛ/G*Q+֊o`m>JɩZNaxl;G:acTB.#tqB>X֟|"wlSk@C_oH@C .{fF2Y%־"rWkYk4]@8xZDzw EOLY B Vs} now51ZȻ+:Y/H6ڏH-#z[|4 v6 P)߅d1nՄ  oχeQ ;xTsB VJHau]"i\F֯nW5d8g]}]sY7NB-7>r>=A/ˋlwgV -3 \G F1g`ޏ 6ynü5*ԍQΠΑ=ujA[ 7'zp2 աs'~q[dcX,NIn5DMl++;K/r^ 3UAR {ZZ`qo"׍.ikQϔ)NMO9obE|/y8D? E~BîObױܖ]RJXLlSڲOGցۊ6@. \| 6HeBs݊PwAϜY"074_@|RehQ>"T%\`%]Tv.D\2CC3t!q[e;~`J!zeaqY!>) aX\!Ů`ThYek].=d\ 殲4C+Qua4vՀD5]K:LyuӺَýf8̕9y1=ɒm0ĆEwz w;)nОV|^1g`K7af_rC@):sE_W y u-Txb ??o3zDн[ ,㐠A׾#w7k?0&Z'e `ueD>?㨘,xL:55Mpsw )iw/:+FܞNq,(|#RLXֺX^!ٗrk9cdcM])>vu@|@|@|@|@|@|@|@|3hN_^ IENDB`Flask-HTTPAuth-4.8.0/docs/_themes/000077500000000000000000000000001442243746600165525ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/_themes/LICENSE000077500000000000000000000033751442243746600175720ustar00rootroot00000000000000Copyright (c) 2010 by Armin Ronacher. Some rights reserved. Redistribution and use in source and binary forms of the theme, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. We kindly ask you to only use these themes in an unmodified manner just for Flask and Flask-related products, not for unrelated projects. If you like the visual style and want to use it for your own projects, please consider making some larger changes to the themes (such as changing font faces, sizes, colors or margins). THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Flask-HTTPAuth-4.8.0/docs/_themes/README000077500000000000000000000021051442243746600174330ustar00rootroot00000000000000Flask Sphinx Styles =================== This repository contains sphinx styles for Flask and Flask related projects. To use this style in your Sphinx documentation, follow this guide: 1. put this folder as _themes into your docs folder. Alternatively you can also use git submodules to check out the contents there. 2. add this to your conf.py: sys.path.append(os.path.abspath('_themes')) html_theme_path = ['_themes'] html_theme = 'flask' The following themes exist: - 'flask' - the standard flask documentation theme for large projects - 'flask_small' - small one-page theme. Intended to be used by very small addon libraries for flask. The following options exist for the flask_small theme: [options] index_logo = '' filename of a picture in _static to be used as replacement for the h1 in the index.rst file. index_logo_height = 120px height of the index logo github_fork = '' repository name on github for the "fork me" badge Flask-HTTPAuth-4.8.0/docs/_themes/flask/000077500000000000000000000000001442243746600176525ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/_themes/flask/layout.html000077500000000000000000000012651442243746600220640ustar00rootroot00000000000000{%- extends "basic/layout.html" %} {%- block extrahead %} {{ super() }} {% if theme_touch_icon %} {% endif %} {% endblock %} {%- block relbar2 %}{% endblock %} {% block header %} {{ super() }} {% if pagename == 'index' %}
{% endif %} {% endblock %} {%- block footer %} {% if pagename == 'index' %}
{% endif %} {%- endblock %} Flask-HTTPAuth-4.8.0/docs/_themes/flask/relations.html000077500000000000000000000011161442243746600225420ustar00rootroot00000000000000

Related Topics

Flask-HTTPAuth-4.8.0/docs/_themes/flask/static/000077500000000000000000000000001442243746600211415ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/_themes/flask/static/flasky.css_t000077500000000000000000000215461442243746600235020ustar00rootroot00000000000000/* * flasky.css_t * ~~~~~~~~~~~~ * * :copyright: Copyright 2010 by Armin Ronacher. * :license: Flask Design License, see LICENSE for details. */ {% set page_width = '940px' %} {% set sidebar_width = '220px' %} @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: 'Georgia', serif; font-size: 17px; background-color: white; color: #000; margin: 0; padding: 0; } div.document { width: {{ page_width }}; margin: 30px auto 0 auto; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 0 0 0 {{ sidebar_width }}; } div.sphinxsidebar { width: {{ sidebar_width }}; } hr { border: 1px solid #B1B4B6; } div.body { background-color: #ffffff; color: #3E4349; padding: 0 30px 0 30px; } img.floatingflask { padding: 0 0 10px 10px; float: right; } div.footer { width: {{ page_width }}; margin: 20px auto 30px auto; font-size: 14px; color: #888; text-align: right; } div.footer a { color: #888; } div.related { display: none; } div.sphinxsidebar a { color: #444; text-decoration: none; border-bottom: 1px dotted #999; } div.sphinxsidebar a:hover { border-bottom: 1px solid #999; } div.sphinxsidebar { font-size: 14px; line-height: 1.5; } div.sphinxsidebarwrapper { padding: 18px 10px; } div.sphinxsidebarwrapper p.logo { padding: 0 0 20px 0; margin: 0; text-align: center; } div.sphinxsidebar h3, div.sphinxsidebar h4 { font-family: 'Garamond', 'Georgia', serif; color: #444; font-size: 24px; font-weight: normal; margin: 0 0 5px 0; padding: 0; } div.sphinxsidebar h4 { font-size: 20px; } div.sphinxsidebar h3 a { color: #444; } div.sphinxsidebar p.logo a, div.sphinxsidebar h3 a, div.sphinxsidebar p.logo a:hover, div.sphinxsidebar h3 a:hover { border: none; } div.sphinxsidebar p { color: #555; margin: 10px 0; } div.sphinxsidebar ul { margin: 10px 0; padding: 0; color: #000; } div.sphinxsidebar input { border: 1px solid #ccc; font-family: 'Georgia', serif; font-size: 1em; } /* -- body styles ----------------------------------------------------------- */ a { color: #004B6B; text-decoration: underline; } a:hover { color: #6D4100; text-decoration: underline; } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; margin: 30px 0px 10px 0px; padding: 0; } {% if theme_index_logo %} div.indexwrapper h1 { text-indent: -999999px; background: url({{ theme_index_logo }}) no-repeat center center; height: {{ theme_index_logo_height }}; } {% endif %} div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } div.body h2 { font-size: 180%; } div.body h3 { font-size: 150%; } div.body h4 { font-size: 130%; } div.body h5 { font-size: 100%; } div.body h6 { font-size: 100%; } a.headerlink { color: #ddd; padding: 0 4px; text-decoration: none; } a.headerlink:hover { color: #444; background: #eaeaea; } div.body p, div.body dd, div.body li { line-height: 1.4em; } div.admonition { background: #fafafa; margin: 20px -30px; padding: 10px 30px; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } div.admonition tt.xref, div.admonition a tt { border-bottom: 1px solid #fafafa; } dd div.admonition { margin-left: -60px; padding-left: 60px; } div.admonition p.admonition-title { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; font-size: 24px; margin: 0 0 10px 0; padding: 0; line-height: 1; } div.admonition p.last { margin-bottom: 0; } div.highlight { background-color: white; } dt:target, .highlight { background: #FAF3E8; } div.note { background-color: #eee; border: 1px solid #ccc; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.topic { background-color: #eee; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre, tt { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.9em; } img.screenshot { } tt.descname, tt.descclassname { font-size: 0.95em; } tt.descname { padding-right: 0.08em; } img.screenshot { -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils { border: 1px solid #888; -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils td, table.docutils th { border: 1px solid #888; padding: 0.25em 0.7em; } table.field-list, table.footnote { border: none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } table.footnote { margin: 15px 0; width: 100%; border: 1px solid #eee; background: #fdfdfd; font-size: 0.9em; } table.footnote + table.footnote { margin-top: -15px; border-top: none; } table.field-list th { padding: 0 0.8em 0 0; } table.field-list td { padding: 0; } table.footnote td.label { width: 0px; padding: 0.3em 0 0.3em 0.5em; } table.footnote td { padding: 0.3em 0.5em; } dl { margin: 0; padding: 0; } dl dd { margin-left: 30px; } blockquote { margin: 0 0 0 30px; padding: 0; } ul, ol { margin: 10px 0 10px 30px; padding: 0; } pre { background: #eee; padding: 7px 30px; margin: 15px -30px; line-height: 1.3em; } dl pre, blockquote pre, li pre { margin-left: -60px; padding-left: 60px; } dl dl pre { margin-left: -90px; padding-left: 90px; } tt { background-color: #ecf0f3; color: #222; /* padding: 1px 2px; */ } tt.xref, a tt { background-color: #FBFBFB; border-bottom: 1px solid white; } a.reference { text-decoration: none; border-bottom: 1px dotted #004B6B; } a.reference:hover { border-bottom: 1px solid #6D4100; } a.footnote-reference { text-decoration: none; font-size: 0.7em; vertical-align: top; border-bottom: 1px dotted #004B6B; } a.footnote-reference:hover { border-bottom: 1px solid #6D4100; } a:hover tt { background: #EEE; } @media screen and (max-width: 870px) { div.sphinxsidebar { display: none; } div.document { width: 100%; } div.documentwrapper { margin-left: 0; margin-top: 0; margin-right: 0; margin-bottom: 0; } div.bodywrapper { margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; } ul { margin-left: 0; } .document { width: auto; } .footer { width: auto; } .bodywrapper { margin: 0; } .footer { width: auto; } .github { display: none; } } @media screen and (max-width: 875px) { body { margin: 0; padding: 20px 30px; } div.documentwrapper { float: none; background: white; } div.sphinxsidebar { display: block; float: none; width: 102.5%; margin: 50px -30px -20px -30px; padding: 10px 20px; background: #333; color: white; } div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, div.sphinxsidebar h3 a { color: white; } div.sphinxsidebar a { color: #aaa; } div.sphinxsidebar p.logo { display: none; } div.document { width: 100%; margin: 0; } div.related { display: block; margin: 0; padding: 10px 0 20px 0; } div.related ul, div.related ul li { margin: 0; padding: 0; } div.footer { display: none; } div.bodywrapper { margin: 0; } div.body { min-height: 0; padding: 0; } .rtd_doc_footer { display: none; } .document { width: auto; } .footer { width: auto; } .footer { width: auto; } .github { display: none; } } /* scrollbars */ ::-webkit-scrollbar { width: 6px; height: 6px; } ::-webkit-scrollbar-button:start:decrement, ::-webkit-scrollbar-button:end:increment { display: block; height: 10px; } ::-webkit-scrollbar-button:vertical:increment { background-color: #fff; } ::-webkit-scrollbar-track-piece { background-color: #eee; -webkit-border-radius: 3px; } ::-webkit-scrollbar-thumb:vertical { height: 50px; background-color: #ccc; -webkit-border-radius: 3px; } ::-webkit-scrollbar-thumb:horizontal { width: 50px; background-color: #ccc; -webkit-border-radius: 3px; } /* misc. */ .revsys-inline { display: none!important; }Flask-HTTPAuth-4.8.0/docs/_themes/flask/theme.conf000077500000000000000000000002441442243746600216260ustar00rootroot00000000000000[theme] inherit = basic stylesheet = flasky.css pygments_style = flask_theme_support.FlaskyStyle [options] index_logo = '' index_logo_height = 120px touch_icon = Flask-HTTPAuth-4.8.0/docs/_themes/flask_small/000077500000000000000000000000001442243746600210425ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/_themes/flask_small/layout.html000077500000000000000000000012531442243746600232510ustar00rootroot00000000000000{% extends "basic/layout.html" %} {% block header %} {{ super() }} {% if pagename == 'index' %}
{% endif %} {% endblock %} {% block footer %} {% if pagename == 'index' %}
{% endif %} {% endblock %} {# do not display relbars #} {% block relbar1 %}{% endblock %} {% block relbar2 %} {% if theme_github_fork %} Fork me on GitHub {% endif %} {% endblock %} {% block sidebar1 %}{% endblock %} {% block sidebar2 %}{% endblock %} Flask-HTTPAuth-4.8.0/docs/_themes/flask_small/static/000077500000000000000000000000001442243746600223315ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/docs/_themes/flask_small/static/flasky.css_t000077500000000000000000000110011442243746600246530ustar00rootroot00000000000000/* * flasky.css_t * ~~~~~~~~~~~~ * * Sphinx stylesheet -- flasky theme based on nature theme. * * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: 'Georgia', serif; font-size: 17px; color: #000; background: white; margin: 0; padding: 0; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 40px auto 0 auto; width: 700px; } hr { border: 1px solid #B1B4B6; } div.body { background-color: #ffffff; color: #3E4349; padding: 0 30px 30px 30px; } img.floatingflask { padding: 0 0 10px 10px; float: right; } div.footer { text-align: right; color: #888; padding: 10px; font-size: 14px; width: 650px; margin: 0 auto 40px auto; } div.footer a { color: #888; text-decoration: underline; } div.related { line-height: 32px; color: #888; } div.related ul { padding: 0 0 0 10px; } div.related a { color: #444; } /* -- body styles ----------------------------------------------------------- */ a { color: #004B6B; text-decoration: underline; } a:hover { color: #6D4100; text-decoration: underline; } div.body { padding-bottom: 40px; /* saved for footer */ } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; margin: 30px 0px 10px 0px; padding: 0; } {% if theme_index_logo %} div.indexwrapper h1 { text-indent: -999999px; background: url({{ theme_index_logo }}) no-repeat center center; height: {{ theme_index_logo_height }}; } {% endif %} div.body h2 { font-size: 180%; } div.body h3 { font-size: 150%; } div.body h4 { font-size: 130%; } div.body h5 { font-size: 100%; } div.body h6 { font-size: 100%; } a.headerlink { color: white; padding: 0 4px; text-decoration: none; } a.headerlink:hover { color: #444; background: #eaeaea; } div.body p, div.body dd, div.body li { line-height: 1.4em; } div.admonition { background: #fafafa; margin: 20px -30px; padding: 10px 30px; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; } div.admonition p.admonition-title { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; font-size: 24px; margin: 0 0 10px 0; padding: 0; line-height: 1; } div.admonition p.last { margin-bottom: 0; } div.highlight{ background-color: white; } dt:target, .highlight { background: #FAF3E8; } div.note { background-color: #eee; border: 1px solid #ccc; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.topic { background-color: #eee; } div.warning { background-color: #ffe4e4; border: 1px solid #f66; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre, tt { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.85em; } img.screenshot { } tt.descname, tt.descclassname { font-size: 0.95em; } tt.descname { padding-right: 0.08em; } img.screenshot { -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils { border: 1px solid #888; -moz-box-shadow: 2px 2px 4px #eee; -webkit-box-shadow: 2px 2px 4px #eee; box-shadow: 2px 2px 4px #eee; } table.docutils td, table.docutils th { border: 1px solid #888; padding: 0.25em 0.7em; } table.field-list, table.footnote { border: none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } table.footnote { margin: 15px 0; width: 100%; border: 1px solid #eee; } table.field-list th { padding: 0 0.8em 0 0; } table.field-list td { padding: 0; } table.footnote td { padding: 0.5em; } dl { margin: 0; padding: 0; } dl dd { margin-left: 30px; } pre { padding: 0; margin: 15px -30px; padding: 8px; line-height: 1.3em; padding: 7px 30px; background: #eee; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } dl pre { margin-left: -60px; padding-left: 60px; } tt { background-color: #ecf0f3; color: #222; /* padding: 1px 2px; */ } tt.xref, a tt { background-color: #FBFBFB; } a:hover tt { background: #EEE; } Flask-HTTPAuth-4.8.0/docs/_themes/flask_small/theme.conf000077500000000000000000000002701442243746600230150ustar00rootroot00000000000000[theme] inherit = basic stylesheet = flasky.css nosidebar = true pygments_style = flask_theme_support.FlaskyStyle [options] index_logo = '' index_logo_height = 120px github_fork = '' Flask-HTTPAuth-4.8.0/docs/_themes/flask_theme_support.py000077500000000000000000000114131442243746600232050ustar00rootroot00000000000000# flasky extensions. flasky pygments style based on tango style from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace, Punctuation, Other, Literal class FlaskyStyle(Style): background_color = "#f8f8f8" default_style = "" styles = { # No corresponding class for the following: #Text: "", # class: '' Whitespace: "underline #f8f8f8", # class: 'w' Error: "#a40000 border:#ef2929", # class: 'err' Other: "#000000", # class 'x' Comment: "italic #8f5902", # class: 'c' Comment.Preproc: "noitalic", # class: 'cp' Keyword: "bold #004461", # class: 'k' Keyword.Constant: "bold #004461", # class: 'kc' Keyword.Declaration: "bold #004461", # class: 'kd' Keyword.Namespace: "bold #004461", # class: 'kn' Keyword.Pseudo: "bold #004461", # class: 'kp' Keyword.Reserved: "bold #004461", # class: 'kr' Keyword.Type: "bold #004461", # class: 'kt' Operator: "#582800", # class: 'o' Operator.Word: "bold #004461", # class: 'ow' - like keywords Punctuation: "bold #000000", # class: 'p' # because special names such as Name.Class, Name.Function, etc. # are not recognized as such later in the parsing, we choose them # to look the same as ordinary variables. Name: "#000000", # class: 'n' Name.Attribute: "#c4a000", # class: 'na' - to be revised Name.Builtin: "#004461", # class: 'nb' Name.Builtin.Pseudo: "#3465a4", # class: 'bp' Name.Class: "#000000", # class: 'nc' - to be revised Name.Constant: "#000000", # class: 'no' - to be revised Name.Decorator: "#888", # class: 'nd' - to be revised Name.Entity: "#ce5c00", # class: 'ni' Name.Exception: "bold #cc0000", # class: 'ne' Name.Function: "#000000", # class: 'nf' Name.Property: "#000000", # class: 'py' Name.Label: "#f57900", # class: 'nl' Name.Namespace: "#000000", # class: 'nn' - to be revised Name.Other: "#000000", # class: 'nx' Name.Tag: "bold #004461", # class: 'nt' - like a keyword Name.Variable: "#000000", # class: 'nv' - to be revised Name.Variable.Class: "#000000", # class: 'vc' - to be revised Name.Variable.Global: "#000000", # class: 'vg' - to be revised Name.Variable.Instance: "#000000", # class: 'vi' - to be revised Number: "#990000", # class: 'm' Literal: "#000000", # class: 'l' Literal.Date: "#000000", # class: 'ld' String: "#4e9a06", # class: 's' String.Backtick: "#4e9a06", # class: 'sb' String.Char: "#4e9a06", # class: 'sc' String.Doc: "italic #8f5902", # class: 'sd' - like a comment String.Double: "#4e9a06", # class: 's2' String.Escape: "#4e9a06", # class: 'se' String.Heredoc: "#4e9a06", # class: 'sh' String.Interpol: "#4e9a06", # class: 'si' String.Other: "#4e9a06", # class: 'sx' String.Regex: "#4e9a06", # class: 'sr' String.Single: "#4e9a06", # class: 's1' String.Symbol: "#4e9a06", # class: 'ss' Generic: "#000000", # class: 'g' Generic.Deleted: "#a40000", # class: 'gd' Generic.Emph: "italic #000000", # class: 'ge' Generic.Error: "#ef2929", # class: 'gr' Generic.Heading: "bold #000080", # class: 'gh' Generic.Inserted: "#00A000", # class: 'gi' Generic.Output: "#888", # class: 'go' Generic.Prompt: "#745334", # class: 'gp' Generic.Strong: "bold #000000", # class: 'gs' Generic.Subheading: "bold #800080", # class: 'gu' Generic.Traceback: "bold #a40000", # class: 'gt' } Flask-HTTPAuth-4.8.0/docs/conf.py000066400000000000000000000177501442243746600164370ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Flask-HTTPAuth documentation build configuration file, created by # sphinx-quickstart on Fri Jul 26 14:48:13 2013. # # 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, os # 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.append(os.path.abspath('_themes')) # -- 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.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. 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 = u'Flask-HTTPAuth' copyright = u'2013, Miguel Grinberg' # 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 = '0.7' # The full version, including alpha/beta/rc tags. #release = '0.7.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #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 # -- 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 = 'flask_small' # 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 = { 'index_logo': 'logo.png', 'github_fork': 'miguelgrinberg/Flask-HTTPAuth' } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # 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 = None # 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'] # 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 = {} # 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 # Output file base name for HTML help builder. htmlhelp_basename = 'Flask-HTTPAuthdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Flask-HTTPAuth.tex', u'Flask-HTTPAuth Documentation', u'Miguel Grinberg', '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 = [ ('index', 'flask-httpauth', u'Flask-HTTPAuth Documentation', [u'Miguel Grinberg'], 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 = [ ('index', 'Flask-HTTPAuth', u'Flask-HTTPAuth Documentation', u'Miguel Grinberg', 'Flask-HTTPAuth', '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 Flask-HTTPAuth-4.8.0/docs/index.rst000077500000000000000000000473141442243746600170030ustar00rootroot00000000000000.. Flask-HTTPAuth documentation master file, created by sphinx-quickstart on Fri Jul 26 14:48:13 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Flask-HTTPAuth's documentation! ========================================== **Flask-HTTPAuth** is a Flask extension that simplifies the use of HTTP authentication with Flask routes. Basic authentication examples ----------------------------- The following example application uses HTTP Basic authentication to protect route ``'/'``:: from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } @auth.verify_password def verify_password(username, password): if username in users and \ check_password_hash(users.get(username), password): return username @app.route('/') @auth.login_required def index(): return "Hello, {}!".format(auth.current_user()) if __name__ == '__main__': app.run() The function decorated with the ``verify_password`` decorator receives the username and password sent by the client. If the credentials belong to a user, then the function should return the user object. If the credentials are invalid the function can return ``None`` or ``False``. The user object can then be queried from the ``current_user()`` method of the authentication instance. Digest authentication example ----------------------------- The following example uses HTTP Digest authentication:: from flask import Flask from flask_httpauth import HTTPDigestAuth app = Flask(__name__) app.config['SECRET_KEY'] = 'secret key here' auth = HTTPDigestAuth() users = { "john": "hello", "susan": "bye" } @auth.get_password def get_pw(username): if username in users: return users.get(username) return None @app.route('/') @auth.login_required def index(): return "Hello, {}!".format(auth.username()) if __name__ == '__main__': app.run() Token Authentication Example ---------------------------- The following example application uses a custom HTTP authentication scheme to protect route ``'/'`` with a token:: from flask import Flask from flask_httpauth import HTTPTokenAuth app = Flask(__name__) auth = HTTPTokenAuth(scheme='Bearer') tokens = { "secret-token-1": "john", "secret-token-2": "susan" } @auth.verify_token def verify_token(token): if token in tokens: return tokens[token] @app.route('/') @auth.login_required def index(): return "Hello, {}!".format(auth.current_user()) if __name__ == '__main__': app.run() The ``HTTPTokenAuth`` is a generic authentication handler that can be used with non-standard authentication schemes, with the scheme name given as an argument in the constructor. In the above example, the ``WWW-Authenticate`` header provided by the server will use ``Bearer`` as scheme:: WWW-Authenticate: Bearer realm="Authentication Required" The ``verify_token`` callback receives the authentication credentials provided by the client on the ``Authorization`` header. This can be a simple token, or can contain multiple arguments, which the function will have to parse and extract from the string. As with the ``verify_password``, the function should return the user object if the token is valid. In the examples directory you can find a complete example that uses JWS tokens. JWS tokens are similar to JWT tokens. However using JWT tokens would require an external dependency. Using Multiple Authentication Schemes ------------------------------------- Applications sometimes need to support a combination of authentication methods. For example, a web application could be authenticated by sending client id and secret over basic authentication, while third party API clients use a JWS or JWT bearer token. The `MultiAuth` class allows you to protect a route with more than one authentication object. To grant access to the endpoint, one of the authentication methods must validate. In the examples directory you can find a complete example that uses basic and token authentication. User Roles ---------- Flask-HTTPAuth includes a simple role-based authentication system that can optionally be added to provide an additional layer of granularity in filtering accesses to routes. To enable role support, write a function that returns the list of roles for a given user and decorate it with the ``get_user_roles`` decorator:: @auth.get_user_roles def get_user_roles(user): return user.get_roles() To restrict access to a route to users having a given role, add the ``role`` argument to the ``login_required`` decorator:: @app.route('/admin') @auth.login_required(role='admin') def admins_only(): return "Hello {}, you are an admin!".format(auth.current_user()) The ``role`` argument can take a list of roles, in which case users who have any of the given roles will be granted access:: @app.route('/admin') @auth.login_required(role=['admin', 'moderator']) def admins_only(): return "Hello {}, you are an admin or a moderator!".format(auth.current_user()) In the most advanced usage, users can be filtered by having multiple roles:: @app.route('/admin') @auth.login_required(role=['user', ['moderator', 'contributor']]) def admins_only(): return "Hello {}, you are a user or a moderator/contributor!".format(auth.current_user()) Deployment Considerations ------------------------- Be aware that some web servers do not pass the ``Authorization`` headers to the WSGI application by default. For example, if you use Apache with mod_wsgi, you have to set option ``WSGIPassAuthorization On`` as `documented here `_. Deprecated Basic Authentication Options --------------------------------------- Before the ``verify_password`` described above existed there were other simpler mechanisms for implementing basic authentication. While these are deprecated they are still maintained. However, the ``verify_password`` callback should be preferred as it provides greater security and flexibility. The ``get_password`` callback needs to return the password associated with the username given as argument. Flask-HTTPAuth will allow access only if ``get_password(username) == password``. Example:: @auth.get_password def get_password(username): return get_password_for_username(username) Using this callback alone is in general not a good idea because it requires passwords to be available in plaintext in the server. In the more likely scenario that the passwords are stored hashed in a user database, then an additional callback is needed to define how to hash a password:: @auth.hash_password def hash_pw(password): return hash_password(password) In this example, you have to replace ``hash_password()`` with the specific hashing function used in your application. When the ``hash_password`` callback is provided, access will be granted when ``get_password(username) == hash_password(password)``. If the hashing algorithm requires the username to be known then the callback can take two arguments instead of one:: @auth.hash_password def hash_pw(username, password): salt = get_salt(username) return hash_password(password, salt) API Documentation ----------------- .. module:: flask_httpauth .. class:: HTTPBasicAuth This class handles HTTP Basic authentication for Flask routes. .. method:: __init__(scheme=None, realm=None) Create a basic authentication object. If the optional ``scheme`` argument is provided, it will be used instead of the standard "Basic" scheme in the ``WWW-Authenticate`` response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login. The ``realm`` argument can be used to provide an application defined realm with the ``WWW-Authenticate`` header. .. method:: verify_password(verify_password_callback) If defined, this callback function will be called by the framework to verify that the username and password combination provided by the client are valid. The callback function takes two arguments, the username and the password. It must return the user object if credentials are valid, or ``True`` if a user object is not available. In case of failed authentication, it should return ``None`` or ``False``. Example usage:: @auth.verify_password def verify_password(username, password): user = User.query.filter_by(username).first() if user and passlib.hash.sha256_crypt.verify(password, user.password_hash): return user If this callback is defined, it is also invoked when the request does not have the ``Authorization`` header with user credentials, and in this case both the ``username`` and ``password`` arguments are set to empty strings. The application can opt to return ``True`` in this case and that will allow anonymous users access to the route. The callback function can indicate that the user is anonymous by writing a state variable to ``flask.g`` or by checking if ``auth.current_user()`` is ``None``. Note that when a ``verify_password`` callback is provided the ``get_password`` and ``hash_password`` callbacks are not used. .. method:: get_user_roles(roles_callback) If defined, this callback function will be called by the framework to obtain the roles assigned to a given user. The callback function takes a single argument, the user for which roles are requested. The user object passed to this function will be the one returned by the "verify" callback. If the verify callback returned ``True`` instead of a user object, then the ``Authorization`` object provided by Flask will be passed to this function. The function should return the role or list of roles that belong to the user. Example:: @auth.get_user_roles def get_user_roles(user): return user.get_roles() .. method:: get_password(password_callback) *Deprecated* This callback function will be called by the framework to obtain the password for a given user. Example:: @auth.get_password def get_password(username): return db.get_user_password(username) .. method:: hash_password(hash_password_callback) *Deprecated* If defined, this callback function will be called by the framework to apply a custom hashing algorithm to the password provided by the client. If this callback isn't provided the password will be checked unchanged. The callback can take one or two arguments. The one argument version receives the password to hash, while the two argument version receives the username and the password in that order. Example single argument callback:: @auth.hash_password def hash_password(password): return md5(password).hexdigest() Example two argument callback:: @auth.hash_password def hash_pw(username, password): salt = get_salt(username) return hash(password, salt) .. method:: error_handler(error_callback) If defined, this callback function will be called by the framework when it is necessary to send an authentication error back to the client. The function can take one argument, the status code of the error, which can be 401 (incorrect credentials) or 403 (correct, but insufficient credentials). To preserve compatiiblity with older releases of this package, the function can also be defined without arguments. The return value from this function must by any accepted response type in Flask routes. If this callback isn't provided a default error response is generated. Example:: @auth.error_handler def auth_error(status): return "Access Denied", status .. method:: login_required(view_function_callback) This callback function will be called when authentication is successful. This will typically be a Flask view function. Example:: @app.route('/private') @auth.login_required def private_page(): return "Only for authorized people!" An optional ``role`` argument can be given to further restrict access by roles. Example:: @app.route('/private') @auth.login_required(role='admin') def private_page(): return "Only for admins!" An optional ``optional`` argument can be set to ``True`` to allow the route to execute also when authentication is not included with the request, in which case ``auth.current_user()`` will be set to ``None``. Example:: @app.route('/private') @auth.login_required(optional=True) def private_page(): user = auth.current_user() return "Hello {}!".format(user.name if user is not None else 'anonymous') .. method:: current_user() The user object returned by the ``verify_password`` callback on successful authentication. If no user is returned by the callback, this is set to the username passed by the client. Example:: @app.route('/') @auth.login_required def index(): user = auth.current_user() return "Hello, {}!".format(user.name) .. method:: username() *Deprecated* A view function that is protected with this class can access the logged username through this method. Example:: @app.route('/') @auth.login_required def index(): return "Hello, {}!".format(auth.username()) .. class:: HTTPDigestAuth This class handles HTTP Digest authentication for Flask routes. The ``SECRET_KEY`` configuration must be set in the Flask application to enable the session to work. Flask by default stores user sessions in the client as secure cookies, so the client must be able to handle cookies. .. method:: __init__(self, scheme=None, realm=None, use_ha1_pw=False, qop='auth', algorithm='MD5') Create a digest authentication object. If the optional ``scheme`` argument is provided, it will be used instead of the "Digest" scheme in the ``WWW-Authenticate`` response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login. The ``realm`` argument can be used to provide an application defined realm with the ``WWW-Authenticate`` header. If ``use_ha1_pw`` is False, then the ``get_password`` callback needs to return the plain text password for the given user. If ``use_ha1_pw`` is True, the ``get_password`` callback needs to return the HA1 value for the given user. The advantage of setting ``use_ha1_pw`` to ``True`` is that it allows the application to store the HA1 hash of the password in the user database. The ``qop`` option configures a list of accepted quality of protection extensions. This argument can be given as a comma-separated string, a list of strings, or ``None`` to disable. The default is ``auth``. The ``auth-int`` option is currently not implemented. The ``algorithm`` option configures the hash generation algorithm to use. The default is ``MD5``. The two algorithms that are implemented are ``MD5`` and ``MD5-Sess``. .. method:: generate_ha1(username, password) Generate the HA1 hash that can be stored in the user database when ``use_ha1_pw`` is set to True in the constructor. .. method:: generate_nonce(nonce_making_callback) If defined, this callback function will be called by the framework to generate a nonce. If this is defined, ``verify_nonce`` should also be defined. This can be used to use a state storage mechanism other than the session. .. method:: verify_nonce(nonce_verify_callback) If defined, this callback function will be called by the framework to verify that a nonce is valid. It will be called with a single argument: the nonce to be verified. This can be used to use a state storage mechanism other than the session. .. method:: generate_opaque(opaque_making_callback) If defined, this callback function will be called by the framework to generate an opaque value. If this is defined, ``verify_opaque`` should also be defined. This can be used to use a state storage mechanism other than the session. .. method:: verify_opaque(opaque_verify_callback) If defined, this callback function will be called by the framework to verify that an opaque value is valid. It will be called with a single argument: the opaque value to be verified. This can be used to use a state storage mechanism other than the session. .. method:: get_password(password_callback) See basic authentication for documentation and examples. .. method:: get_user_roles(roles_callback) See basic authentication for documentation and examples. .. method:: error_handler(error_callback) See basic authentication for documentation and examples. .. method:: login_required(view_function_callback) See basic authentication for documentation and examples. .. method:: current_user() See basic authentication for documentation and examples. .. method:: username() See basic authentication for documentation and examples. .. class:: HTTPTokenAuth This class handles HTTP authentication with custom schemes for Flask routes. .. method:: __init__(scheme='Bearer', realm=None, header=None) Create a token authentication object. The ``scheme`` argument can be use to specify the scheme to be used in the ``WWW-Authenticate`` response. The ``Authorization`` header sent by the client must include this scheme followed by the token. Example:: Authorization: Bearer this-is-my-token The ``realm`` argument can be used to provide an application defined realm with the ``WWW-Authenticate`` header. The ``header`` argument can be used to specify a custom header instead of ``Authorization`` from where to obtain the token. If a custom header is used, the ``scheme`` should not be included. Example:: X-API-Key: this-is-my-token .. method:: verify_token(verify_token_callback) This callback function will be called by the framework to verify that the credentials sent by the client with the ``Authorization`` header are valid. The callback function takes one argument, the token provided by the client. The function must return the user object if the token is valid, or ``True`` if a user object is not available. In case of a failed authentication, the function should return ``None`` or ``False``. Example usage:: @auth.verify_token def verify_token(token): return User.query.filter_by(token=token).first() Note that a ``verify_token`` callback is required when using this class. .. method:: get_user_roles(roles_callback) See basic authentication for documentation and examples. .. method:: error_handler(error_callback) See basic authentication for documentation and examples. .. method:: login_required(view_function_callback) See basic authentication for documentation and examples. .. method:: current_user() See basic authentication for documentation and examples. .. class:: HTTPMultiAuth This class handles HTTP authentication with custom schemes for Flask routes. .. method:: __init__(auth_object, ...) Create a multiple authentication object. The arguments are one or more instances of ``HTTPBasicAuth``, ``HTTPDigestAuth`` or ``HTTPTokenAuth``. A route protected with this authentication method will try all the given authentication objects until one succeeds. .. method:: login_required(view_function_callback) See basic authentication for documentation and examples. .. method:: current_user() See basic authentication for documentation and examples. Flask-HTTPAuth-4.8.0/docs/make.bat000066400000000000000000000150751442243746600165430ustar00rootroot00000000000000@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 goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %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 ) 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\Flask-HTTPAuth.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Flask-HTTPAuth.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 %BUILDDIR%/.. 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 %BUILDDIR%/.. 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" == "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 Flask-HTTPAuth-4.8.0/examples/000077500000000000000000000000001442243746600160145ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/examples/basic_auth.py000066400000000000000000000017671442243746600205030ustar00rootroot00000000000000#!/usr/bin/env python """Basic authentication example This example demonstrates how to protect Flask endpoints with basic authentication, using secure hashed passwords. After running this example, visit http://localhost:5000 in your browser. To gain access, you can use (username=john, password=hello) or (username=susan, password=bye). """ from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } @auth.verify_password def verify_password(username, password): if username in users and check_password_hash(users.get(username), password): return username @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.current_user() if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Flask-HTTPAuth-4.8.0/examples/digest_auth.py000066400000000000000000000014121442243746600206640ustar00rootroot00000000000000#!/usr/bin/env python """Digest authentication example This example demonstrates how to protect Flask endpoints with digest authentication. After running this example, visit http://localhost:5000 in your browser. To gain access, you can use (username=john, password=hello) or (username=susan, password=bye). """ from flask import Flask from flask_httpauth import HTTPDigestAuth app = Flask(__name__) app.secret_key = 'this-is-a-secret-key' auth = HTTPDigestAuth(qop='auth') users = { "john": "hello", "susan": "bye", } @auth.get_password def get_password(username): return users.get(username) @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.current_user() if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Flask-HTTPAuth-4.8.0/examples/multi_auth.py000066400000000000000000000032211442243746600205370ustar00rootroot00000000000000#!/usr/bin/env python """Multiple authentication example This example demonstrates how to combine two authentication methods using the "MultiAuth" class. The root URL for this application can be accessed via basic auth, providing username and password, or via token auth, providing a bearer JWS token. This example requires the PyJWT package to be installed. """ from time import time from flask import Flask from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth from werkzeug.security import generate_password_hash, check_password_hash import jwt app = Flask(__name__) app.config['SECRET_KEY'] = 'top secret!' basic_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth('Bearer') multi_auth = MultiAuth(basic_auth, token_auth) users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } for user in users.keys(): token = jwt.encode({'username': user, 'exp': int(time()) + 3600}, app.config['SECRET_KEY'], algorithm='HS256') print('*** token for {}: {}\n'.format(user, token)) @basic_auth.verify_password def verify_password(username, password): if username in users: if check_password_hash(users.get(username), password): return username @token_auth.verify_token def verify_token(token): try: data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']) except: # noqa: E722 return False if 'username' in data: return data['username'] @app.route('/') @multi_auth.login_required def index(): return "Hello, %s!" % multi_auth.current_user() if __name__ == '__main__': app.run() Flask-HTTPAuth-4.8.0/examples/roles_auth.py000066400000000000000000000024101442243746600205300ustar00rootroot00000000000000#!/usr/bin/env python """Basic authentication example This example demonstrates how to protect Flask endpoints with basic authentication, using secure hashed passwords. After running this example, visit http://localhost:5000 in your browser. To gain access, you can use (username=john, password=hello) or (username=susan, password=bye). """ from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye"), } roles = { "john": "user", "susan": ["user", "admin"], } @auth.get_user_roles def get_user_roles(username): return roles.get(username) @auth.verify_password def verify_password(username, password): if username in users and check_password_hash( users.get(username), password): return username @app.route('/') @auth.login_required(role='user') def index(): return "Hello, {}!".format(auth.current_user()) @app.route('/admin') @auth.login_required(role='admin') def admin(): return "Hello {}, you are an admin!".format(auth.current_user()) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Flask-HTTPAuth-4.8.0/examples/token_auth.py000066400000000000000000000027331442243746600205340ustar00rootroot00000000000000#!/usr/bin/env python """Token authentication example This example demonstrates how to protect Flask endpoints with token authentication, using JWT tokens. To use this example you need to install the PyJWT library: pip install pyjwt When this application starts, a token is generated for each of the two users. To gain access, you can use a command line HTTP client such as curl, passing one of the tokens: curl -X GET -H "Authorization: Bearer " http://localhost:5000/ The response should include the username, which is obtained from the token. The tokens have a validity time of one hour, after which they will be rejected. """ from time import time from flask import Flask from flask_httpauth import HTTPTokenAuth import jwt app = Flask(__name__) app.config['SECRET_KEY'] = 'top secret!' auth = HTTPTokenAuth('Bearer') users = ['john', 'susan'] for user in users: token = jwt.encode({'username': user, 'exp': int(time()) + 3600}, app.config['SECRET_KEY'], algorithm='HS256') print('*** token for {}: {}\n'.format(user, token)) @auth.verify_token def verify_token(token): try: data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']) except: # noqa: E722 return False if 'username' in data: return data['username'] @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.current_user() if __name__ == '__main__': app.run() Flask-HTTPAuth-4.8.0/pyproject.toml000066400000000000000000000001501442243746600171060ustar00rootroot00000000000000[build-system] requires = [ "setuptools>=42", "wheel" ] build-backend = "setuptools.build_meta" Flask-HTTPAuth-4.8.0/setup.cfg000066400000000000000000000014471442243746600160250ustar00rootroot00000000000000[metadata] name = Flask-HTTPAuth version = 4.8.0 author = Miguel Grinberg author_email = miguel.grinberg@gmail.com description = HTTP authentication for Flask routes long_description = file: README.md long_description_content_type = text/markdown url = https://github.com/miguelgrinberg/flask-httpauth project_urls = Bug Tracker = https://github.com/miguelgrinberg/flask-httpauth/issues classifiers = Environment :: Web Environment Intended Audience :: Developers Programming Language :: Python :: 3 Programming Language :: Python :: Implementation :: MicroPython License :: OSI Approved :: MIT License Operating System :: OS Independent [options] zip_safe = False include_package_data = True install_requires = flask package_dir = = src py_modules = flask_httpauth Flask-HTTPAuth-4.8.0/setup.py000077500000000000000000000000461442243746600157130ustar00rootroot00000000000000import setuptools setuptools.setup() Flask-HTTPAuth-4.8.0/src/000077500000000000000000000000001442243746600147655ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/src/flask_httpauth.py000066400000000000000000000367341442243746600203750ustar00rootroot00000000000000""" flask_httpauth ================== This module provides Basic and Digest HTTP authentication for Flask routes. :copyright: (C) 2014 by Miguel Grinberg. :license: MIT, see LICENSE for more details. """ import hmac from base64 import b64decode from functools import wraps from hashlib import md5 from random import Random, SystemRandom from flask import request, make_response, session, g, Response, current_app from werkzeug.datastructures import Authorization class HTTPAuth(object): def __init__(self, scheme=None, realm=None, header=None): self.scheme = scheme self.realm = realm or "Authentication Required" self.header = header self.get_password_callback = None self.get_user_roles_callback = None self.auth_error_callback = None def default_get_password(username): return None def default_auth_error(status): return "Unauthorized Access", status self.get_password(default_get_password) self.error_handler(default_auth_error) def is_compatible_auth(self, headers): if self.header is None or self.header == 'Authorization': try: scheme, _ = request.headers.get('Authorization', '').split( None, 1) except ValueError: # malformed Authorization header return False return scheme == self.scheme else: return self.header in headers def get_password(self, f): self.get_password_callback = f return f def get_user_roles(self, f): self.get_user_roles_callback = f return f def error_handler(self, f): @wraps(f) def decorated(*args, **kwargs): res = self.ensure_sync(f)(*args, **kwargs) check_status_code = not isinstance(res, (tuple, Response)) res = make_response(res) if check_status_code and res.status_code == 200: # if user didn't set status code, use 401 res.status_code = 401 if 'WWW-Authenticate' not in res.headers.keys(): res.headers['WWW-Authenticate'] = self.authenticate_header() return res self.auth_error_callback = decorated return decorated def authenticate_header(self): return '{0} realm="{1}"'.format(self.scheme, self.realm) def get_auth(self): auth = None if self.header is None or self.header == 'Authorization': auth = request.authorization if auth is None and \ 'Authorization' in request.headers: # pragma: no cover # Flask/Werkzeug versions before 2.3 do not recognize any # authentication types other than Basic or Digest, so here we # parse the header by hand try: auth_type, token = request.headers['Authorization'].split( None, 1) auth = Authorization(auth_type) auth.token = token except (ValueError, KeyError): # The Authorization header is either empty or has no token pass elif self.header in request.headers: # using a custom header, so the entire value of the header is # assumed to be a token auth = Authorization(self.scheme) auth.token = request.headers[self.header] # if the auth type does not match, we act as if there is no auth # this is better than failing directly, as it allows the callback # to handle special cases, like supporting multiple auth types if auth is not None and auth.type.lower() != self.scheme.lower(): auth = None return auth def get_auth_password(self, auth): password = None if auth and auth.username: password = self.ensure_sync(self.get_password_callback)( auth.username) return password def authorize(self, role, user, auth): if role is None: return True if isinstance(role, (list, tuple)): roles = role else: roles = [role] if user is True: user = auth if self.get_user_roles_callback is None: # pragma: no cover raise ValueError('get_user_roles callback is not defined') user_roles = self.ensure_sync(self.get_user_roles_callback)(user) if user_roles is None: user_roles = {} elif not isinstance(user_roles, (list, tuple)): user_roles = {user_roles} else: user_roles = set(user_roles) for role in roles: if isinstance(role, (list, tuple)): role = set(role) if role & user_roles == role: return True elif role in user_roles: return True def login_required(self, f=None, role=None, optional=None): if f is not None and \ (role is not None or optional is not None): # pragma: no cover raise ValueError( 'role and optional are the only supported arguments') def login_required_internal(f): @wraps(f) def decorated(*args, **kwargs): auth = self.get_auth() # Flask normally handles OPTIONS requests on its own, but in # the case it is configured to forward those to the # application, we need to ignore authentication headers and # let the request through to avoid unwanted interactions with # CORS. if request.method != 'OPTIONS': # pragma: no cover password = self.get_auth_password(auth) status = None user = self.authenticate(auth, password) if user in (False, None): status = 401 elif not self.authorize(role, user, auth): status = 403 if not optional and status: try: return self.auth_error_callback(status) except TypeError: return self.auth_error_callback() g.flask_httpauth_user = user if user is not True \ else auth.username if auth else None return self.ensure_sync(f)(*args, **kwargs) return decorated if f: return login_required_internal(f) return login_required_internal def username(self): auth = self.get_auth() if not auth: return "" return auth.username def current_user(self): if hasattr(g, 'flask_httpauth_user'): return g.flask_httpauth_user def ensure_sync(self, f): try: return current_app.ensure_sync(f) except AttributeError: # pragma: no cover return f class HTTPBasicAuth(HTTPAuth): def __init__(self, scheme=None, realm=None): super(HTTPBasicAuth, self).__init__(scheme or 'Basic', realm) self.hash_password_callback = None self.verify_password_callback = None def hash_password(self, f): self.hash_password_callback = f return f def verify_password(self, f): self.verify_password_callback = f return f def get_auth(self): # this version of the Authorization header parser is more flexible # than Werkzeug's, as it also accepts other schemes besides "Basic" header = self.header or 'Authorization' if header not in request.headers: return None value = request.headers[header].encode('utf-8') try: scheme, credentials = value.split(b' ', 1) encoded_username, encoded_password = b64decode( credentials).split(b':', 1) except (ValueError, TypeError): return None try: username = encoded_username.decode('utf-8') password = encoded_password.decode('utf-8') except UnicodeDecodeError: # try to decode again with latin-1, which should always work username = encoded_username.decode('latin1') password = encoded_password.decode('latin1') return Authorization( scheme, {'username': username, 'password': password}) def authenticate(self, auth, stored_password): if auth: username = auth.username client_password = auth.password else: username = "" client_password = "" if self.verify_password_callback: return self.ensure_sync(self.verify_password_callback)( username, client_password) if not auth: return if self.hash_password_callback: try: client_password = self.ensure_sync( self.hash_password_callback)(client_password) except TypeError: client_password = self.ensure_sync( self.hash_password_callback)(username, client_password) return auth.username if client_password is not None and \ stored_password is not None and \ hmac.compare_digest(client_password, stored_password) else None class HTTPDigestAuth(HTTPAuth): def __init__(self, scheme=None, realm=None, use_ha1_pw=False, qop='auth', algorithm='MD5'): super(HTTPDigestAuth, self).__init__(scheme or 'Digest', realm) self.use_ha1_pw = use_ha1_pw if isinstance(qop, str): self.qop = [v.strip() for v in qop.split(',')] else: self.qop = qop if algorithm.lower() == 'md5': self.algorithm = 'MD5' elif algorithm.lower() == 'md5-sess': self.algorithm = 'MD5-Sess' else: raise ValueError(f'Algorithm {algorithm} is not supported') self.random = SystemRandom() try: self.random.random() except NotImplementedError: # pragma: no cover self.random = Random() self.generate_nonce_callback = None self.verify_nonce_callback = None self.generate_opaque_callback = None self.verify_opaque_callback = None def _generate_random(): return md5(str(self.random.random()).encode('utf-8')).hexdigest() def default_generate_nonce(): session["auth_nonce"] = _generate_random() return session["auth_nonce"] def default_verify_nonce(nonce): session_nonce = session.get("auth_nonce") if nonce is None or session_nonce is None: return False return hmac.compare_digest(nonce, session_nonce) def default_generate_opaque(): session["auth_opaque"] = _generate_random() return session["auth_opaque"] def default_verify_opaque(opaque): session_opaque = session.get("auth_opaque") if opaque is None or session_opaque is None: # pragma: no cover return False return hmac.compare_digest(opaque, session_opaque) self.generate_nonce(default_generate_nonce) self.generate_opaque(default_generate_opaque) self.verify_nonce(default_verify_nonce) self.verify_opaque(default_verify_opaque) def generate_nonce(self, f): self.generate_nonce_callback = f return f def verify_nonce(self, f): self.verify_nonce_callback = f return f def generate_opaque(self, f): self.generate_opaque_callback = f return f def verify_opaque(self, f): self.verify_opaque_callback = f return f def get_nonce(self): return self.generate_nonce_callback() def get_opaque(self): return self.generate_opaque_callback() def generate_ha1(self, username, password): a1 = username + ":" + self.realm + ":" + password a1 = a1.encode('utf-8') return md5(a1).hexdigest() def authenticate_header(self): nonce = self.get_nonce() opaque = self.get_opaque() if self.qop: return ('{0} realm="{1}",nonce="{2}",opaque="{3}",algorithm="{4}"' ',qop="{5}"').format( self.scheme, self.realm, nonce, opaque, self.algorithm, ','.join(self.qop)) else: return '{0} realm="{1}",nonce="{2}",opaque="{3}"'.format( self.scheme, self.realm, nonce, opaque) def authenticate(self, auth, stored_password_or_ha1): if not auth or not auth.username or not auth.realm or not auth.uri \ or not auth.nonce or not auth.response \ or not stored_password_or_ha1: return False if not self.verify_nonce_callback(auth.nonce) or \ not self.verify_opaque_callback(auth.opaque): return False if auth.qop and auth.qop not in self.qop: # pragma: no cover return False if self.use_ha1_pw: ha1 = stored_password_or_ha1 else: a1 = auth.username + ":" + auth.realm + ":" + \ stored_password_or_ha1 ha1 = md5(a1.encode('utf-8')).hexdigest() if self.algorithm == 'MD5-Sess': ha1 = md5((ha1 + ':' + auth.nonce + ':' + auth.cnonce).encode( 'utf-8')).hexdigest() a2 = request.method + ":" + auth.uri ha2 = md5(a2.encode('utf-8')).hexdigest() if auth.qop == 'auth': a3 = ha1 + ":" + auth.nonce + ":" + auth.nc + ":" + \ auth.cnonce + ":auth:" + ha2 else: a3 = ha1 + ":" + auth.nonce + ":" + ha2 response = md5(a3.encode('utf-8')).hexdigest() return hmac.compare_digest(response, auth.response) class HTTPTokenAuth(HTTPAuth): def __init__(self, scheme='Bearer', realm=None, header=None): super(HTTPTokenAuth, self).__init__(scheme, realm, header) self.verify_token_callback = None def verify_token(self, f): self.verify_token_callback = f return f def authenticate(self, auth, stored_password): token = getattr(auth, 'token', '') if self.verify_token_callback: return self.ensure_sync(self.verify_token_callback)(token) class MultiAuth(object): def __init__(self, main_auth, *args): self.main_auth = main_auth self.additional_auth = args def login_required(self, f=None, role=None, optional=None): if f is not None and \ (role is not None or optional is not None): # pragma: no cover raise ValueError( 'role and optional are the only supported arguments') def login_required_internal(f): @wraps(f) def decorated(*args, **kwargs): selected_auth = self.main_auth if not self.main_auth.is_compatible_auth(request.headers): for auth in self.additional_auth: if auth.is_compatible_auth(request.headers): selected_auth = auth break return selected_auth.login_required( role=role, optional=optional)(f)(*args, **kwargs) return decorated if f: return login_required_internal(f) return login_required_internal def current_user(self): if hasattr(g, 'flask_httpauth_user'): # pragma: no cover return g.flask_httpauth_user Flask-HTTPAuth-4.8.0/tests/000077500000000000000000000000001442243746600153405ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/tests/__init__.py000066400000000000000000000000001442243746600174370ustar00rootroot00000000000000Flask-HTTPAuth-4.8.0/tests/test_basic_custom_realm.py000066400000000000000000000045621442243746600226130ustar00rootroot00000000000000import unittest import base64 from flask import Flask from flask_httpauth import HTTPBasicAuth class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_auth_my_realm = HTTPBasicAuth(realm='My Realm') @basic_auth_my_realm.get_password def get_basic_password_2(username): if username == 'john': return 'johnhello' elif username == 'susan': return 'susanbye' else: return None @basic_auth_my_realm.hash_password def basic_auth_my_realm_hash_password(username, password): return username + password @basic_auth_my_realm.error_handler def basic_auth_my_realm_error(): return 'custom error' @app.route('/') def index(): return 'index' @app.route('/basic-with-realm') @basic_auth_my_realm.login_required def basic_auth_my_realm_route(): return 'basic_auth_my_realm:' + basic_auth_my_realm.username() self.app = app self.basic_auth_my_realm = basic_auth_my_realm self.client = app.test_client() def test_basic_auth_prompt(self): response = self.client.get('/basic-with-realm') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="My Realm"') self.assertEqual(response.data.decode('utf-8'), 'custom error') def test_basic_auth_login_valid(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/basic-with-realm', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'basic_auth_my_realm:john') def test_basic_auth_login_invalid(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/basic-with-realm', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="My Realm"') Flask-HTTPAuth-4.8.0/tests/test_basic_get_password.py000066400000000000000000000043501442243746600226150ustar00rootroot00000000000000import unittest import base64 from flask import Flask from flask_httpauth import HTTPBasicAuth class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_auth = HTTPBasicAuth() @basic_auth.get_password def get_basic_password(username): if username == 'john': return 'hello' elif username == 'susan': return 'bye' else: return None @app.route('/') def index(): return 'index' @app.route('/basic') @basic_auth.login_required def basic_auth_route(): return 'basic_auth:' + basic_auth.username() self.app = app self.basic_auth = basic_auth self.client = app.test_client() def test_no_auth(self): response = self.client.get('/') self.assertEqual(response.data.decode('utf-8'), 'index') def test_basic_auth_prompt(self): response = self.client.get('/basic') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_basic_auth_ignore_options(self): response = self.client.options('/basic') self.assertEqual(response.status_code, 200) self.assertTrue('WWW-Authenticate' not in response.headers) def test_basic_auth_login_valid(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/basic', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'basic_auth:john') def test_basic_auth_login_invalid(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/basic', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') Flask-HTTPAuth-4.8.0/tests/test_basic_hashed_password.py000066400000000000000000000042471442243746600232770ustar00rootroot00000000000000import unittest import base64 from hashlib import md5 as basic_md5 from flask import Flask from flask_httpauth import HTTPBasicAuth def md5(s): if isinstance(s, str): s = s.encode('utf-8') return basic_md5(s) class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_custom_auth = HTTPBasicAuth() @basic_custom_auth.get_password def get_basic_custom_auth_get_password(username): if username == 'john': return md5('hello').hexdigest() elif username == 'susan': return md5('bye').hexdigest() else: return None @basic_custom_auth.hash_password def basic_custom_auth_hash_password(password): return md5(password).hexdigest() @app.route('/') def index(): return 'index' @app.route('/basic-custom') @basic_custom_auth.login_required def basic_custom_auth_route(): return 'basic_custom_auth:' + basic_custom_auth.username() self.app = app self.basic_custom_auth = basic_custom_auth self.client = app.test_client() def test_basic_auth_login_valid_with_hash1(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/basic-custom', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'basic_custom_auth:john') def test_basic_custom_auth_login_valid(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/basic-custom', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'basic_custom_auth:john') def test_basic_custom_auth_login_invalid(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/basic-custom', headers={"Authorization": "Basic " + creds}) self.assertEqual(response.status_code, 401) self.assertTrue("WWW-Authenticate" in response.headers) Flask-HTTPAuth-4.8.0/tests/test_basic_verify_password.py000066400000000000000000000072451442243746600233500ustar00rootroot00000000000000import unittest import base64 from flask import Flask, g from flask_httpauth import HTTPBasicAuth class HTTPAuthTestCase(unittest.TestCase): use_old_style_callback = False def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_verify_auth = HTTPBasicAuth() @basic_verify_auth.verify_password def basic_verify_auth_verify_password(username, password): if self.use_old_style_callback: g.anon = False if username == 'john': return password == 'hello' elif username == 'susan': return password == 'bye' elif username == 'garçon': return password == 'áéíóú' elif username == '': g.anon = True return True return False else: g.anon = False if username == 'john' and password == 'hello': return 'john' elif username == 'susan' and password == 'bye': return 'susan' elif username == 'garçon' and password == 'áéíóú': return 'garçon' elif username == '': g.anon = True return '' @basic_verify_auth.error_handler def error_handler(): self.assertIsNone(basic_verify_auth.current_user()) return 'error', 403 # use a custom error status @app.route('/') def index(): return 'index' @app.route('/basic-verify') @basic_verify_auth.login_required def basic_verify_auth_route(): if self.use_old_style_callback: return 'basic_verify_auth:' + basic_verify_auth.username() + \ ' anon:' + str(g.anon) else: return 'basic_verify_auth:' + \ basic_verify_auth.current_user() + ' anon:' + str(g.anon) self.app = app self.basic_verify_auth = basic_verify_auth self.client = app.test_client() def test_verify_auth_login_valid(self): creds = base64.b64encode(b'susan:bye').decode() response = self.client.get( '/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'basic_verify_auth:susan anon:False') def test_verify_auth_login_valid_latin1(self): creds = base64.b64encode('garçon:áéíóú'.encode('latin1')).decode() response = self.client.get( '/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode(), 'basic_verify_auth:garçon anon:False') def test_verify_auth_login_empty(self): response = self.client.get('/basic-verify') self.assertEqual(response.data, b'basic_verify_auth: anon:True') def test_verify_auth_login_invalid(self): creds = base64.b64encode(b'john:bye').decode() response = self.client.get( '/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_malformed_password(self): creds = 'eyJhbGciOieyJp==' response = self.client.get('/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) class HTTPAuthTestCaseOldStyle(HTTPAuthTestCase): use_old_style_callback = True Flask-HTTPAuth-4.8.0/tests/test_basic_verify_password_async.py000066400000000000000000000063751442243746600245500ustar00rootroot00000000000000import sys import unittest import base64 from flask import Flask, g from flask_httpauth import HTTPBasicAuth import pytest @pytest.mark.skipif(sys.version_info < (3, 7), reason='requires python3.7') class HTTPAuthTestCase(unittest.TestCase): use_old_style_callback = False def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_verify_auth = HTTPBasicAuth() @basic_verify_auth.verify_password async def basic_verify_auth_verify_password(username, password): if self.use_old_style_callback: g.anon = False if username == 'john': return password == 'hello' elif username == 'susan': return password == 'bye' elif username == '': g.anon = True return True return False else: g.anon = False if username == 'john' and password == 'hello': return 'john' elif username == 'susan' and password == 'bye': return 'susan' elif username == '': g.anon = True return '' @basic_verify_auth.error_handler async def error_handler(): self.assertIsNone(basic_verify_auth.current_user()) return 'error', 403 # use a custom error status @app.route('/') async def index(): return 'index' @app.route('/basic-verify') @basic_verify_auth.login_required async def basic_verify_auth_route(): if self.use_old_style_callback: return 'basic_verify_auth:' + basic_verify_auth.username() + \ ' anon:' + str(g.anon) else: return 'basic_verify_auth:' + \ basic_verify_auth.current_user() + ' anon:' + str(g.anon) self.app = app self.basic_verify_auth = basic_verify_auth self.client = app.test_client() def test_verify_auth_login_valid(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'basic_verify_auth:susan anon:False') def test_verify_auth_login_empty(self): response = self.client.get('/basic-verify') self.assertEqual(response.data, b'basic_verify_auth: anon:True') def test_verify_auth_login_invalid(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_malformed_password(self): creds = 'eyJhbGciOieyJp==' response = self.client.get('/basic-verify', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) class HTTPAuthTestCaseOldStyle(HTTPAuthTestCase): use_old_style_callback = True Flask-HTTPAuth-4.8.0/tests/test_digest_custom_realm.py000066400000000000000000000042601442243746600230040ustar00rootroot00000000000000import unittest import re from flask import Flask from flask_httpauth import HTTPDigestAuth class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' digest_auth_my_realm = HTTPDigestAuth(realm='My Realm', qop=None) @digest_auth_my_realm.get_password def get_digest_password_3(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @app.route('/') def index(): return 'index' @app.route('/digest-with-realm') @digest_auth_my_realm.login_required def digest_auth_my_realm_route(): return 'digest_auth_my_realm:' + digest_auth_my_realm.username() self.app = app self.client = app.test_client() def test_digest_auth_prompt_with_custom_realm(self): response = self.client.get('/digest-with-realm') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="My Realm",' 'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$', response.headers['WWW-Authenticate'])) def test_digest_auth_login_invalid(self): response = self.client.get( '/digest-with-realm', headers={ "Authorization": 'Digest username="susan",' 'realm="My Realm",' 'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",' 'uri="/digest-with-realm",' 'response="ca306c361a9055b968810067a37fb8cb",' 'opaque="5ccc069c403ebaf9f0171e9517f40e41"'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="My Realm",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$', response.headers['WWW-Authenticate'])) Flask-HTTPAuth-4.8.0/tests/test_digest_get_password.py000066400000000000000000000243561442243746600230230ustar00rootroot00000000000000import unittest import re import pytest from hashlib import md5 as basic_md5 from flask import Flask from flask_httpauth import HTTPDigestAuth from werkzeug.http import parse_dict_header def md5(str): if type(str).__name__ == 'str': str = str.encode('utf-8') return basic_md5(str) def get_ha1(user, pw, realm): a1 = user + ":" + realm + ":" + pw return md5(a1).hexdigest() class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' digest_auth = HTTPDigestAuth() @digest_auth.get_password def get_digest_password_2(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @app.route('/') def index(): return 'index' @app.route('/digest') @digest_auth.login_required def digest_auth_route(): return 'digest_auth:' + digest_auth.username() self.app = app self.digest_auth = digest_auth self.client = app.test_client() def test_constructor(self): d = HTTPDigestAuth() assert d.qop == ['auth'] assert d.algorithm == 'MD5' d = HTTPDigestAuth(qop=None) assert d.qop is None d = HTTPDigestAuth(qop='auth') assert d.qop == ['auth'] d = HTTPDigestAuth(qop=['foo', 'bar']) assert d.qop == ['foo', 'bar'] d = HTTPDigestAuth(qop='foo,bar, baz') assert d.qop == ['foo', 'bar', 'baz'] d = HTTPDigestAuth(algorithm='md5') assert d.algorithm == 'MD5' d = HTTPDigestAuth(algorithm='md5-sess') assert d.algorithm == 'MD5-Sess' with pytest.raises(ValueError): HTTPDigestAuth(algorithm='foo') def test_digest_auth_prompt(self): response = self.client.get('/digest') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="Authentication Required",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+",' r'algorithm="MD5",qop="auth"$', response.headers['WWW-Authenticate'])) def test_digest_auth_ignore_options(self): response = self.client.options('/digest') self.assertEqual(response.status_code, 200) self.assertTrue('WWW-Authenticate' not in response.headers) def test_digest_auth_login_valid(self): response = self.client.get('/digest') self.assertTrue(response.status_code == 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'john:' + d['realm'] + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':00000001:foobar:auth:' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",qop=auth,' 'nc=00000001,cnonce="foobar",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.data, b'digest_auth:john') def test_digest_auth_md5_sess_login_valid(self): self.digest_auth.algorithm = 'MD5-Sess' response = self.client.get('/digest') self.assertTrue(response.status_code == 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'john:' + d['realm'] + ':bye' ha1 = md5( md5(a1).hexdigest() + ':' + d['nonce'] + ':foobar').hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':00000001:foobar:auth:' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",qop=auth,' 'nc=00000001,cnonce="foobar",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.data, b'digest_auth:john') def test_digest_auth_login_bad_realm(self): response = self.client.get('/digest') self.assertTrue(response.status_code == 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'john:' + 'Wrong Realm' + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':00000001:foobar:auth:' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",qop=auth,' 'nc=00000001,cnonce="foobar",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="Authentication Required",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+",' r'algorithm="MD5",qop="auth"$', response.headers['WWW-Authenticate'])) def test_digest_auth_login_invalid2(self): response = self.client.get('/digest') self.assertEqual(response.status_code, 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'david:' + 'Authentication Required' + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':00000001:foobar:auth:' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",qop=auth,' 'nc=00000001,cnonce="foobar",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="Authentication Required",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+",' r'algorithm="MD5",qop="auth"$', response.headers['WWW-Authenticate'])) def test_digest_generate_ha1(self): ha1 = self.digest_auth.generate_ha1('pawel', 'test') ha1_expected = get_ha1('pawel', 'test', self.digest_auth.realm) self.assertEqual(ha1, ha1_expected) def test_digest_custom_nonce_checker(self): @self.digest_auth.generate_nonce def noncemaker(): return 'not a good nonce' @self.digest_auth.generate_opaque def opaquemaker(): return 'some opaque' verify_nonce_called = [] @self.digest_auth.verify_nonce def verify_nonce(provided_nonce): verify_nonce_called.append(provided_nonce) return True verify_opaque_called = [] @self.digest_auth.verify_opaque def verify_opaque(provided_opaque): verify_opaque_called.append(provided_opaque) return True response = self.client.get('/digest') self.assertEqual(response.status_code, 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) self.assertEqual(d['nonce'], 'not a good nonce') self.assertEqual(d['opaque'], 'some opaque') a1 = 'john:' + d['realm'] + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':00000001:foobar:auth:' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",qop=auth,' 'nc=00000001,cnonce="foobar",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.data, b'digest_auth:john') self.assertEqual(verify_nonce_called, ['not a good nonce'], "Should have verified the nonce.") self.assertEqual(verify_opaque_called, ['some opaque'], "Should have verified the opaque.") Flask-HTTPAuth-4.8.0/tests/test_digest_ha1_password.py000066400000000000000000000045711442243746600227120ustar00rootroot00000000000000import unittest from hashlib import md5 as basic_md5 from flask import Flask from flask_httpauth import HTTPDigestAuth from werkzeug.http import parse_dict_header def md5(str): if type(str).__name__ == 'str': str = str.encode('utf-8') return basic_md5(str) def get_ha1(user, pw, realm): a1 = user + ":" + realm + ":" + pw return md5(a1).hexdigest() class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' digest_auth_ha1_pw = HTTPDigestAuth(use_ha1_pw=True) @digest_auth_ha1_pw.get_password def get_digest_password(username): if username == 'susan': return get_ha1(username, 'hello', digest_auth_ha1_pw.realm) elif username == 'john': return get_ha1(username, 'bye', digest_auth_ha1_pw.realm) else: return None @app.route('/') def index(): return 'index' @app.route('/digest_ha1_pw') @digest_auth_ha1_pw.login_required def digest_auth_ha1_pw_route(): return 'digest_auth_ha1_pw:' + digest_auth_ha1_pw.username() self.app = app self.client = app.test_client() def test_digest_ha1_pw_auth_login_valid(self): response = self.client.get('/digest_ha1_pw') self.assertTrue(response.status_code == 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'john:' + d['realm'] + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest_ha1_pw' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest_ha1_pw', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest_ha1_pw",' 'response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.data, b'digest_auth_ha1_pw:john') Flask-HTTPAuth-4.8.0/tests/test_digest_no_qop.py000066400000000000000000000173461442243746600216160ustar00rootroot00000000000000import unittest import re from hashlib import md5 as basic_md5 from flask import Flask from flask_httpauth import HTTPDigestAuth from werkzeug.http import parse_dict_header def md5(str): if type(str).__name__ == 'str': str = str.encode('utf-8') return basic_md5(str) def get_ha1(user, pw, realm): a1 = user + ":" + realm + ":" + pw return md5(a1).hexdigest() class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' digest_auth = HTTPDigestAuth(qop=None) @digest_auth.get_password def get_digest_password_2(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @app.route('/') def index(): return 'index' @app.route('/digest') @digest_auth.login_required def digest_auth_route(): return 'digest_auth:' + digest_auth.username() self.app = app self.digest_auth = digest_auth self.client = app.test_client() def test_digest_auth_prompt(self): response = self.client.get('/digest') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="Authentication Required",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$', response.headers['WWW-Authenticate'])) def test_digest_auth_ignore_options(self): response = self.client.options('/digest') self.assertEqual(response.status_code, 200) self.assertTrue('WWW-Authenticate' not in response.headers) def test_digest_auth_login_valid(self): response = self.client.get('/digest') self.assertTrue(response.status_code == 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'john:' + d['realm'] + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.data, b'digest_auth:john') def test_digest_auth_login_bad_realm(self): response = self.client.get('/digest') self.assertTrue(response.status_code == 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'john:' + 'Wrong Realm' + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="Authentication Required",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$', response.headers['WWW-Authenticate'])) def test_digest_auth_login_invalid2(self): response = self.client.get('/digest') self.assertEqual(response.status_code, 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) a1 = 'david:' + 'Authentication Required' + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="david",realm="{0}",' 'nonce="{1}",uri="/digest",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue(re.match(r'^Digest realm="Authentication Required",' r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$', response.headers['WWW-Authenticate'])) def test_digest_generate_ha1(self): ha1 = self.digest_auth.generate_ha1('pawel', 'test') ha1_expected = get_ha1('pawel', 'test', self.digest_auth.realm) self.assertEqual(ha1, ha1_expected) def test_digest_custom_nonce_checker(self): @self.digest_auth.generate_nonce def noncemaker(): return 'not a good nonce' @self.digest_auth.generate_opaque def opaquemaker(): return 'some opaque' verify_nonce_called = [] @self.digest_auth.verify_nonce def verify_nonce(provided_nonce): verify_nonce_called.append(provided_nonce) return True verify_opaque_called = [] @self.digest_auth.verify_opaque def verify_opaque(provided_opaque): verify_opaque_called.append(provided_opaque) return True response = self.client.get('/digest') self.assertEqual(response.status_code, 401) header = response.headers.get('WWW-Authenticate') auth_type, auth_info = header.split(None, 1) d = parse_dict_header(auth_info) self.assertEqual(d['nonce'], 'not a good nonce') self.assertEqual(d['opaque'], 'some opaque') a1 = 'john:' + d['realm'] + ':bye' ha1 = md5(a1).hexdigest() a2 = 'GET:/digest' ha2 = md5(a2).hexdigest() a3 = ha1 + ':' + d['nonce'] + ':' + ha2 auth_response = md5(a3).hexdigest() response = self.client.get( '/digest', headers={ 'Authorization': 'Digest username="john",realm="{0}",' 'nonce="{1}",uri="/digest",response="{2}",' 'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response, d['opaque'])}) self.assertEqual(response.data, b'digest_auth:john') self.assertEqual(verify_nonce_called, ['not a good nonce'], "Should have verified the nonce.") self.assertEqual(verify_opaque_called, ['some opaque'], "Should have verified the opaque.") Flask-HTTPAuth-4.8.0/tests/test_error_responses.py000066400000000000000000000025131442243746600222040ustar00rootroot00000000000000import unittest import base64 from flask import Flask, Response from flask_httpauth import HTTPBasicAuth class HTTPAuthTestCase(unittest.TestCase): responses = [ ['error', 401], [('error', 403), 403], [('error', 200), 200], [Response('error'), 200], [Response('error', 403), 403], ] def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_verify_auth = HTTPBasicAuth() @basic_verify_auth.verify_password def basic_verify_auth_verify_password(username, password): return False @basic_verify_auth.error_handler def error_handler(): self.assertIsNone(basic_verify_auth.current_user()) return self.error_response @app.route('/') @basic_verify_auth.login_required def index(): return 'index' self.app = app self.basic_verify_auth = basic_verify_auth self.client = app.test_client() def test_default_status_code(self): creds = base64.b64encode(b'foo:bar').decode('utf-8') for r in self.responses: self.error_response = r[0] response = self.client.get( '/', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, r[1]) Flask-HTTPAuth-4.8.0/tests/test_multi.py000066400000000000000000000137251442243746600201130ustar00rootroot00000000000000import base64 import unittest from flask import Flask from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth('MyToken') custom_token_auth = HTTPTokenAuth(header='X-Token') multi_auth = MultiAuth(basic_auth, token_auth, custom_token_auth) @basic_auth.verify_password def verify_password(username, password): if username == 'john' and password == 'hello': return 'john' @basic_auth.get_user_roles def get_basic_role(username): if username == 'john': return ['foo', 'bar'] @token_auth.verify_token def verify_token(token): return token == 'this-is-the-token!' @token_auth.get_user_roles def get_token_role(auth): if auth.token == 'this-is-the-token!': return 'foo' return @token_auth.error_handler def error_handler(): return 'error', 401, {'WWW-Authenticate': 'MyToken realm="Foo"'} @custom_token_auth.verify_token def verify_custom_token(token): return token == 'this-is-the-custom-token!' @custom_token_auth.get_user_roles def get_custom_token_role(auth): if auth.token == 'this-is-the-custom-token!': return 'foo' return @app.route('/') def index(): return 'index' @app.route('/protected') @multi_auth.login_required def auth_route(): return 'access granted:' + str(multi_auth.current_user()) @app.route('/protected-with-role') @multi_auth.login_required(role='foo') def auth_role_route(): return 'role access granted' self.app = app self.client = app.test_client() def test_multi_auth_prompt(self): response = self.client.get('/protected') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_multi_auth_login_valid_basic(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/protected', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'access granted:john') def test_multi_auth_login_invalid_basic(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/protected', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_multi_auth_login_valid_token(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'access granted:None') def test_multi_auth_login_invalid_token(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-not-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_multi_auth_login_valid_custom_token(self): response = self.client.get( '/protected', headers={'X-Token': 'this-is-the-custom-token!'}) self.assertEqual(response.data.decode('utf-8'), 'access granted:None') def test_multi_auth_login_invalid_custom_token(self): response = self.client.get( '/protected', headers={'X-Token': 'this-is-not-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Bearer realm="Authentication Required"') def test_multi_auth_login_invalid_scheme(self): response = self.client.get( '/protected', headers={'Authorization': 'Foo this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_multi_malformed_header(self): response = self.client.get( '/protected', headers={'Authorization': 'token-without-scheme'}) self.assertEqual(response.status_code, 401) def test_multi_auth_login_valid_basic_role(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/protected-with-role', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'role access granted') def test_multi_auth_login_valid_token_role(self): response = self.client.get( '/protected-with-role', headers={'Authorization': 'MyToken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'role access granted') def test_multi_auth_login_valid_custom_token_role(self): response = self.client.get( '/protected-with-role', headers={'X-Token': 'this-is-the-custom-token!'}) self.assertEqual(response.data.decode('utf-8'), 'role access granted') Flask-HTTPAuth-4.8.0/tests/test_multi_async.py000066400000000000000000000141661442243746600213100ustar00rootroot00000000000000import base64 import sys import unittest from flask import Flask from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth import pytest @pytest.mark.skipif(sys.version_info < (3, 7), reason='requires python3.7') class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth('MyToken') custom_token_auth = HTTPTokenAuth(header='X-Token') multi_auth = MultiAuth(basic_auth, token_auth, custom_token_auth) @basic_auth.verify_password async def verify_password(username, password): if username == 'john' and password == 'hello': return 'john' @basic_auth.get_user_roles async def get_basic_role(username): if username == 'john': return ['foo', 'bar'] @token_auth.verify_token async def verify_token(token): return token == 'this-is-the-token!' @token_auth.get_user_roles async def get_token_role(auth): if auth.token == 'this-is-the-token!': return 'foo' return @token_auth.error_handler async def error_handler(): return 'error', 401, {'WWW-Authenticate': 'MyToken realm="Foo"'} @custom_token_auth.verify_token async def verify_custom_token(token): return token == 'this-is-the-custom-token!' @custom_token_auth.get_user_roles async def get_custom_token_role(auth): if auth.token == 'this-is-the-custom-token!': return 'foo' return @app.route('/') async def index(): return 'index' @app.route('/protected') @multi_auth.login_required async def auth_route(): return 'access granted:' + str(multi_auth.current_user()) @app.route('/protected-with-role') @multi_auth.login_required(role='foo') async def auth_role_route(): return 'role access granted' self.app = app self.client = app.test_client() def test_multi_auth_prompt(self): response = self.client.get('/protected') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_multi_auth_login_valid_basic(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/protected', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'access granted:john') def test_multi_auth_login_invalid_basic(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/protected', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_multi_auth_login_valid_token(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'access granted:None') def test_multi_auth_login_invalid_token(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-not-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_multi_auth_login_valid_custom_token(self): response = self.client.get( '/protected', headers={'X-Token': 'this-is-the-custom-token!'}) self.assertEqual(response.data.decode('utf-8'), 'access granted:None') def test_multi_auth_login_invalid_custom_token(self): response = self.client.get( '/protected', headers={'X-Token': 'this-is-not-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Bearer realm="Authentication Required"') def test_multi_auth_login_invalid_scheme(self): response = self.client.get( '/protected', headers={'Authorization': 'Foo this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="Authentication Required"') def test_multi_malformed_header(self): response = self.client.get( '/protected', headers={'Authorization': 'token-without-scheme'}) self.assertEqual(response.status_code, 401) def test_multi_auth_login_valid_basic_role(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/protected-with-role', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'role access granted') def test_multi_auth_login_valid_token_role(self): response = self.client.get( '/protected-with-role', headers={'Authorization': 'MyToken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'role access granted') def test_multi_auth_login_valid_custom_token_role(self): response = self.client.get( '/protected-with-role', headers={'X-Token': 'this-is-the-custom-token!'}) self.assertEqual(response.data.decode('utf-8'), 'role access granted') Flask-HTTPAuth-4.8.0/tests/test_roles.py000066400000000000000000000123111442243746600200730ustar00rootroot00000000000000import unittest import base64 from flask import Flask, g from flask_httpauth import HTTPBasicAuth class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' roles_auth = HTTPBasicAuth() @roles_auth.verify_password def roles_auth_verify_password(username, password): g.anon = False if username == 'john': return password == 'hello' elif username == 'susan': return password == 'bye' elif username == 'cindy': return password == 'byebye' elif username == '': g.anon = True return True return False @roles_auth.get_user_roles def get_user_roles(auth): username = auth.username if username == 'john': return 'normal' elif username == 'susan': return ('normal', 'special') elif username == 'cindy': return None @roles_auth.error_handler def error_handler(): return 'error', 403 # use a custom error status @app.route('/') def index(): return 'index' @app.route('/normal') @roles_auth.login_required(role='normal') def roles_auth_route_normal(): return 'normal:' + roles_auth.username() @app.route('/special') @roles_auth.login_required(role='special') def roles_auth_route_special(): return 'special:' + roles_auth.username() @app.route('/normal-or-special') @roles_auth.login_required(role=('normal', 'special')) def roles_auth_route_normal_or_special(): return 'normal_or_special:' + roles_auth.username() @app.route('/normal-and-special') @roles_auth.login_required(role=(('normal', 'special'),)) def roles_auth_route_normal_and_special(): return 'normal_and_special:' + roles_auth.username() self.app = app self.roles_auth = roles_auth self.client = app.test_client() def test_verify_roles_valid_normal_1(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/normal', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal:susan') def test_verify_roles_valid_normal_2(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/normal', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal:john') def test_verify_auth_login_valid_special(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'special:susan') def test_verify_auth_login_invalid_special_1(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_invalid_special_2(self): creds = base64.b64encode(b'cindy:byebye').decode('utf-8') response = self.client.get( '/special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_valid_normal_or_special_1(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/normal-or-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal_or_special:susan') def test_verify_auth_login_valid_normal_or_special_2(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/normal-or-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal_or_special:john') def test_verify_auth_login_valid_normal_and_special_1(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/normal-and-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal_and_special:susan') def test_verify_auth_login_valid_normal_and_special_2(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/normal-and-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_invalid_password(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/normal', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) Flask-HTTPAuth-4.8.0/tests/test_roles_async.py000066400000000000000000000125361442243746600213010ustar00rootroot00000000000000import sys import unittest import base64 from flask import Flask, g from flask_httpauth import HTTPBasicAuth import pytest @pytest.mark.skipif(sys.version_info < (3, 7), reason='requires python3.7') class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' roles_auth = HTTPBasicAuth() @roles_auth.verify_password async def roles_auth_verify_password(username, password): g.anon = False if username == 'john': return password == 'hello' elif username == 'susan': return password == 'bye' elif username == 'cindy': return password == 'byebye' elif username == '': g.anon = True return True return False @roles_auth.get_user_roles async def get_user_roles(auth): username = auth.username if username == 'john': return 'normal' elif username == 'susan': return ('normal', 'special') elif username == 'cindy': return None @roles_auth.error_handler async def error_handler(): return 'error', 403 # use a custom error status @app.route('/') async def index(): return 'index' @app.route('/normal') @roles_auth.login_required(role='normal') async def roles_auth_route_normal(): return 'normal:' + roles_auth.username() @app.route('/special') @roles_auth.login_required(role='special') async def roles_auth_route_special(): return 'special:' + roles_auth.username() @app.route('/normal-or-special') @roles_auth.login_required(role=('normal', 'special')) async def roles_auth_route_normal_or_special(): return 'normal_or_special:' + roles_auth.username() @app.route('/normal-and-special') @roles_auth.login_required(role=(('normal', 'special'),)) async def roles_auth_route_normal_and_special(): return 'normal_and_special:' + roles_auth.username() self.app = app self.roles_auth = roles_auth self.client = app.test_client() def test_verify_roles_valid_normal_1(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/normal', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal:susan') def test_verify_roles_valid_normal_2(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/normal', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal:john') def test_verify_auth_login_valid_special(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'special:susan') def test_verify_auth_login_invalid_special_1(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_invalid_special_2(self): creds = base64.b64encode(b'cindy:byebye').decode('utf-8') response = self.client.get( '/special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_valid_normal_or_special_1(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/normal-or-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal_or_special:susan') def test_verify_auth_login_valid_normal_or_special_2(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/normal-or-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal_or_special:john') def test_verify_auth_login_valid_normal_and_special_1(self): creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/normal-and-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'normal_and_special:susan') def test_verify_auth_login_valid_normal_and_special_2(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/normal-and-special', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) def test_verify_auth_login_invalid_password(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/normal', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.status_code, 403) self.assertTrue('WWW-Authenticate' in response.headers) Flask-HTTPAuth-4.8.0/tests/test_token.py000066400000000000000000000136241442243746600200770ustar00rootroot00000000000000import base64 import unittest from flask import Flask from flask_httpauth import HTTPTokenAuth class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' token_auth = HTTPTokenAuth('MyToken') token_auth2 = HTTPTokenAuth('Token', realm='foo') token_auth3 = HTTPTokenAuth(header='X-API-Key') @token_auth.verify_token def verify_token(token): if token == 'this-is-the-token!': return 'user' @token_auth3.verify_token def verify_token3(token): if token == 'this-is-the-token!': return 'user' @token_auth.error_handler def error_handler(): return 'error', 401, {'WWW-Authenticate': 'MyToken realm="Foo"'} @app.route('/') def index(): return 'index' @app.route('/protected') @token_auth.login_required def token_auth_route(): return 'token_auth:' + token_auth.current_user() @app.route('/protected-optional') @token_auth.login_required(optional=True) def token_auth_optional_route(): return 'token_auth:' + str(token_auth.current_user()) @app.route('/protected2') @token_auth2.login_required def token_auth_route2(): return 'token_auth2' @app.route('/protected3') @token_auth3.login_required def token_auth_route3(): return 'token_auth3:' + token_auth3.current_user() self.app = app self.token_auth = token_auth self.client = app.test_client() def test_token_auth_prompt(self): response = self.client.get('/protected') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_ignore_options(self): response = self.client.options('/protected') self.assertEqual(response.status_code, 200) self.assertTrue('WWW-Authenticate' not in response.headers) def test_token_auth_login_valid(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'token_auth:user') def test_token_auth_login_valid_different_case(self): response = self.client.get( '/protected', headers={'Authorization': 'mytoken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'token_auth:user') def test_token_auth_login_optional(self): response = self.client.get('/protected-optional') self.assertEqual(response.data.decode('utf-8'), 'token_auth:None') def test_token_auth_login_invalid_token(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-not-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_login_invalid_scheme(self): response = self.client.get( '/protected', headers={'Authorization': 'Foo this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_login_invalid_header(self): response = self.client.get( '/protected', headers={'Authorization': 'this-is-a-bad-header'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_login_invalid_no_callback(self): response = self.client.get( '/protected2', headers={'Authorization': 'Token this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Token realm="foo"') def test_token_auth_custom_header_valid_token(self): response = self.client.get( '/protected3', headers={'X-API-Key': 'this-is-the-token!'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.decode('utf-8'), 'token_auth3:user') def test_token_auth_custom_header_invalid_token(self): response = self.client.get( '/protected3', headers={'X-API-Key': 'invalid-token-should-fail'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) def test_token_auth_custom_header_invalid_header(self): response = self.client.get( '/protected3', headers={'API-Key': 'this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Bearer realm="Authentication Required"') def test_token_auth_header_precedence(self): basic_creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/protected3', headers={'Authorization': 'Basic ' + basic_creds, 'X-API-Key': 'this-is-the-token!'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.decode('utf-8'), 'token_auth3:user') Flask-HTTPAuth-4.8.0/tests/test_token_async.py000066400000000000000000000140511442243746600212670ustar00rootroot00000000000000import base64 import sys import unittest from flask import Flask from flask_httpauth import HTTPTokenAuth import pytest @pytest.mark.skipif(sys.version_info < (3, 7), reason='requires python3.7') class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' token_auth = HTTPTokenAuth('MyToken') token_auth2 = HTTPTokenAuth('Token', realm='foo') token_auth3 = HTTPTokenAuth(header='X-API-Key') @token_auth.verify_token async def verify_token(token): if token == 'this-is-the-token!': return 'user' @token_auth3.verify_token async def verify_token3(token): if token == 'this-is-the-token!': return 'user' @token_auth.error_handler async def error_handler(): return 'error', 401, {'WWW-Authenticate': 'MyToken realm="Foo"'} @app.route('/') async def index(): return 'index' @app.route('/protected') @token_auth.login_required async def token_auth_route(): return 'token_auth:' + token_auth.current_user() @app.route('/protected-optional') @token_auth.login_required(optional=True) async def token_auth_optional_route(): return 'token_auth:' + str(token_auth.current_user()) @app.route('/protected2') @token_auth2.login_required async def token_auth_route2(): return 'token_auth2' @app.route('/protected3') @token_auth3.login_required async def token_auth_route3(): return 'token_auth3:' + token_auth3.current_user() self.app = app self.token_auth = token_auth self.client = app.test_client() def test_token_auth_prompt(self): response = self.client.get('/protected') self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_ignore_options(self): response = self.client.options('/protected') self.assertEqual(response.status_code, 200) self.assertTrue('WWW-Authenticate' not in response.headers) def test_token_auth_login_valid(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'token_auth:user') def test_token_auth_login_valid_different_case(self): response = self.client.get( '/protected', headers={'Authorization': 'mytoken this-is-the-token!'}) self.assertEqual(response.data.decode('utf-8'), 'token_auth:user') def test_token_auth_login_optional(self): response = self.client.get('/protected-optional') self.assertEqual(response.data.decode('utf-8'), 'token_auth:None') def test_token_auth_login_invalid_token(self): response = self.client.get( '/protected', headers={'Authorization': 'MyToken this-is-not-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_login_invalid_scheme(self): response = self.client.get( '/protected', headers={'Authorization': 'Foo this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_login_invalid_header(self): response = self.client.get( '/protected', headers={'Authorization': 'this-is-a-bad-header'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'MyToken realm="Foo"') def test_token_auth_login_invalid_no_callback(self): response = self.client.get( '/protected2', headers={'Authorization': 'Token this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Token realm="foo"') def test_token_auth_custom_header_valid_token(self): response = self.client.get( '/protected3', headers={'X-API-Key': 'this-is-the-token!'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.decode('utf-8'), 'token_auth3:user') def test_token_auth_custom_header_invalid_token(self): response = self.client.get( '/protected3', headers={'X-API-Key': 'invalid-token-should-fail'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) def test_token_auth_custom_header_invalid_header(self): response = self.client.get( '/protected3', headers={'API-Key': 'this-is-the-token!'}) self.assertEqual(response.status_code, 401) self.assertTrue('WWW-Authenticate' in response.headers) self.assertEqual(response.headers['WWW-Authenticate'], 'Bearer realm="Authentication Required"') def test_token_auth_header_precedence(self): basic_creds = base64.b64encode(b'susan:bye').decode('utf-8') response = self.client.get( '/protected3', headers={'Authorization': 'Basic ' + basic_creds, 'X-API-Key': 'this-is-the-token!'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.data.decode('utf-8'), 'token_auth3:user') Flask-HTTPAuth-4.8.0/tox.ini000066400000000000000000000012151442243746600155100ustar00rootroot00000000000000[tox] envlist=flake8,py37,py38,py39,py310,py311,pypy3,docs skip_missing_interpreters=True [gh-actions] python = 3.7: py37 3.8: py38 3.9: py39 3.10: py310 3.11: py311 pypy-3: pypy3 [testenv] commands= pip install -e . pip install {env:FLASK_VERSION:flask>=2.3} pytest -p no:logging --cov=src --cov-branch --cov-report=term-missing --cov-report=xml deps= asgiref pytest pytest-cov [testenv:flake8] deps= flake8 commands= flake8 --exclude=".*" --ignore=E402 src/flask_httpauth.py tests examples [testenv:docs] changedir=docs deps= sphinx allowlist_externals= make commands= make html