pax_global_header00006660000000000000000000000064121570733240014516gustar00rootroot0000000000000052 comment=d3b0ba9b8cd19003d0c929ceb15e49679e98d716 flask-basicauth-0.2.0/000077500000000000000000000000001215707332400145565ustar00rootroot00000000000000flask-basicauth-0.2.0/.gitignore000066400000000000000000000000531215707332400165440ustar00rootroot00000000000000*.egg-info/ *.pyc .tox/ dist/ docs/_build/ flask-basicauth-0.2.0/.gitmodules000066400000000000000000000001541215707332400167330ustar00rootroot00000000000000[submodule "docs/_themes"] path = docs/_themes url = https://github.com/mitsuhiko/flask-sphinx-themes.git flask-basicauth-0.2.0/.travis.yml000066400000000000000000000001661215707332400166720ustar00rootroot00000000000000language: python python: - 2.6 - 2.7 - 3.3 - pypy install: - pip install . script: - python setup.py test flask-basicauth-0.2.0/CHANGES.rst000066400000000000000000000007121215707332400163600ustar00rootroot00000000000000Changelog --------- Here you can see the full list of changes between each Flask-BasicAuth release. 0.2.0 (June 15, 2013) ^^^^^^^^^^^^^^^^^^^^^ - Added Python 3 support. 0.1.1 (May 20, 2013) ^^^^^^^^^^^^^^^^^^^^ - Fixed an issue where attempting to authenticate with password containing one or more colons was failing with "too many values to unpack" error (Michael Wallace). 0.1.0 (April 30, 2012) ^^^^^^^^^^^^^^^^^^^^^^ - Initial public release flask-basicauth-0.2.0/LICENSE000066400000000000000000000026311215707332400155650ustar00rootroot00000000000000Copyright (c) 2013, Janne Vanhala All rights reserved. Redistribution and use in source and binary forms, 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. THIS SOFTWARE 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 HOLDER 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 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. flask-basicauth-0.2.0/MANIFEST.in000066400000000000000000000002431215707332400163130ustar00rootroot00000000000000include CHANGES.rst LICENSE README.rst include test_basicauth.py recursive-include docs * recursive-exclude docs *.pyc prune docs/_build exclude docs/_themes/.git flask-basicauth-0.2.0/README.rst000066400000000000000000000014341215707332400162470ustar00rootroot00000000000000Flask-BasicAuth =============== |build status|_ .. |build status| image:: https://secure.travis-ci.org/jpvanhal/flask-basicauth.png?branch=master :alt: Build Status .. _build status: http://travis-ci.org/jpvanhal/flask-basicauth Flask-BasicAuth is a Flask extension that provides an easy way to protect certain views or your whole application with HTTP `basic access authentication`_. .. _basic access authentication: http://en.wikipedia.org/wiki/Basic_access_authentication Links ----- - `Documentation `_ - `Issue Tracker `_ - `Code `_ - `Development Version `_ flask-basicauth-0.2.0/docs/000077500000000000000000000000001215707332400155065ustar00rootroot00000000000000flask-basicauth-0.2.0/docs/Makefile000066400000000000000000000127401215707332400171520ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # 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 " 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 " 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-BasicAuth.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-BasicAuth.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-BasicAuth" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-BasicAuth" @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." 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." flask-basicauth-0.2.0/docs/_themes/000077500000000000000000000000001215707332400171325ustar00rootroot00000000000000flask-basicauth-0.2.0/docs/conf.py000066400000000000000000000176051215707332400170160ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Flask-BasicAuth documentation build configuration file, created by # sphinx-quickstart on Sun Apr 29 21:12:20 2012. # # 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 from flask.ext.basicauth import __version__ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- 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', 'sphinx.ext.intersphinx'] # 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-BasicAuth' copyright = u'2012, Janne Vanhala' # 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 = __version__ # The full version, including alpha/beta/rc tags. release = version # 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' intersphinx_mapping = { 'flask': ('http://flask.pocoo.org/docs/', None), } # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- 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': False, 'github_fork': 'jpvanhal/flask-basicauth', } # 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-BasicAuthdoc' # -- 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-BasicAuth.tex', u'Flask-BasicAuth Documentation', u'Janne Vanhala', '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-basicauth', u'Flask-BasicAuth Documentation', [u'Janne Vanhala'], 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-BasicAuth', u'Flask-BasicAuth Documentation', u'Janne Vanhala', 'Flask-BasicAuth', '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' flask-basicauth-0.2.0/docs/index.rst000066400000000000000000000051121215707332400173460ustar00rootroot00000000000000Flask-BasicAuth =============== Flask-BasicAuth is a Flask extension that provides an easy way to protect certain views or your whole application with HTTP `basic access authentication`_. .. _basic access authentication: http://en.wikipedia.org/wiki/Basic_access_authentication Installation ------------ The easiest way to install Flask-BasicAuth is with pip:: pip install Flask-BasicAuth Usage ----- Usage of Flask-BasicAuth is simple:: from flask import Flask, render_template from flask.ext.basicauth import BasicAuth app = Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = 'john' app.config['BASIC_AUTH_PASSWORD'] = 'matrix' basic_auth = BasicAuth(app) @app.route('/secret') @basic_auth.required def secret_view(): return render_template('secret.html') If you would like to protect you entire site with basic access authentication, just set ``BASIC_AUTH_FORCE`` configuration variable to `True`:: app.config['BASIC_AUTH_FORCE'] = True You might find this useful, for example, if you would like to protect your staging server from uninvited guests. .. warning:: Please make sure that you use SSL/TLS (HTTPS) to encrypt the connection between the client and the server, when using basic access authentication. In basic access authentication username and password are sent in cleartext, and if SSL/TLS is not used, the credentials could be easily intercepted. Configuration ------------- The following configuration values exist for Flask-BasicAuth. Flask-BasicAuth loads these values from your main Flask config which can be populated in various ways. A list of configuration keys currently understood by the extension: ``BASIC_AUTH_FORCE`` If set to `True`, makes the whole site require HTTP basic access authentication. Defaults to `False`. ``BASIC_AUTH_REALM`` The authentication realm used for the challenge. This is typically a description of the system being accessed. Defaults to ``''``. ``BASIC_AUTH_USERNAME`` and ``BASIC_AUTH_PASSWORD`` The correct username and password combination that grants access for the client to the protected resource. You can override :meth:`BasicAuth.check_credentials `, if you need a different authentication logic for your application. API reference ------------- .. module:: flask.ext.basicauth This part of the documentation covers all the public classes and functions in Flask-BasicAuth. .. autoclass:: BasicAuth :members: .. include:: ../CHANGES.rst License ------- .. include:: ../LICENSE flask-basicauth-0.2.0/flask_basicauth.py000066400000000000000000000070251215707332400202570ustar00rootroot00000000000000""" flask.ext.basicauth ~~~~~~~~~~~~~~~~~~~ Flask-BasicAuth is a Flask extension that provides an easy way to protect certain views or your whole application with HTTP basic access authentication. :copyright: (c) 2013 Janne Vanhala. :license: BSD, see LICENSE for more details. """ import base64 from functools import wraps from flask import current_app, request, Response __version__ = '0.2.0' class BasicAuth(object): """ A Flask extension for adding HTTP basic access authentication to the application. :param app: a :class:`~flask.Flask` instance. Defaults to `None`. If no application is provided on creation, then it can be provided later on via :meth:`init_app`. """ def __init__(self, app=None): if app is not None: self.app = app self.init_app(app) else: self.app = None def init_app(self, app): """ Initialize this BasicAuth extension for the given application. :param app: a :class:`~flask.Flask` instance """ app.config.setdefault('BASIC_AUTH_FORCE', False) app.config.setdefault('BASIC_AUTH_REALM', '') @app.before_request def require_basic_auth(): if not current_app.config['BASIC_AUTH_FORCE']: return if not self.authenticate(): return self.challenge() def check_credentials(self, username, password): """ Check if the given username and password are correct. By default compares the given username and password to ``HTTP_BASIC_AUTH_USERNAME`` and ``HTTP_BASIC_AUTH_PASSWORD`` configuration variables. :param username: a username provided by the client :param password: a password provided by the client :returns: `True` if the username and password combination was correct, and `False` otherwise. """ correct_username = current_app.config['BASIC_AUTH_USERNAME'] correct_password = current_app.config['BASIC_AUTH_PASSWORD'] return username == correct_username and password == correct_password def authenticate(self): """ Check the request for HTTP basic access authentication header and try to authenticate the user. :returns: `True` if the user is authorized, or `False` otherwise. """ auth = request.authorization return ( auth and auth.type == 'basic' and self.check_credentials(auth.username, auth.password) ) def challenge(self): """ Challenge the client for username and password. This method is called when the client did not provide username and password in the request, or the username and password combination was wrong. :returns: a :class:`~flask.Response` with 401 response code, including the required authentication scheme and authentication realm. """ realm = current_app.config['BASIC_AUTH_REALM'] return Response( status=401, headers={'WWW-Authenticate': 'Basic realm="%s"' % realm} ) def required(self, view_func): """ A decorator that can be used to protect specific views with HTTP basic access authentication. """ @wraps(view_func) def wrapper(*args, **kwargs): if self.authenticate(): return view_func(*args, **kwargs) else: return self.challenge() return wrapper flask-basicauth-0.2.0/setup.py000066400000000000000000000026321215707332400162730ustar00rootroot00000000000000import os import re from setuptools import setup HERE = os.path.dirname(os.path.abspath(__file__)) def get_version(): filename = os.path.join(HERE, 'flask_basicauth.py') contents = open(filename).read() pattern = r"^__version__ = '(.*?)'$" return re.search(pattern, contents, re.MULTILINE).group(1) setup( name='Flask-BasicAuth', version=get_version(), url='https://github.com/jpvanhal/flask-basicauth', license='BSD', author='Janne Vanhala', author_email='janne.vanhala@gmail.com', description='HTTP basic access authentication for Flask.', long_description=( open('README.rst').read() + '\n\n' + open('CHANGES.rst').read() ), py_modules=['flask_basicauth'], zip_safe=False, include_package_data=True, platforms='any', install_requires=['Flask'], test_suite='test_basicauth.suite', classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) flask-basicauth-0.2.0/test_basicauth.py000066400000000000000000000077001215707332400201360ustar00rootroot00000000000000import base64 import unittest from flask import Flask from flask.ext.basicauth import BasicAuth class BasicAuthTestCase(unittest.TestCase): def assertIn(self, value, container): self.assertTrue(value in container) def setUp(self): app = Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = 'john' app.config['BASIC_AUTH_PASSWORD'] = 'matrix' basic_auth = BasicAuth(app) @app.route('/') def normal_view(): return 'This view does not normally require authentication.' @app.route('/protected') @basic_auth.required def protected_view(): return 'This view always requires authentication.' self.app = app self.basic_auth = basic_auth self.client = app.test_client() def make_headers(self, username, password): auth = base64.b64encode(username + b':' + password) return {'Authorization': b'Basic ' + auth} def test_sets_default_values_for_configuration(self): self.assertEqual(self.app.config['BASIC_AUTH_REALM'], '') self.assertEqual(self.app.config['BASIC_AUTH_FORCE'], False) def test_views_without_basic_auth_decorator_respond_with_200(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_requires_authentication_for_all_views_when_forced(self): self.app.config['BASIC_AUTH_FORCE'] = True response = self.client.get('/') self.assertEqual(response.status_code, 401) def test_responds_with_401_without_authorization(self): response = self.client.get('/protected') self.assertEqual(response.status_code, 401) def test_asks_for_authentication(self): response = self.client.get('/protected') self.assertIn('WWW-Authenticate', response.headers) self.assertEqual( response.headers['WWW-Authenticate'], 'Basic realm=""' ) def test_asks_for_authentication_with_custom_realm(self): self.app.config['BASIC_AUTH_REALM'] = 'Secure Area' response = self.client.get('/protected') self.assertIn('WWW-Authenticate', response.headers) self.assertEqual( response.headers['WWW-Authenticate'], 'Basic realm="Secure Area"' ) def test_check_credentials_with_correct_credentials(self): with self.app.test_request_context(): self.assertTrue( self.basic_auth.check_credentials('john', 'matrix') ) def test_check_credentials_with_incorrect_credentials(self): with self.app.test_request_context(): self.assertFalse( self.basic_auth.check_credentials('john', 'rambo') ) def test_responds_with_401_with_incorrect_credentials(self): response = self.client.get( '/protected', headers=self.make_headers(b'john', b'rambo') ) self.assertEqual(response.status_code, 401) def test_responds_with_200_with_correct_credentials(self): response = self.client.get( '/protected', headers=self.make_headers(b'john', b'matrix') ) self.assertEqual(response.status_code, 200) def test_responds_with_200_with_correct_credentials_containing_colon(self): self.app.config['BASIC_AUTH_PASSWORD'] = 'matrix:' response = self.client.get( '/protected', headers=self.make_headers(b'john', b'matrix:') ) self.assertEqual(response.status_code, 200) def test_runs_decorated_view_after_authentication(self): response = self.client.get( '/protected', headers=self.make_headers(b'john', b'matrix') ) self.assertEqual( response.data, b'This view always requires authentication.' ) def suite(): return unittest.makeSuite(BasicAuthTestCase) if __name__ == '__main__': unittest.main(defaultTest='suite') flask-basicauth-0.2.0/tox.ini000066400000000000000000000001171215707332400160700ustar00rootroot00000000000000[tox] envlist = py26,py27,pypy,py33 [testenv] commands = python setup.py test