├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── circle.yml ├── docs ├── Makefile ├── api.rst ├── conf.py ├── example.rst ├── index.rst ├── intro.rst └── make.bat ├── example.py ├── flask_micropub.py ├── setup.py ├── tests ├── __init__.py └── test_micropub_client.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # PyInstaller 26 | # Usually these files are written by a python script from a template 27 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 28 | *.manifest 29 | *.spec 30 | 31 | # Installer logs 32 | pip-log.txt 33 | pip-delete-this-directory.txt 34 | 35 | # Unit test / coverage reports 36 | htmlcov/ 37 | .tox/ 38 | .coverage 39 | .cache 40 | nosetests.xml 41 | coverage.xml 42 | 43 | # Translations 44 | *.mo 45 | *.pot 46 | 47 | # Django stuff: 48 | *.log 49 | 50 | # Sphinx documentation 51 | docs/_build/ 52 | 53 | # PyBuilder 54 | target/ 55 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.6" 4 | - "2.7" 5 | - "3.3" 6 | - "3.4" 7 | # command to run tests 8 | script: "python setup.py test" 9 | sudo: false 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | 4 | ## 0.2.8 - 2017-11-04 5 | ### Changed 6 | - Added params to auth requests to support micropub.rocks tests 7 | 8 | ### Added 9 | - support JSON auth responses from token endpoints 10 | 11 | ## 0.2.7 - 2016-03-18 12 | ### Changed 13 | - Allow all 2xx responses to indicate success. 14 | 15 | ## 0.2.6 - 2016-03-18 16 | ### Changed 17 | - Support discovering endpoints from HTTP Link headers in addition 18 | to searching the body of the page. 19 | 20 | ## 0.2.5 - 2016-01-27 21 | ### Changed 22 | - Bugfix: authorization_handler was burning the auth code by 23 | delegating to authentication_handler. This broke authorization for 24 | endpoints that only allow codes to be used once. A side effect of 25 | this is that authorization no longer falls back to authentication 26 | when there is no token_endpoint or the token_endpoint request fails. 27 | 28 | ## 0.2.4 - 2015-12-13 29 | ### Changed 30 | - Replace `next_url` parameter with more general `state` 31 | (though we're keeping `next_url` for backward compatibility for now) 32 | 33 | ## 0.2.3 34 | ### Changed 35 | - Fix; fall back to indieauth.com when no authorization_endpoint is 36 | specified (previous fix broke this). 37 | 38 | ## 0.2.2 39 | ### Changed 40 | - Fix vulnerability; re-discover the authorization_endpoint and 41 | token_endpoint at each stage in the flow. Prevents a buggy or 42 | malicious authorization_endpoint from giving you credentials for 43 | another user's domain name. 44 | 45 | ## 0.2.1 - 2015-02-07 46 | ### Changed 47 | - Updated setup.py, no functional changes 48 | 49 | ## 0.2.0 - 2015-02-07 50 | ### Changed 51 | - Started keeping a changelog! 52 | - Added a separate 'authenticate' flow to provide explicit support for 53 | calling out to indieauth without requesting any sort of access 54 | token. 55 | - Redirect_url is now determined automatically based on the 56 | authenticated_handler or authorized_handler annotations 57 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Kyle Mahan 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 17 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 18 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 20 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 21 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 22 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 23 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 24 | 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Documentation Status](https://readthedocs.org/projects/flask-micropub/badge/?version=latest)](http://flask-micropub.readthedocs.org/en/latest/?badge=latest) 2 | 3 | [![Build Status](https://travis-ci.org/kylewm/flask-micropub.svg?branch=master)](https://travis-ci.org/kylewm/flask-micropub) 4 | 5 | # Flask-Micropub 6 | 7 | A Flask extension to support IndieAuth and Micropub clients. 8 | 9 | ## Authentication 10 | 11 | Authentication uses the 12 | [IndieAuth](https://indiewebcamp.com/IndieAuth) flow to confirm a user 13 | controls a particular URL, without requesting any sort of permissions 14 | or access token. Annotate an endpoint with 15 | `@micropub.authenticated_handler` and then call 16 | `micropub.authenticate` to initiate the login. 17 | 18 | ## Authorization 19 | 20 | Authorization uses the full 21 | [Micropub](https://indiewebcamp.com/Micropub) flow to authenticate a 22 | user and then request an access token with which to make micropub 23 | requests. Annotate an endpoint with `@micropub.authorized_handler` and 24 | then call `micropub.authorize` to initiate the login. 25 | 26 | ## CSRF 27 | 28 | MicropubClient provides a simple mechanism to deter Cross-Site Request 29 | Forgery. Based on 30 | [this Flask snippet](http://flask.pocoo.org/snippets/3/), we generate 31 | a random string, pass it to the indieauth service via the state 32 | parameter, and then confirm we get the same random string back later. 33 | 34 | This helps prevent malicious sites from sending users to your 35 | indieauth endpoint against their will. 36 | 37 | ## Example 38 | 39 | ```python 40 | from flask import Flask, request, url_for 41 | from flask.ext.micropub import MicropubClient 42 | 43 | app = Flask(__name__) 44 | micropub = MicropubClient(app) 45 | 46 | 47 | @app.route('/login') 48 | def login(): 49 | return micropub.authorize( 50 | me, scope=request.args.get('scope')) 51 | 52 | 53 | @app.route('/micropub-callback') 54 | @micropub.authorized_handler 55 | def micropub_callback(resp): 56 | print('success!', resp.me, resp.access_token, resp.next_url, resp.error) 57 | 58 | ``` 59 | 60 | See example.py for a more thorough example. Protocol details at 61 | https://indiewebcamp.com/IndieAuth and 62 | https://indiewebcamp.com/Micropub 63 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | dependencies: 2 | pre: 3 | - pip install tox 4 | 5 | test: 6 | override: 7 | - tox 8 | -------------------------------------------------------------------------------- /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 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(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/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-Micropub.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-Micropub.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-Micropub" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-Micropub" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | .. automodule:: flask_micropub 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Flask-Micropub documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Dec 16 17:53:24 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | import shlex 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | #sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | 'sphinx.ext.autodoc', 34 | 'sphinx.ext.viewcode', 35 | 'sphinx.ext.napoleon', 36 | ] 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # The suffix(es) of source filenames. 42 | # You can specify multiple suffix as a list of string: 43 | # source_suffix = ['.rst', '.md'] 44 | source_suffix = '.rst' 45 | 46 | # The encoding of source files. 47 | #source_encoding = 'utf-8-sig' 48 | 49 | # The master toctree document. 50 | master_doc = 'index' 51 | 52 | # General information about the project. 53 | project = u'Flask-Micropub' 54 | copyright = u'2015, Kyle Mahan' 55 | author = u'Kyle Mahan' 56 | 57 | # The version info for the project you're documenting, acts as replacement for 58 | # |version| and |release|, also used in various other places throughout the 59 | # built documents. 60 | # 61 | # The short X.Y version. 62 | version = u'0.2.4' 63 | # The full version, including alpha/beta/rc tags. 64 | release = u'0.2.4' 65 | 66 | # The language for content autogenerated by Sphinx. Refer to documentation 67 | # for a list of supported languages. 68 | # 69 | # This is also used if you do content translation via gettext catalogs. 70 | # Usually you set "language" from the command line for these cases. 71 | language = None 72 | 73 | # There are two options for replacing |today|: either, you set today to some 74 | # non-false value, then it is used: 75 | #today = '' 76 | # Else, today_fmt is used as the format for a strftime call. 77 | #today_fmt = '%B %d, %Y' 78 | 79 | # List of patterns, relative to source directory, that match files and 80 | # directories to ignore when looking for source files. 81 | exclude_patterns = ['_build'] 82 | 83 | # The reST default role (used for this markup: `text`) to use for all 84 | # documents. 85 | #default_role = None 86 | 87 | # If true, '()' will be appended to :func: etc. cross-reference text. 88 | #add_function_parentheses = True 89 | 90 | # If true, the current module name will be prepended to all description 91 | # unit titles (such as .. function::). 92 | #add_module_names = True 93 | 94 | # If true, sectionauthor and moduleauthor directives will be shown in the 95 | # output. They are ignored by default. 96 | #show_authors = False 97 | 98 | # The name of the Pygments (syntax highlighting) style to use. 99 | pygments_style = 'sphinx' 100 | 101 | # A list of ignored prefixes for module index sorting. 102 | #modindex_common_prefix = [] 103 | 104 | # If true, keep warnings as "system message" paragraphs in the built documents. 105 | #keep_warnings = False 106 | 107 | # If true, `todo` and `todoList` produce output, else they produce nothing. 108 | todo_include_todos = False 109 | 110 | # -- Napoleon docstrings 111 | 112 | 113 | # Napoleon settings 114 | napoleon_google_docstring = True 115 | napoleon_numpy_docstring = False 116 | napoleon_include_private_with_doc = False 117 | napoleon_include_special_with_doc = True 118 | napoleon_use_admonition_for_examples = False 119 | napoleon_use_admonition_for_notes = False 120 | napoleon_use_admonition_for_references = False 121 | napoleon_use_ivar = False 122 | napoleon_use_param = True 123 | napoleon_use_rtype = True 124 | 125 | 126 | # -- Options for HTML output ---------------------------------------------- 127 | 128 | # The theme to use for HTML and HTML Help pages. See the documentation for 129 | # a list of builtin themes. 130 | html_theme = 'sphinx_rtd_theme' 131 | 132 | # Theme options are theme-specific and customize the look and feel of a theme 133 | # further. For a list of options available for each theme, see the 134 | # documentation. 135 | #html_theme_options = {} 136 | 137 | # Add any paths that contain custom themes here, relative to this directory. 138 | #html_theme_path = [] 139 | 140 | # The name for this set of Sphinx documents. If None, it defaults to 141 | # " v documentation". 142 | #html_title = None 143 | 144 | # A shorter title for the navigation bar. Default is the same as html_title. 145 | #html_short_title = None 146 | 147 | # The name of an image file (relative to this directory) to place at the top 148 | # of the sidebar. 149 | #html_logo = None 150 | 151 | # The name of an image file (within the static path) to use as favicon of the 152 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 153 | # pixels large. 154 | #html_favicon = None 155 | 156 | # Add any paths that contain custom static files (such as style sheets) here, 157 | # relative to this directory. They are copied after the builtin static files, 158 | # so a file named "default.css" will overwrite the builtin "default.css". 159 | html_static_path = ['_static'] 160 | 161 | # Add any extra paths that contain custom files (such as robots.txt or 162 | # .htaccess) here, relative to this directory. These files are copied 163 | # directly to the root of the documentation. 164 | #html_extra_path = [] 165 | 166 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 167 | # using the given strftime format. 168 | #html_last_updated_fmt = '%b %d, %Y' 169 | 170 | # If true, SmartyPants will be used to convert quotes and dashes to 171 | # typographically correct entities. 172 | #html_use_smartypants = True 173 | 174 | # Custom sidebar templates, maps document names to template names. 175 | #html_sidebars = {} 176 | 177 | # Additional templates that should be rendered to pages, maps page names to 178 | # template names. 179 | #html_additional_pages = {} 180 | 181 | # If false, no module index is generated. 182 | #html_domain_indices = True 183 | 184 | # If false, no index is generated. 185 | #html_use_index = True 186 | 187 | # If true, the index is split into individual pages for each letter. 188 | #html_split_index = False 189 | 190 | # If true, links to the reST sources are added to the pages. 191 | #html_show_sourcelink = True 192 | 193 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 194 | #html_show_sphinx = True 195 | 196 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 197 | #html_show_copyright = True 198 | 199 | # If true, an OpenSearch description file will be output, and all pages will 200 | # contain a tag referring to it. The value of this option must be the 201 | # base URL from which the finished HTML is served. 202 | #html_use_opensearch = '' 203 | 204 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 205 | #html_file_suffix = None 206 | 207 | # Language to be used for generating the HTML full-text search index. 208 | # Sphinx supports the following languages: 209 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 210 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 211 | #html_search_language = 'en' 212 | 213 | # A dictionary with options for the search language support, empty by default. 214 | # Now only 'ja' uses this config value 215 | #html_search_options = {'type': 'default'} 216 | 217 | # The name of a javascript file (relative to the configuration directory) that 218 | # implements a search results scorer. If empty, the default will be used. 219 | #html_search_scorer = 'scorer.js' 220 | 221 | # Output file base name for HTML help builder. 222 | htmlhelp_basename = 'Flask-Micropubdoc' 223 | 224 | # -- Options for LaTeX output --------------------------------------------- 225 | 226 | latex_elements = { 227 | # The paper size ('letterpaper' or 'a4paper'). 228 | #'papersize': 'letterpaper', 229 | 230 | # The font size ('10pt', '11pt' or '12pt'). 231 | #'pointsize': '10pt', 232 | 233 | # Additional stuff for the LaTeX preamble. 234 | #'preamble': '', 235 | 236 | # Latex figure (float) alignment 237 | #'figure_align': 'htbp', 238 | } 239 | 240 | # Grouping the document tree into LaTeX files. List of tuples 241 | # (source start file, target name, title, 242 | # author, documentclass [howto, manual, or own class]). 243 | latex_documents = [ 244 | (master_doc, 'Flask-Micropub.tex', u'Flask-Micropub Documentation', 245 | u'Kyle Mahan', 'manual'), 246 | ] 247 | 248 | # The name of an image file (relative to this directory) to place at the top of 249 | # the title page. 250 | #latex_logo = None 251 | 252 | # For "manual" documents, if this is true, then toplevel headings are parts, 253 | # not chapters. 254 | #latex_use_parts = False 255 | 256 | # If true, show page references after internal links. 257 | #latex_show_pagerefs = False 258 | 259 | # If true, show URL addresses after external links. 260 | #latex_show_urls = False 261 | 262 | # Documents to append as an appendix to all manuals. 263 | #latex_appendices = [] 264 | 265 | # If false, no module index is generated. 266 | #latex_domain_indices = True 267 | 268 | 269 | # -- Options for manual page output --------------------------------------- 270 | 271 | # One entry per manual page. List of tuples 272 | # (source start file, name, description, authors, manual section). 273 | man_pages = [ 274 | (master_doc, 'flask-micropub', u'Flask-Micropub Documentation', 275 | [author], 1) 276 | ] 277 | 278 | # If true, show URL addresses after external links. 279 | #man_show_urls = False 280 | 281 | 282 | # -- Options for Texinfo output ------------------------------------------- 283 | 284 | # Grouping the document tree into Texinfo files. List of tuples 285 | # (source start file, target name, title, author, 286 | # dir menu entry, description, category) 287 | texinfo_documents = [ 288 | (master_doc, 'Flask-Micropub', u'Flask-Micropub Documentation', 289 | author, 'Flask-Micropub', 'One line description of project.', 290 | 'Miscellaneous'), 291 | ] 292 | 293 | # Documents to append as an appendix to all manuals. 294 | #texinfo_appendices = [] 295 | 296 | # If false, no module index is generated. 297 | #texinfo_domain_indices = True 298 | 299 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 300 | #texinfo_show_urls = 'footnote' 301 | 302 | # If true, do not generate a @detailmenu in the "Top" node's menu. 303 | #texinfo_no_detailmenu = False 304 | -------------------------------------------------------------------------------- /docs/example.rst: -------------------------------------------------------------------------------- 1 | Example Usage 2 | ============= 3 | 4 | .. code:: python 5 | 6 | from flask import Flask, request, url_for 7 | from flask.ext.micropub import MicropubClient 8 | 9 | app = Flask(__name__) 10 | micropub = MicropubClient(app) 11 | 12 | 13 | @app.route('/login') 14 | def login(): 15 | return micropub.authorize( 16 | me, scope=request.args.get('scope')) 17 | 18 | 19 | @app.route('/micropub-callback') 20 | @micropub.authorized_handler 21 | def micropub_callback(resp): 22 | print('success!', resp.me, resp.access_token, resp.next_url, resp.error) 23 | 24 | See example.py for a more thorough example. Protocol details at 25 | https://indiewebcamp.com/IndieAuth and https://indiewebcamp.com/Micropub 26 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Flask-Micropub 2 | ============== 3 | 4 | A Flask extension to support IndieAuth and Micropub clients. 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | intro 10 | example 11 | api 12 | -------------------------------------------------------------------------------- /docs/intro.rst: -------------------------------------------------------------------------------- 1 | Flask-Micropub 2 | ============== 3 | 4 | A Flask extension to support IndieAuth and Micropub clients. 5 | 6 | Authentication 7 | -------------- 8 | 9 | Authentication uses the 10 | `IndieAuth `__ flow to confirm a 11 | user controls a particular URL, without requesting any sort of 12 | permissions or access token. Annotate an endpoint with 13 | ``@micropub.authenticated_handler`` and then call 14 | ``micropub.authenticate`` to initiate the login. 15 | 16 | Authorization 17 | ------------- 18 | 19 | Authorization uses the full 20 | `Micropub `__ flow to authenticate a 21 | user and then request an access token with which to make micropub 22 | requests. Annotate an endpoint with ``@micropub.authorized_handler`` and 23 | then call ``micropub.authorize`` to initiate the login. 24 | 25 | CSRF 26 | ---- 27 | 28 | MicropubClient provides a simple mechanism to deter Cross-Site Request 29 | Forgery. Based on `this Flask 30 | snippet `__, we generate a random 31 | string, pass it to the indieauth service via the state parameter, and 32 | then confirm we get the same random string back later. 33 | 34 | This helps prevent malicious sites from sending users to your indieauth 35 | endpoint against their will. 36 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 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. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 1>NUL 2>NUL 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Flask-Micropub.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Flask-Micropub.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, url_for 2 | from flask.ext.micropub import MicropubClient 3 | 4 | 5 | app = Flask(__name__) 6 | app.config['SECRET_KEY'] = 'my super secret key' 7 | micropub = MicropubClient(app) 8 | 9 | 10 | @app.route('/') 11 | def index(): 12 | return """ 13 | 14 | 15 | 16 |
17 | 18 | 19 |
20 |
21 | 22 | 27 | 28 |
29 | 30 | 31 | """ 32 | 33 | 34 | @app.route('/authenticate') 35 | def authenticate(): 36 | return micropub.authenticate( 37 | request.args.get('me'), next_url=url_for('index')) 38 | 39 | 40 | @app.route('/authorize') 41 | def authorize(): 42 | return micropub.authorize( 43 | request.args.get('me'), next_url=url_for('index'), 44 | scope=request.args.get('scope')) 45 | 46 | 47 | @app.route('/indieauth-callback') 48 | @micropub.authenticated_handler 49 | def indieauth_callback(resp): 50 | return """ 51 | 52 | 53 | 54 | Authenticated: 55 |
    56 |
  • me: {}
  • 57 |
  • next: {}
  • 58 |
  • error: {}
  • 59 |
