├── .gitignore
├── .gitmodules
├── .travis.yml
├── CHANGES.rst
├── LICENSE
├── MANIFEST.in
├── README.rst
├── docs
├── Makefile
├── conf.py
└── index.rst
├── flask_basicauth.py
├── setup.py
├── test_basicauth.py
└── tox.ini
/.gitignore:
--------------------------------------------------------------------------------
1 | *.egg-info/
2 | *.pyc
3 | .coverage
4 | .tox/
5 | dist/
6 | docs/_build/
7 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "docs/_themes"]
2 | path = docs/_themes
3 | url = https://github.com/mitsuhiko/flask-sphinx-themes.git
4 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - 2.6
4 | - 2.7
5 | - 3.3
6 | - pypy
7 | install:
8 | - pip install .
9 | - pip install coveralls
10 | script:
11 | - coverage run --source flask_basicauth setup.py test
12 | - coverage report -m
13 | after_script:
14 | - coveralls --verbose
15 |
--------------------------------------------------------------------------------
/CHANGES.rst:
--------------------------------------------------------------------------------
1 | Changelog
2 | ---------
3 |
4 | Here you can see the full list of changes between each Flask-BasicAuth
5 | release.
6 |
7 | 0.2.0 (June 15, 2013)
8 | ^^^^^^^^^^^^^^^^^^^^^
9 |
10 | - Added Python 3 support.
11 |
12 | 0.1.1 (May 20, 2013)
13 | ^^^^^^^^^^^^^^^^^^^^
14 |
15 | - Fixed an issue where attempting to authenticate with password containing one
16 | or more colons was failing with "too many values to unpack" error (Michael
17 | Wallace).
18 |
19 | 0.1.0 (April 30, 2012)
20 | ^^^^^^^^^^^^^^^^^^^^^^
21 |
22 | - Initial public release
23 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2013, Janne Vanhala
2 |
3 | All rights reserved.
4 |
5 | Redistribution and use in source and binary forms, with or without
6 | modification, are permitted provided that the following conditions are met:
7 |
8 | * Redistributions of source code must retain the above copyright notice, this
9 | list of conditions and the following disclaimer.
10 |
11 | * Redistributions in binary form must reproduce the above copyright notice,
12 | this list of conditions and the following disclaimer in the documentation
13 | and/or other materials provided with the distribution.
14 |
15 | * The names of the contributors may not be used to endorse or promote products
16 | derived from this software without specific prior written permission.
17 |
18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT,
22 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 | OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
27 | ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include CHANGES.rst LICENSE README.rst
2 | include test_basicauth.py
3 | recursive-include docs *
4 | recursive-exclude docs *.pyc
5 | prune docs/_build
6 | exclude docs/_themes/.git
7 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Flask-BasicAuth
2 | ===============
3 |
4 | .. image:: https://secure.travis-ci.org/jpvanhal/flask-basicauth.png?branch=master
5 | :target: https://travis-ci.org/jpvanhal/flask-basicauth
6 | :alt: Build Status
7 |
8 | .. image:: https://coveralls.io/repos/jpvanhal/flask-basicauth/badge.png
9 | :target: https://coveralls.io/r/jpvanhal/flask-basicauth
10 | :alt: Coverage Status
11 |
12 | Flask-BasicAuth is a Flask extension that provides an easy way to protect
13 | certain views or your whole application with HTTP `basic access
14 | authentication`_.
15 |
16 | .. _basic access authentication: http://en.wikipedia.org/wiki/Basic_access_authentication
17 |
18 |
19 | Links
20 | -----
21 |
22 | - `Documentation `_
23 | - `Issue Tracker `_
24 | - `Code `_
25 | - `Development Version
26 | `_
27 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-BasicAuth.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-BasicAuth.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-BasicAuth"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-BasicAuth"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Flask-BasicAuth documentation build configuration file, created by
4 | # sphinx-quickstart on Sun Apr 29 21:12:20 2012.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | from flask.ext.basicauth import __version__
17 |
18 | # If extensions (or modules to document with autodoc) are in another directory,
19 | # add these directories to sys.path here. If the directory is relative to the
20 | # documentation root, use os.path.abspath to make it absolute, like shown here.
21 | #sys.path.insert(0, os.path.abspath('.'))
22 |
23 | # -- General configuration -----------------------------------------------------
24 |
25 | # If your documentation needs a minimal Sphinx version, state it here.
26 | #needs_sphinx = '1.0'
27 |
28 | # Add any Sphinx extension module names here, as strings. They can be extensions
29 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
30 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
31 |
32 | # Add any paths that contain templates here, relative to this directory.
33 | templates_path = ['_templates']
34 |
35 | # The suffix of source filenames.
36 | source_suffix = '.rst'
37 |
38 | # The encoding of source files.
39 | #source_encoding = 'utf-8-sig'
40 |
41 | # The master toctree document.
42 | master_doc = 'index'
43 |
44 | # General information about the project.
45 | project = u'Flask-BasicAuth'
46 | copyright = u'2012, Janne Vanhala'
47 |
48 | # The version info for the project you're documenting, acts as replacement for
49 | # |version| and |release|, also used in various other places throughout the
50 | # built documents.
51 | #
52 | # The short X.Y version.
53 | version = __version__
54 | # The full version, including alpha/beta/rc tags.
55 | release = version
56 |
57 | # The language for content autogenerated by Sphinx. Refer to documentation
58 | # for a list of supported languages.
59 | #language = None
60 |
61 | # There are two options for replacing |today|: either, you set today to some
62 | # non-false value, then it is used:
63 | #today = ''
64 | # Else, today_fmt is used as the format for a strftime call.
65 | #today_fmt = '%B %d, %Y'
66 |
67 | # List of patterns, relative to source directory, that match files and
68 | # directories to ignore when looking for source files.
69 | exclude_patterns = ['_build']
70 |
71 | # The reST default role (used for this markup: `text`) to use for all documents.
72 | #default_role = None
73 |
74 | # If true, '()' will be appended to :func: etc. cross-reference text.
75 | #add_function_parentheses = True
76 |
77 | # If true, the current module name will be prepended to all description
78 | # unit titles (such as .. function::).
79 | #add_module_names = True
80 |
81 | # If true, sectionauthor and moduleauthor directives will be shown in the
82 | # output. They are ignored by default.
83 | #show_authors = False
84 |
85 | # The name of the Pygments (syntax highlighting) style to use.
86 | pygments_style = 'sphinx'
87 |
88 | intersphinx_mapping = {
89 | 'flask': ('http://flask.pocoo.org/docs/', None),
90 | }
91 |
92 | # A list of ignored prefixes for module index sorting.
93 | #modindex_common_prefix = []
94 |
95 |
96 | # -- Options for HTML output ---------------------------------------------------
97 |
98 | # The theme to use for HTML and HTML Help pages. See the documentation for
99 | # a list of builtin themes.
100 | html_theme = 'flask_small'
101 |
102 | # Theme options are theme-specific and customize the look and feel of a theme
103 | # further. For a list of options available for each theme, see the
104 | # documentation.
105 | html_theme_options = {
106 | 'index_logo': False,
107 | 'github_fork': 'jpvanhal/flask-basicauth',
108 | }
109 |
110 | # Add any paths that contain custom themes here, relative to this directory.
111 | html_theme_path = ['_themes']
112 |
113 | # The name for this set of Sphinx documents. If None, it defaults to
114 | # " v documentation".
115 | #html_title = None
116 |
117 | # A shorter title for the navigation bar. Default is the same as html_title.
118 | #html_short_title = None
119 |
120 | # The name of an image file (relative to this directory) to place at the top
121 | # of the sidebar.
122 | #html_logo = None
123 |
124 | # The name of an image file (within the static path) to use as favicon of the
125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
126 | # pixels large.
127 | #html_favicon = None
128 |
129 | # Add any paths that contain custom static files (such as style sheets) here,
130 | # relative to this directory. They are copied after the builtin static files,
131 | # so a file named "default.css" will overwrite the builtin "default.css".
132 | html_static_path = ['_static']
133 |
134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
135 | # using the given strftime format.
136 | #html_last_updated_fmt = '%b %d, %Y'
137 |
138 | # If true, SmartyPants will be used to convert quotes and dashes to
139 | # typographically correct entities.
140 | #html_use_smartypants = True
141 |
142 | # Custom sidebar templates, maps document names to template names.
143 | #html_sidebars = {}
144 |
145 | # Additional templates that should be rendered to pages, maps page names to
146 | # template names.
147 | #html_additional_pages = {}
148 |
149 | # If false, no module index is generated.
150 | #html_domain_indices = True
151 |
152 | # If false, no index is generated.
153 | #html_use_index = True
154 |
155 | # If true, the index is split into individual pages for each letter.
156 | #html_split_index = False
157 |
158 | # If true, links to the reST sources are added to the pages.
159 | #html_show_sourcelink = True
160 |
161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
162 | #html_show_sphinx = True
163 |
164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
165 | #html_show_copyright = True
166 |
167 | # If true, an OpenSearch description file will be output, and all pages will
168 | # contain a tag referring to it. The value of this option must be the
169 | # base URL from which the finished HTML is served.
170 | #html_use_opensearch = ''
171 |
172 | # This is the file name suffix for HTML files (e.g. ".xhtml").
173 | #html_file_suffix = None
174 |
175 | # Output file base name for HTML help builder.
176 | htmlhelp_basename = 'Flask-BasicAuthdoc'
177 |
178 |
179 | # -- Options for LaTeX output --------------------------------------------------
180 |
181 | latex_elements = {
182 | # The paper size ('letterpaper' or 'a4paper').
183 | #'papersize': 'letterpaper',
184 |
185 | # The font size ('10pt', '11pt' or '12pt').
186 | #'pointsize': '10pt',
187 |
188 | # Additional stuff for the LaTeX preamble.
189 | #'preamble': '',
190 | }
191 |
192 | # Grouping the document tree into LaTeX files. List of tuples
193 | # (source start file, target name, title, author, documentclass [howto/manual]).
194 | latex_documents = [
195 | ('index', 'Flask-BasicAuth.tex', u'Flask-BasicAuth Documentation',
196 | u'Janne Vanhala', 'manual'),
197 | ]
198 |
199 | # The name of an image file (relative to this directory) to place at the top of
200 | # the title page.
201 | #latex_logo = None
202 |
203 | # For "manual" documents, if this is true, then toplevel headings are parts,
204 | # not chapters.
205 | #latex_use_parts = False
206 |
207 | # If true, show page references after internal links.
208 | #latex_show_pagerefs = False
209 |
210 | # If true, show URL addresses after external links.
211 | #latex_show_urls = False
212 |
213 | # Documents to append as an appendix to all manuals.
214 | #latex_appendices = []
215 |
216 | # If false, no module index is generated.
217 | #latex_domain_indices = True
218 |
219 |
220 | # -- Options for manual page output --------------------------------------------
221 |
222 | # One entry per manual page. List of tuples
223 | # (source start file, name, description, authors, manual section).
224 | man_pages = [
225 | ('index', 'flask-basicauth', u'Flask-BasicAuth Documentation',
226 | [u'Janne Vanhala'], 1)
227 | ]
228 |
229 | # If true, show URL addresses after external links.
230 | #man_show_urls = False
231 |
232 |
233 | # -- Options for Texinfo output ------------------------------------------------
234 |
235 | # Grouping the document tree into Texinfo files. List of tuples
236 | # (source start file, target name, title, author,
237 | # dir menu entry, description, category)
238 | texinfo_documents = [
239 | ('index', 'Flask-BasicAuth', u'Flask-BasicAuth Documentation',
240 | u'Janne Vanhala', 'Flask-BasicAuth', 'One line description of project.',
241 | 'Miscellaneous'),
242 | ]
243 |
244 | # Documents to append as an appendix to all manuals.
245 | #texinfo_appendices = []
246 |
247 | # If false, no module index is generated.
248 | #texinfo_domain_indices = True
249 |
250 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
251 | #texinfo_show_urls = 'footnote'
252 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | Flask-BasicAuth
2 | ===============
3 |
4 | Flask-BasicAuth is a Flask extension that provides an easy way to protect
5 | certain views or your whole application with HTTP `basic access
6 | authentication`_.
7 |
8 | .. _basic access authentication: http://en.wikipedia.org/wiki/Basic_access_authentication
9 |
10 |
11 | Installation
12 | ------------
13 |
14 | The easiest way to install Flask-BasicAuth is with pip::
15 |
16 | pip install Flask-BasicAuth
17 |
18 |
19 | Usage
20 | -----
21 |
22 | Usage of Flask-BasicAuth is simple::
23 |
24 | from flask import Flask, render_template
25 | from flask_basicauth import BasicAuth
26 |
27 | app = Flask(__name__)
28 |
29 | app.config['BASIC_AUTH_USERNAME'] = 'john'
30 | app.config['BASIC_AUTH_PASSWORD'] = 'matrix'
31 |
32 | basic_auth = BasicAuth(app)
33 |
34 | @app.route('/secret')
35 | @basic_auth.required
36 | def secret_view():
37 | return render_template('secret.html')
38 |
39 | If you would like to protect you entire site with basic access authentication,
40 | just set ``BASIC_AUTH_FORCE`` configuration variable to `True`::
41 |
42 | app.config['BASIC_AUTH_FORCE'] = True
43 |
44 | You might find this useful, for example, if you would like to protect your
45 | staging server from uninvited guests.
46 |
47 | .. warning::
48 |
49 | Please make sure that you use SSL/TLS (HTTPS) to encrypt the connection
50 | between the client and the server, when using basic access authentication.
51 | In basic access authentication username and password are sent in cleartext,
52 | and if SSL/TLS is not used, the credentials could be easily intercepted.
53 |
54 |
55 | Configuration
56 | -------------
57 |
58 | The following configuration values exist for Flask-BasicAuth. Flask-BasicAuth
59 | loads these values from your main Flask config which can be populated in
60 | various ways.
61 |
62 | A list of configuration keys currently understood by the extension:
63 |
64 | ``BASIC_AUTH_FORCE``
65 | If set to `True`, makes the whole site require HTTP basic access
66 | authentication.
67 |
68 | Defaults to `False`.
69 |
70 | ``BASIC_AUTH_REALM``
71 | The authentication realm used for the challenge. This is typically a
72 | description of the system being accessed.
73 |
74 | Defaults to ``''``.
75 |
76 | ``BASIC_AUTH_USERNAME`` and ``BASIC_AUTH_PASSWORD``
77 | The correct username and password combination that grants access for the
78 | client to the protected resource.
79 |
80 | You can override :meth:`BasicAuth.check_credentials `,
81 | if you need a different authentication logic for your application.
82 |
83 |
84 | API reference
85 | -------------
86 |
87 | .. module:: flask.ext.basicauth
88 |
89 | This part of the documentation covers all the public classes and functions
90 | in Flask-BasicAuth.
91 |
92 | .. autoclass:: BasicAuth
93 | :members:
94 |
95 |
96 | .. include:: ../CHANGES.rst
97 |
98 |
99 | License
100 | -------
101 |
102 | .. include:: ../LICENSE
103 |
--------------------------------------------------------------------------------
/flask_basicauth.py:
--------------------------------------------------------------------------------
1 | """
2 | flask.ext.basicauth
3 | ~~~~~~~~~~~~~~~~~~~
4 |
5 | Flask-BasicAuth is a Flask extension that provides an easy way to protect
6 | certain views or your whole application with HTTP basic access
7 | authentication.
8 |
9 | :copyright: (c) 2013 Janne Vanhala.
10 | :license: BSD, see LICENSE for more details.
11 | """
12 | import base64
13 | from functools import wraps
14 |
15 | from flask import current_app, request, Response
16 |
17 |
18 | __version__ = '0.2.0'
19 |
20 |
21 | class BasicAuth(object):
22 | """
23 | A Flask extension for adding HTTP basic access authentication to the
24 | application.
25 |
26 | :param app: a :class:`~flask.Flask` instance. Defaults to `None`. If no
27 | application is provided on creation, then it can be provided later on
28 | via :meth:`init_app`.
29 | """
30 | def __init__(self, app=None):
31 | if app is not None:
32 | self.app = app
33 | self.init_app(app)
34 | else:
35 | self.app = None
36 |
37 | def init_app(self, app):
38 | """
39 | Initialize this BasicAuth extension for the given application.
40 |
41 | :param app: a :class:`~flask.Flask` instance
42 | """
43 | app.config.setdefault('BASIC_AUTH_FORCE', False)
44 | app.config.setdefault('BASIC_AUTH_REALM', '')
45 |
46 | @app.before_request
47 | def require_basic_auth():
48 | if not current_app.config['BASIC_AUTH_FORCE']:
49 | return
50 | if not self.authenticate():
51 | return self.challenge()
52 |
53 | def check_credentials(self, username, password):
54 | """
55 | Check if the given username and password are correct.
56 |
57 | By default compares the given username and password to
58 | ``BASIC_AUTH_USERNAME`` and ``BASIC_AUTH_PASSWORD``
59 | configuration variables.
60 |
61 | :param username: a username provided by the client
62 | :param password: a password provided by the client
63 | :returns: `True` if the username and password combination was correct,
64 | and `False` otherwise.
65 | """
66 | correct_username = current_app.config['BASIC_AUTH_USERNAME']
67 | correct_password = current_app.config['BASIC_AUTH_PASSWORD']
68 | return username == correct_username and password == correct_password
69 |
70 | def authenticate(self):
71 | """
72 | Check the request for HTTP basic access authentication header and try
73 | to authenticate the user.
74 |
75 | :returns: `True` if the user is authorized, or `False` otherwise.
76 | """
77 | auth = request.authorization
78 | return (
79 | auth and auth.type == 'basic' and
80 | self.check_credentials(auth.username, auth.password)
81 | )
82 |
83 | def challenge(self):
84 | """
85 | Challenge the client for username and password.
86 |
87 | This method is called when the client did not provide username and
88 | password in the request, or the username and password combination was
89 | wrong.
90 |
91 | :returns: a :class:`~flask.Response` with 401 response code, including
92 | the required authentication scheme and authentication realm.
93 | """
94 | realm = current_app.config['BASIC_AUTH_REALM']
95 | return Response(
96 | status=401,
97 | headers={'WWW-Authenticate': 'Basic realm="%s"' % realm}
98 | )
99 |
100 | def required(self, view_func):
101 | """
102 | A decorator that can be used to protect specific views with HTTP
103 | basic access authentication.
104 | """
105 | @wraps(view_func)
106 | def wrapper(*args, **kwargs):
107 | if self.authenticate():
108 | return view_func(*args, **kwargs)
109 | else:
110 | return self.challenge()
111 | return wrapper
112 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 |
4 | from setuptools import setup
5 |
6 | HERE = os.path.dirname(os.path.abspath(__file__))
7 |
8 |
9 | def get_version():
10 | filename = os.path.join(HERE, 'flask_basicauth.py')
11 | contents = open(filename).read()
12 | pattern = r"^__version__ = '(.*?)'$"
13 | return re.search(pattern, contents, re.MULTILINE).group(1)
14 |
15 |
16 | setup(
17 | name='Flask-BasicAuth',
18 | version=get_version(),
19 | url='https://github.com/jpvanhal/flask-basicauth',
20 | license='BSD',
21 | author='Janne Vanhala',
22 | author_email='janne.vanhala@gmail.com',
23 | description='HTTP basic access authentication for Flask.',
24 | long_description=(
25 | open('README.rst').read() + '\n\n' +
26 | open('CHANGES.rst').read()
27 | ),
28 | py_modules=['flask_basicauth'],
29 | zip_safe=False,
30 | include_package_data=True,
31 | platforms='any',
32 | install_requires=['Flask'],
33 | test_suite='test_basicauth.suite',
34 | classifiers=[
35 | 'Environment :: Web Environment',
36 | 'Intended Audience :: Developers',
37 | 'License :: OSI Approved :: BSD License',
38 | 'Operating System :: OS Independent',
39 | 'Programming Language :: Python :: 2.6',
40 | 'Programming Language :: Python :: 2.7',
41 | 'Programming Language :: Python :: 3.3',
42 | 'Programming Language :: Python :: Implementation :: PyPy',
43 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
44 | 'Topic :: Software Development :: Libraries :: Python Modules'
45 | ]
46 | )
47 |
--------------------------------------------------------------------------------
/test_basicauth.py:
--------------------------------------------------------------------------------
1 | import base64
2 | import unittest
3 |
4 | from flask import Flask
5 | from flask.ext.basicauth import BasicAuth
6 |
7 |
8 | class BasicAuthTestCase(unittest.TestCase):
9 |
10 | def assertIn(self, value, container):
11 | self.assertTrue(value in container)
12 |
13 | def setUp(self):
14 | app = Flask(__name__)
15 |
16 | app.config['BASIC_AUTH_USERNAME'] = 'john'
17 | app.config['BASIC_AUTH_PASSWORD'] = 'matrix'
18 |
19 | basic_auth = BasicAuth(app)
20 |
21 | @app.route('/')
22 | def normal_view():
23 | return 'This view does not normally require authentication.'
24 |
25 | @app.route('/protected')
26 | @basic_auth.required
27 | def protected_view():
28 | return 'This view always requires authentication.'
29 |
30 | self.app = app
31 | self.basic_auth = basic_auth
32 | self.client = app.test_client()
33 |
34 | def make_headers(self, username, password):
35 | auth = base64.b64encode(username + b':' + password)
36 | return {'Authorization': b'Basic ' + auth}
37 |
38 | def test_sets_default_values_for_configuration(self):
39 | self.assertEqual(self.app.config['BASIC_AUTH_REALM'], '')
40 | self.assertEqual(self.app.config['BASIC_AUTH_FORCE'], False)
41 |
42 | def test_views_without_basic_auth_decorator_respond_with_200(self):
43 | response = self.client.get('/')
44 | self.assertEqual(response.status_code, 200)
45 |
46 | def test_requires_authentication_for_all_views_when_forced(self):
47 | self.app.config['BASIC_AUTH_FORCE'] = True
48 | response = self.client.get('/')
49 | self.assertEqual(response.status_code, 401)
50 |
51 | def test_responds_with_401_without_authorization(self):
52 | response = self.client.get('/protected')
53 | self.assertEqual(response.status_code, 401)
54 |
55 | def test_asks_for_authentication(self):
56 | response = self.client.get('/protected')
57 | self.assertIn('WWW-Authenticate', response.headers)
58 | self.assertEqual(
59 | response.headers['WWW-Authenticate'],
60 | 'Basic realm=""'
61 | )
62 |
63 | def test_asks_for_authentication_with_custom_realm(self):
64 | self.app.config['BASIC_AUTH_REALM'] = 'Secure Area'
65 | response = self.client.get('/protected')
66 | self.assertIn('WWW-Authenticate', response.headers)
67 | self.assertEqual(
68 | response.headers['WWW-Authenticate'],
69 | 'Basic realm="Secure Area"'
70 | )
71 |
72 | def test_check_credentials_with_correct_credentials(self):
73 | with self.app.test_request_context():
74 | self.assertTrue(
75 | self.basic_auth.check_credentials('john', 'matrix')
76 | )
77 |
78 | def test_check_credentials_with_incorrect_credentials(self):
79 | with self.app.test_request_context():
80 | self.assertFalse(
81 | self.basic_auth.check_credentials('john', 'rambo')
82 | )
83 |
84 | def test_responds_with_401_with_incorrect_credentials(self):
85 | response = self.client.get(
86 | '/protected',
87 | headers=self.make_headers(b'john', b'rambo')
88 | )
89 | self.assertEqual(response.status_code, 401)
90 |
91 | def test_responds_with_200_with_correct_credentials(self):
92 | response = self.client.get(
93 | '/protected',
94 | headers=self.make_headers(b'john', b'matrix')
95 | )
96 | self.assertEqual(response.status_code, 200)
97 |
98 | def test_responds_with_200_with_correct_credentials_containing_colon(self):
99 | self.app.config['BASIC_AUTH_PASSWORD'] = 'matrix:'
100 | response = self.client.get(
101 | '/protected',
102 | headers=self.make_headers(b'john', b'matrix:')
103 | )
104 | self.assertEqual(response.status_code, 200)
105 |
106 | def test_runs_decorated_view_after_authentication(self):
107 | response = self.client.get(
108 | '/protected',
109 | headers=self.make_headers(b'john', b'matrix')
110 | )
111 | self.assertEqual(
112 | response.data,
113 | b'This view always requires authentication.'
114 | )
115 |
116 |
117 | def suite():
118 | return unittest.makeSuite(BasicAuthTestCase)
119 |
120 |
121 | if __name__ == '__main__':
122 | unittest.main(defaultTest='suite')
123 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py26,py27,pypy,py33
3 |
4 | [testenv]
5 | commands = python setup.py test
6 |
--------------------------------------------------------------------------------