60 | 61 | 62 | """.format(resp.me, resp.next_url, resp.error) 63 | 64 | 65 | @app.route('/micropub-callback') 66 | @micropub.authorized_handler 67 | def micropub_callback(resp): 68 | return """ 69 | 70 | 71 | 72 | Authorized: 73 |
    74 |
  • me: {}
  • 75 |
  • endpoint: {}
  • 76 |
  • token: {}
  • 77 |
  • next: {}
  • 78 |
  • error: {}
  • 79 |
80 | 81 | 82 | """.format(resp.me, resp.micropub_endpoint, resp.access_token, 83 | resp.next_url, resp.error) 84 | 85 | 86 | if __name__ == '__main__': 87 | app.run(debug=True) 88 | -------------------------------------------------------------------------------- /flask_micropub.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Flask-Micropub 4 | ============== 5 | 6 | This extension adds the ability to login to a Flask-based website 7 | using [IndieAuth](https://indiewebcamp.com/IndieAuth), and to request 8 | an [Micropub](https://indiewebcamp.com/Micropub) access token. 9 | """ 10 | 11 | import requests 12 | import bs4 13 | import flask 14 | import functools 15 | import uuid 16 | 17 | import sys 18 | if sys.version < '3': 19 | from urlparse import parse_qs 20 | from urllib import urlencode 21 | else: 22 | from urllib.parse import urlencode, parse_qs 23 | 24 | DEFAULT_AUTH_URL = 'https://indieauth.com/auth' 25 | 26 | 27 | class MicropubClient: 28 | """Flask-Micropub provides support for IndieAuth/Micropub 29 | authentication and authorization. 30 | """ 31 | 32 | def __init__(self, app=None, client_id=None): 33 | """Initialize the Micropub extension 34 | 35 | Args: 36 | app (flask.Flask, optional): the flask application to extend. 37 | client_id (string, optional): the IndieAuth client id, will be displayed 38 | when the user is asked to authorize this client. 39 | """ 40 | self.app = app 41 | self.client_id = client_id 42 | if app is not None: 43 | self.init_app(app, client_id) 44 | 45 | def init_app(self, app, client_id=None): 46 | """Initialize the Micropub extension if it was not given app 47 | in the constructor. 48 | 49 | Args: 50 | app (flask.Flask): the flask application to extend. 51 | client_id (string, optional): the IndieAuth client id, will be 52 | displayed when the user is asked to authorize this client. If not 53 | provided, the app name will be used. 54 | """ 55 | if not self.client_id: 56 | if client_id: 57 | self.client_id = client_id 58 | else: 59 | self.client_id = app.name 60 | 61 | def authenticate(self, me, state=None, next_url=None): 62 | """Authenticate a user via IndieAuth. 63 | 64 | Args: 65 | me (string): the authing user's URL. if it does not begin with 66 | https?://, http:// will be prepended. 67 | state (string, optional): passed through the whole auth process, 68 | useful if you want to maintain some state, e.g. the starting page 69 | to return to when auth is complete. 70 | next_url (string, optional): deprecated and replaced by the more 71 | general "state". still here for backward compatibility. 72 | 73 | Returns: 74 | a redirect to the user's specified authorization url, or 75 | https://indieauth.com/auth if none is provided. 76 | """ 77 | redirect_url = flask.url_for( 78 | self.flask_endpoint_for_function(self._authenticated_handler), 79 | _external=True) 80 | return self._start_indieauth(me, redirect_url, state or next_url, None) 81 | 82 | def authorize(self, me, state=None, next_url=None, scope='read'): 83 | """Authorize a user via Micropub. 84 | 85 | Args: 86 | me (string): the authing user's URL. if it does not begin with 87 | https?://, http:// will be prepended. 88 | state (string, optional): passed through the whole auth process, 89 | useful if you want to maintain some state, e.g. the starting page 90 | to return to when auth is complete. 91 | next_url (string, optional): deprecated and replaced by the more 92 | general "state". still here for backward compatibility. 93 | scope (string, optional): a space-separated string of micropub 94 | scopes. 'read' by default. 95 | 96 | Returns: 97 | a redirect to the user's specified authorization 98 | https://indieauth.com/auth if none is provided. 99 | """ 100 | redirect_url = flask.url_for( 101 | self.flask_endpoint_for_function(self._authorized_handler), 102 | _external=True) 103 | return self._start_indieauth( 104 | me, redirect_url, state or next_url, scope) 105 | 106 | def _start_indieauth(self, me, redirect_url, state, scope): 107 | """Helper for both authentication and authorization. Kicks off 108 | IndieAuth by fetching the authorization endpoint from the user's 109 | homepage and redirecting to it. 110 | 111 | Args: 112 | me (string): the authing user's URL. if it does not begin with 113 | https?://, http:// will be prepended. 114 | redirect_url: the callback URL that we pass to the auth endpoint. 115 | state (string, optional): passed through the whole auth process, 116 | useful if you want to maintain some state, e.g. the url to return 117 | to when the process is complete. 118 | scope (string): a space-separated string of micropub scopes. 119 | 120 | Returns: 121 | a redirect to the user's specified authorization 122 | https://indieauth.com/auth if none is provided. 123 | """ 124 | 125 | if not me.startswith('http://') and not me.startswith('https://'): 126 | me = 'http://' + me 127 | auth_url, token_url, micropub_url = self._discover_endpoints(me) 128 | if not auth_url: 129 | auth_url = DEFAULT_AUTH_URL 130 | 131 | csrf_token = uuid.uuid4().hex 132 | flask.session['_micropub_csrf_token'] = csrf_token 133 | 134 | auth_params = { 135 | 'me': me, 136 | 'client_id': self.client_id, 137 | 'redirect_uri': redirect_url, 138 | 'response_type': 'code', 139 | 'state': '{}|{}'.format(csrf_token, state or ''), 140 | } 141 | if scope: 142 | auth_params['scope'] = scope 143 | 144 | auth_url = auth_url + '?' + urlencode(auth_params) 145 | flask.current_app.logger.debug('redirecting to %s', auth_url) 146 | 147 | return flask.redirect(auth_url) 148 | 149 | def authenticated_handler(self, f): 150 | """Decorates the authentication callback endpoint. The endpoint should 151 | take one argument, a flask.ext.micropub.AuthResponse. 152 | """ 153 | @functools.wraps(f) 154 | def decorated(): 155 | resp = self._handle_authenticate_response() 156 | return f(resp) 157 | self._authenticated_handler = decorated 158 | return decorated 159 | 160 | def authorized_handler(self, f): 161 | """Decorates the authorization callback endpoint. The endpoint should 162 | take one argument, a flask.ext.micropub.AuthResponse. 163 | """ 164 | @functools.wraps(f) 165 | def decorated(): 166 | resp = self._handle_authorize_response() 167 | return f(resp) 168 | self._authorized_handler = decorated 169 | return decorated 170 | 171 | def _handle_authenticate_response(self): 172 | code = flask.request.args.get('code') 173 | wrapped_state = flask.request.args.get('state') 174 | me = flask.request.args.get('me') 175 | redirect_uri = flask.url_for(flask.request.endpoint, _external=True) 176 | 177 | if wrapped_state and '|' in wrapped_state: 178 | csrf_token, state = wrapped_state.split('|', 1) 179 | else: 180 | csrf_token = state = None 181 | 182 | if not csrf_token: 183 | return AuthResponse( 184 | state=state, error='no CSRF token in response') 185 | 186 | if csrf_token != flask.session.get('_micropub_csrf_token'): 187 | return AuthResponse( 188 | state=state, error='mismatched CSRF token') 189 | 190 | auth_url = self._discover_endpoints(me)[0] 191 | if not auth_url: 192 | auth_url = DEFAULT_AUTH_URL 193 | 194 | # validate the authorization code 195 | auth_data = { 196 | 'code': code, 197 | 'client_id': self.client_id, 198 | 'redirect_uri': redirect_uri, 199 | 'state': wrapped_state, 200 | } 201 | flask.current_app.logger.debug( 202 | 'Flask-Micropub: checking code against auth url: %s, data: %s', 203 | auth_url, auth_data) 204 | response = requests.post(auth_url, data=auth_data) 205 | flask.current_app.logger.debug( 206 | 'Flask-Micropub: auth response: %d - %s', response.status_code, 207 | response.text) 208 | 209 | try: 210 | rdata = dict((k,[v]) for (k,v) in response.json().items()) 211 | except ValueError: 212 | rdata = parse_qs(response.text) 213 | if response.status_code < 200 or response.status_code >= 300: 214 | error_vals = rdata.get('error') 215 | error_descs = rdata.get('error_description') 216 | return AuthResponse( 217 | state=state, 218 | error='authorization failed. {}: {}'.format( 219 | error_vals[0] if error_vals else 'Unknown Error', 220 | error_descs[0] if error_descs else 'Unknown Error')) 221 | 222 | if 'me' not in rdata: 223 | return AuthResponse( 224 | state=state, 225 | error='missing "me" in response') 226 | 227 | confirmed_me = rdata.get('me')[0] 228 | return AuthResponse(me=confirmed_me, state=state) 229 | 230 | def _handle_authorize_response(self): 231 | code = flask.request.args.get('code') 232 | wrapped_state = flask.request.args.get('state') 233 | me = flask.request.args.get('me') 234 | redirect_uri = flask.url_for(flask.request.endpoint, _external=True) 235 | 236 | if wrapped_state and '|' in wrapped_state: 237 | csrf_token, state = wrapped_state.split('|', 1) 238 | else: 239 | csrf_token = state = None 240 | 241 | if not csrf_token: 242 | return AuthResponse( 243 | state=state, error='no CSRF token in response') 244 | 245 | if csrf_token != flask.session.get('_micropub_csrf_token'): 246 | return AuthResponse( 247 | state=state, error='mismatched CSRF token') 248 | 249 | token_url, micropub_url = self._discover_endpoints(me)[1:] 250 | 251 | if not token_url or not micropub_url: 252 | # successfully auth'ed user, no micropub endpoint 253 | return AuthResponse( 254 | me=me, 255 | state=state, 256 | error='no micropub endpoint found.') 257 | 258 | # request an access token 259 | token_data = { 260 | 'code': code, 261 | 'me': me, 262 | 'redirect_uri': redirect_uri, 263 | 'client_id': self.client_id, 264 | 'state': wrapped_state, 265 | 'grant_type': 'authorization_code', 266 | } 267 | flask.current_app.logger.debug( 268 | 'Flask-Micropub: requesting access token from: %s, data: %s', 269 | token_url, token_data) 270 | token_response = requests.post(token_url, data=token_data) 271 | flask.current_app.logger.debug( 272 | 'Flask-Micropub: token response: %d - %s', 273 | token_response.status_code, token_response.text) 274 | 275 | if token_response.status_code < 200 or token_response.status_code >= 300: 276 | return AuthResponse( 277 | me=me, 278 | state=state, 279 | error='bad response from token endpoint: {}' 280 | .format(token_response)) 281 | 282 | try: 283 | tdata = dict((k,[v]) for (k,v) in token_response.json().items()) 284 | except ValueError: 285 | tdata = parse_qs(token_response.text) 286 | if 'access_token' not in tdata: 287 | return AuthResponse( 288 | me=me, 289 | state=state, 290 | error='response from token endpoint missing access_token: {}' 291 | .format(tdata)) 292 | 293 | # success! 294 | access_token = tdata.get('access_token')[0] 295 | confirmed_me = tdata.get('me')[0] 296 | confirmed_scope = tdata.get('scope')[0] 297 | return AuthResponse( 298 | me=confirmed_me, 299 | micropub_endpoint=micropub_url, 300 | access_token=access_token, 301 | scope=confirmed_scope, 302 | state=state) 303 | 304 | def _discover_endpoints(self, me): 305 | me_response = requests.get(me) 306 | if me_response.status_code < 200 or me_response.status_code >= 300: 307 | return None, None, None 308 | 309 | auth_endpoint = me_response.links.get('authorization_endpoint', {}).get('url') 310 | token_endpoint = me_response.links.get('token_endpoint', {}).get('url') 311 | micropub_endpoint = me_response.links.get('micropub', {}).get('url') 312 | 313 | if not auth_endpoint or not token_endpoint or not micropub_endpoint: 314 | soup = bs4.BeautifulSoup(me_response.text) 315 | if not auth_endpoint: 316 | auth_link = soup.find('link', {'rel': 'authorization_endpoint'}) 317 | auth_endpoint = auth_link and auth_link['href'] 318 | if not token_endpoint: 319 | token_link = soup.find('link', {'rel': 'token_endpoint'}) 320 | token_endpoint = token_link and token_link['href'] 321 | if not micropub_endpoint: 322 | micropub_link = soup.find('link', {'rel': 'micropub'}) 323 | micropub_endpoint = micropub_link and micropub_link['href'] 324 | 325 | return auth_endpoint, token_endpoint, micropub_endpoint 326 | 327 | @staticmethod 328 | def flask_endpoint_for_function(func): 329 | for endpt, view_func in flask.current_app.view_functions.items(): 330 | if func == view_func: 331 | return endpt 332 | 333 | 334 | class AuthResponse: 335 | """Authorization response, passed to the authorized_handler endpoint. 336 | 337 | Attributes: 338 | me (string): The authenticated user's URL. This will be non-None if and 339 | only if the user was successfully authenticated. 340 | micropub_endpoint (string): The endpoint to POST micropub requests to. 341 | access_token (string): The authorized user's micropub access token. 342 | state (string): The optional state that was passed to authorize. 343 | scope (string): The scope that comes with the micropub access token 344 | error (string): describes the error encountered if any. It is possible 345 | that the authentication step will succeed but the access token step 346 | will fail, in which case me will be non-None, and error will describe 347 | this condition. 348 | """ 349 | def __init__(self, me=None, micropub_endpoint=None, 350 | access_token=None, state=None, scope=None, 351 | error=None): 352 | self.me = me 353 | self.micropub_endpoint = micropub_endpoint 354 | self.access_token = access_token 355 | self.next_url = self.state = state 356 | self.scope = scope 357 | self.error = error 358 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Flask-Micropub 3 | -------------- 4 | 5 | This extension adds the ability to login to a Flask-based website 6 | using IndieAuth (https://indiewebcamp.com/IndieAuth), and to request 7 | a Micropub (https://indiewebcamp.com/Micropub) access token. 8 | """ 9 | from setuptools import setup 10 | 11 | 12 | setup( 13 | name='Flask-Micropub', 14 | version='0.2.8', 15 | url='https://github.com/kylewm/flask-micropub/', 16 | license='BSD', 17 | author='Kyle Mahan', 18 | author_email='kyle@kylewm.com', 19 | description='Adds support for Micropub clients.', 20 | long_description=__doc__, 21 | py_modules=['flask_micropub'], 22 | zip_safe=False, 23 | include_package_data=True, 24 | platforms='any', 25 | install_requires=[ 26 | 'Flask', 27 | 'requests', 28 | 'BeautifulSoup4', 29 | ], 30 | tests_require=[ 31 | 'mock', 32 | ], 33 | test_suite='tests', 34 | classifiers=[ 35 | 'Environment :: Web Environment', 36 | 'Intended Audience :: Developers', 37 | 'License :: OSI Approved :: BSD License', 38 | 'Operating System :: OS Independent', 39 | 'Development Status :: 3 - Alpha', 40 | 'Programming Language :: Python', 41 | 'Programming Language :: Python :: 3', 42 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 43 | 'Topic :: Software Development :: Libraries :: Python Modules', 44 | ] 45 | ) 46 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/karadaisy/flask-micropub/897c75848c441758d61c11e36c02ae9c1f786950/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_micropub_client.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import unicode_literals, print_function 3 | 4 | import collections 5 | import json 6 | import os 7 | import unittest 8 | import requests 9 | 10 | import flask_micropub 11 | 12 | try: 13 | from unittest import mock 14 | except: 15 | import mock 16 | 17 | 18 | class MicropubClientTest(unittest.TestCase): 19 | 20 | def setUp(self): 21 | self.client = flask_micropub.MicropubClient() 22 | 23 | @mock.patch('requests.get') 24 | def test_discover_endpoints_from_http_header(self, get_method): 25 | r = requests.Response() 26 | r.headers['Link'] = ';rel=authorization_endpoint, ;rel=token_endpoint, ;rel=micropub' 27 | r.status_code = 200 28 | get_method.return_value = r 29 | result = self.client._discover_endpoints('http://foo.bar/') 30 | get_method.assert_called_once_with('http://foo.bar/') 31 | self.assertEqual(('http://foo.bar/auth', 'http://baz.bux/token', 'http://do.re/micropub'), result) 32 | 33 | @mock.patch('requests.get') 34 | def test_discover_endpoints_from_html(self, get_method): 35 | r = requests.Response() 36 | r._content = """ 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | """.encode('utf-8') 48 | r.status_code = 200 49 | get_method.return_value = r 50 | result = self.client._discover_endpoints('http://foo.bar/') 51 | get_method.assert_called_once_with('http://foo.bar/') 52 | self.assertEqual(('http://foo.bar/auth', 'http://baz.bux/token', 'http://do.re/micropub'), result) 53 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # content of: tox.ini , put in same dir as setup.py 2 | [tox] 3 | envlist = py27, py34 4 | [testenv] 5 | deps = mock 6 | commands = python -m unittest discover 7 | --------------------------------------------------------------------------------