2015-01-19 17:01:56 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
Flask-Micropub
|
|
|
|
==============
|
|
|
|
|
|
|
|
This extension adds the ability to login to a Flask-based website
|
|
|
|
using [IndieAuth](https://indiewebcamp.com/IndieAuth), and to request
|
|
|
|
an [Micropub](https://indiewebcamp.com/Micropub) access token.
|
2015-01-19 07:10:03 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
import requests
|
|
|
|
import bs4
|
|
|
|
import flask
|
|
|
|
import functools
|
2015-02-04 06:45:08 +00:00
|
|
|
import uuid
|
2015-01-19 07:10:03 +00:00
|
|
|
|
|
|
|
import sys
|
2015-01-19 17:01:56 +00:00
|
|
|
if sys.version < '3':
|
2015-01-19 07:10:03 +00:00
|
|
|
from urlparse import parse_qs
|
|
|
|
from urllib import urlencode
|
2015-01-19 17:01:56 +00:00
|
|
|
else:
|
|
|
|
from urllib.parse import urlencode, parse_qs
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-06-22 06:35:45 +01:00
|
|
|
DEFAULT_AUTH_URL = 'https://indieauth.com/auth'
|
|
|
|
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-01-28 16:37:47 +00:00
|
|
|
class MicropubClient:
|
2015-01-19 17:01:56 +00:00
|
|
|
"""Flask-Micropub provides support for IndieAuth/Micropub
|
|
|
|
authentication and authorization.
|
|
|
|
"""
|
2015-12-16 18:12:31 +00:00
|
|
|
|
2015-01-19 17:01:56 +00:00
|
|
|
def __init__(self, app=None, client_id=None):
|
2015-12-16 18:12:31 +00:00
|
|
|
"""Initialize the Micropub extension
|
|
|
|
|
|
|
|
Args:
|
|
|
|
app (flask.Flask, optional): the flask application to extend.
|
|
|
|
client_id (string, optional): the IndieAuth client id, will be displayed
|
|
|
|
when the user is asked to authorize this client.
|
|
|
|
"""
|
2015-01-19 07:10:03 +00:00
|
|
|
self.app = app
|
2015-02-03 06:49:20 +00:00
|
|
|
self.client_id = client_id
|
2015-01-19 07:10:03 +00:00
|
|
|
if app is not None:
|
2015-01-19 17:01:56 +00:00
|
|
|
self.init_app(app, client_id)
|
|
|
|
|
|
|
|
def init_app(self, app, client_id=None):
|
|
|
|
"""Initialize the Micropub extension if it was not given app
|
|
|
|
in the constructor.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
app (flask.Flask): the flask application to extend.
|
|
|
|
client_id (string, optional): the IndieAuth client id, will be
|
|
|
|
displayed when the user is asked to authorize this client. If not
|
|
|
|
provided, the app name will be used.
|
|
|
|
"""
|
2015-02-03 06:49:20 +00:00
|
|
|
if not self.client_id:
|
|
|
|
if client_id:
|
|
|
|
self.client_id = client_id
|
|
|
|
else:
|
|
|
|
self.client_id = app.name
|
2015-01-19 17:01:56 +00:00
|
|
|
|
2015-12-14 03:50:54 +00:00
|
|
|
def authenticate(self, me, state=None, next_url=None):
|
2015-02-07 17:40:31 +00:00
|
|
|
"""Authenticate a user via IndieAuth.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
me (string): the authing user's URL. if it does not begin with
|
|
|
|
https?://, http:// will be prepended.
|
2015-12-14 03:50:54 +00:00
|
|
|
state (string, optional): passed through the whole auth process,
|
|
|
|
useful if you want to maintain some state, e.g. the starting page
|
|
|
|
to return to when auth is complete.
|
|
|
|
next_url (string, optional): deprecated and replaced by the more
|
|
|
|
general "state". still here for backward compatibility.
|
2015-02-07 17:40:31 +00:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
a redirect to the user's specified authorization url, or
|
|
|
|
https://indieauth.com/auth if none is provided.
|
|
|
|
"""
|
|
|
|
redirect_url = flask.url_for(
|
2015-02-07 20:23:06 +00:00
|
|
|
self.flask_endpoint_for_function(self._authenticated_handler),
|
|
|
|
_external=True)
|
2015-12-14 03:50:54 +00:00
|
|
|
return self._start_indieauth(me, redirect_url, state or next_url, None)
|
2015-02-07 17:40:31 +00:00
|
|
|
|
2015-12-14 03:50:54 +00:00
|
|
|
def authorize(self, me, state=None, next_url=None, scope='read'):
|
2015-01-19 17:01:56 +00:00
|
|
|
"""Authorize a user via Micropub.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
me (string): the authing user's URL. if it does not begin with
|
|
|
|
https?://, http:// will be prepended.
|
2015-12-14 03:50:54 +00:00
|
|
|
state (string, optional): passed through the whole auth process,
|
|
|
|
useful if you want to maintain some state, e.g. the starting page
|
|
|
|
to return to when auth is complete.
|
|
|
|
next_url (string, optional): deprecated and replaced by the more
|
|
|
|
general "state". still here for backward compatibility.
|
2015-01-19 17:01:56 +00:00
|
|
|
scope (string, optional): a space-separated string of micropub
|
|
|
|
scopes. 'read' by default.
|
|
|
|
|
|
|
|
Returns:
|
2015-02-07 17:40:31 +00:00
|
|
|
a redirect to the user's specified authorization
|
|
|
|
https://indieauth.com/auth if none is provided.
|
|
|
|
"""
|
|
|
|
redirect_url = flask.url_for(
|
2015-02-07 20:23:06 +00:00
|
|
|
self.flask_endpoint_for_function(self._authorized_handler),
|
|
|
|
_external=True)
|
2015-12-14 03:50:54 +00:00
|
|
|
return self._start_indieauth(
|
|
|
|
me, redirect_url, state or next_url, scope)
|
2015-02-07 17:40:31 +00:00
|
|
|
|
2015-12-14 03:50:54 +00:00
|
|
|
def _start_indieauth(self, me, redirect_url, state, scope):
|
2015-02-07 17:40:31 +00:00
|
|
|
"""Helper for both authentication and authorization. Kicks off
|
|
|
|
IndieAuth by fetching the authorization endpoint from the user's
|
|
|
|
homepage and redirecting to it.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
me (string): the authing user's URL. if it does not begin with
|
|
|
|
https?://, http:// will be prepended.
|
|
|
|
redirect_url: the callback URL that we pass to the auth endpoint.
|
2015-12-14 03:50:54 +00:00
|
|
|
state (string, optional): passed through the whole auth process,
|
|
|
|
useful if you want to maintain some state, e.g. the url to return
|
|
|
|
to when the process is complete.
|
2015-02-07 17:40:31 +00:00
|
|
|
scope (string): a space-separated string of micropub scopes.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
a redirect to the user's specified authorization
|
2015-01-19 17:01:56 +00:00
|
|
|
https://indieauth.com/auth if none is provided.
|
|
|
|
"""
|
2015-02-07 17:40:31 +00:00
|
|
|
|
2015-01-19 07:10:03 +00:00
|
|
|
if not me.startswith('http://') and not me.startswith('https://'):
|
|
|
|
me = 'http://' + me
|
|
|
|
auth_url, token_url, micropub_url = self._discover_endpoints(me)
|
|
|
|
if not auth_url:
|
2015-06-22 06:35:45 +01:00
|
|
|
auth_url = DEFAULT_AUTH_URL
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-02-04 06:45:08 +00:00
|
|
|
csrf_token = uuid.uuid4().hex
|
|
|
|
flask.session['_micropub_csrf_token'] = csrf_token
|
2015-01-19 17:01:56 +00:00
|
|
|
|
2015-02-07 17:40:31 +00:00
|
|
|
auth_params = {
|
2015-01-19 07:10:03 +00:00
|
|
|
'me': me,
|
|
|
|
'client_id': self.client_id,
|
2015-01-19 17:01:56 +00:00
|
|
|
'redirect_uri': redirect_url,
|
2017-03-10 03:18:20 +00:00
|
|
|
'response_type': 'code',
|
2015-12-14 03:50:54 +00:00
|
|
|
'state': '{}|{}'.format(csrf_token, state or ''),
|
2015-02-07 17:40:31 +00:00
|
|
|
}
|
|
|
|
if scope:
|
|
|
|
auth_params['scope'] = scope
|
|
|
|
|
|
|
|
auth_url = auth_url + '?' + urlencode(auth_params)
|
2015-02-04 06:45:08 +00:00
|
|
|
flask.current_app.logger.debug('redirecting to %s', auth_url)
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-02-04 06:45:08 +00:00
|
|
|
return flask.redirect(auth_url)
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-02-07 17:40:31 +00:00
|
|
|
def authenticated_handler(self, f):
|
|
|
|
"""Decorates the authentication callback endpoint. The endpoint should
|
|
|
|
take one argument, a flask.ext.micropub.AuthResponse.
|
|
|
|
"""
|
|
|
|
@functools.wraps(f)
|
|
|
|
def decorated():
|
2016-01-27 07:54:40 +00:00
|
|
|
resp = self._handle_authenticate_response()
|
2015-02-07 17:40:31 +00:00
|
|
|
return f(resp)
|
|
|
|
self._authenticated_handler = decorated
|
|
|
|
return decorated
|
|
|
|
|
2015-01-19 07:10:03 +00:00
|
|
|
def authorized_handler(self, f):
|
2015-01-19 17:01:56 +00:00
|
|
|
"""Decorates the authorization callback endpoint. The endpoint should
|
|
|
|
take one argument, a flask.ext.micropub.AuthResponse.
|
|
|
|
"""
|
2015-01-19 07:10:03 +00:00
|
|
|
@functools.wraps(f)
|
2015-01-19 17:01:56 +00:00
|
|
|
def decorated():
|
2015-02-07 17:40:31 +00:00
|
|
|
resp = self._handle_authorize_response()
|
2015-01-19 17:01:56 +00:00
|
|
|
return f(resp)
|
2015-02-07 17:40:31 +00:00
|
|
|
self._authorized_handler = decorated
|
2015-01-19 07:10:03 +00:00
|
|
|
return decorated
|
|
|
|
|
2015-02-07 17:40:31 +00:00
|
|
|
def _handle_authenticate_response(self):
|
|
|
|
code = flask.request.args.get('code')
|
2015-12-14 03:50:54 +00:00
|
|
|
wrapped_state = flask.request.args.get('state')
|
2015-05-31 17:16:40 +01:00
|
|
|
me = flask.request.args.get('me')
|
2015-02-07 17:40:31 +00:00
|
|
|
redirect_uri = flask.url_for(flask.request.endpoint, _external=True)
|
|
|
|
|
2015-12-14 03:50:54 +00:00
|
|
|
if wrapped_state and '|' in wrapped_state:
|
|
|
|
csrf_token, state = wrapped_state.split('|', 1)
|
2015-02-04 06:45:08 +00:00
|
|
|
else:
|
2015-12-14 03:50:54 +00:00
|
|
|
csrf_token = state = None
|
2015-02-04 06:45:08 +00:00
|
|
|
|
|
|
|
if not csrf_token:
|
|
|
|
return AuthResponse(
|
2015-12-14 03:50:54 +00:00
|
|
|
state=state, error='no CSRF token in response')
|
2015-02-04 06:45:08 +00:00
|
|
|
|
|
|
|
if csrf_token != flask.session.get('_micropub_csrf_token'):
|
|
|
|
return AuthResponse(
|
2015-12-14 03:50:54 +00:00
|
|
|
state=state, error='mismatched CSRF token')
|
2015-01-19 17:01:56 +00:00
|
|
|
|
2015-05-31 17:16:40 +01:00
|
|
|
auth_url = self._discover_endpoints(me)[0]
|
2015-01-19 07:10:03 +00:00
|
|
|
if not auth_url:
|
2015-06-22 06:35:45 +01:00
|
|
|
auth_url = DEFAULT_AUTH_URL
|
2015-01-19 07:10:03 +00:00
|
|
|
|
|
|
|
# validate the authorization code
|
2015-02-04 06:45:08 +00:00
|
|
|
auth_data = {
|
2015-01-19 07:10:03 +00:00
|
|
|
'code': code,
|
2015-02-03 06:49:20 +00:00
|
|
|
'client_id': self.client_id,
|
2015-01-19 07:10:03 +00:00
|
|
|
'redirect_uri': redirect_uri,
|
2015-12-14 03:50:54 +00:00
|
|
|
'state': wrapped_state,
|
2015-02-04 06:45:08 +00:00
|
|
|
}
|
|
|
|
flask.current_app.logger.debug(
|
|
|
|
'Flask-Micropub: checking code against auth url: %s, data: %s',
|
|
|
|
auth_url, auth_data)
|
|
|
|
response = requests.post(auth_url, data=auth_data)
|
|
|
|
flask.current_app.logger.debug(
|
|
|
|
'Flask-Micropub: auth response: %d - %s', response.status_code,
|
|
|
|
response.text)
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2017-03-10 04:33:43 +00:00
|
|
|
try:
|
|
|
|
rdata = dict((k,[v]) for (k,v) in response.json().items())
|
|
|
|
except ValueError:
|
|
|
|
rdata = parse_qs(response.text)
|
2016-03-18 18:34:04 +00:00
|
|
|
if response.status_code < 200 or response.status_code >= 300:
|
2015-02-02 16:42:38 +00:00
|
|
|
error_vals = rdata.get('error')
|
|
|
|
error_descs = rdata.get('error_description')
|
2015-01-19 17:01:56 +00:00
|
|
|
return AuthResponse(
|
2015-12-14 03:50:54 +00:00
|
|
|
state=state,
|
2015-01-19 17:01:56 +00:00
|
|
|
error='authorization failed. {}: {}'.format(
|
2015-02-02 16:42:38 +00:00
|
|
|
error_vals[0] if error_vals else 'Unknown Error',
|
|
|
|
error_descs[0] if error_descs else 'Unknown Error'))
|
2015-01-19 07:10:03 +00:00
|
|
|
|
|
|
|
if 'me' not in rdata:
|
2015-01-19 17:01:56 +00:00
|
|
|
return AuthResponse(
|
2015-12-14 03:50:54 +00:00
|
|
|
state=state,
|
2015-01-19 17:01:56 +00:00
|
|
|
error='missing "me" in response')
|
2015-01-19 07:10:03 +00:00
|
|
|
|
|
|
|
confirmed_me = rdata.get('me')[0]
|
2015-12-14 03:50:54 +00:00
|
|
|
return AuthResponse(me=confirmed_me, state=state)
|
2015-02-07 17:40:31 +00:00
|
|
|
|
|
|
|
def _handle_authorize_response(self):
|
|
|
|
code = flask.request.args.get('code')
|
2015-12-14 03:50:54 +00:00
|
|
|
wrapped_state = flask.request.args.get('state')
|
2015-05-31 17:16:40 +01:00
|
|
|
me = flask.request.args.get('me')
|
2015-02-07 17:40:31 +00:00
|
|
|
redirect_uri = flask.url_for(flask.request.endpoint, _external=True)
|
|
|
|
|
2016-01-27 15:24:55 +00:00
|
|
|
if wrapped_state and '|' in wrapped_state:
|
|
|
|
csrf_token, state = wrapped_state.split('|', 1)
|
|
|
|
else:
|
|
|
|
csrf_token = state = None
|
|
|
|
|
|
|
|
if not csrf_token:
|
|
|
|
return AuthResponse(
|
|
|
|
state=state, error='no CSRF token in response')
|
|
|
|
|
|
|
|
if csrf_token != flask.session.get('_micropub_csrf_token'):
|
|
|
|
return AuthResponse(
|
|
|
|
state=state, error='mismatched CSRF token')
|
2015-02-07 17:40:31 +00:00
|
|
|
|
2015-05-31 17:16:40 +01:00
|
|
|
token_url, micropub_url = self._discover_endpoints(me)[1:]
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-01-19 17:01:56 +00:00
|
|
|
if not token_url or not micropub_url:
|
|
|
|
# successfully auth'ed user, no micropub endpoint
|
|
|
|
return AuthResponse(
|
2016-01-27 15:24:55 +00:00
|
|
|
me=me,
|
|
|
|
state=state,
|
2015-01-19 17:01:56 +00:00
|
|
|
error='no micropub endpoint found.')
|
|
|
|
|
2015-01-19 07:10:03 +00:00
|
|
|
# request an access token
|
2015-02-04 06:45:08 +00:00
|
|
|
token_data = {
|
2015-01-19 07:10:03 +00:00
|
|
|
'code': code,
|
2016-01-27 15:24:55 +00:00
|
|
|
'me': me,
|
2015-01-19 07:10:03 +00:00
|
|
|
'redirect_uri': redirect_uri,
|
2015-02-03 06:49:20 +00:00
|
|
|
'client_id': self.client_id,
|
2015-12-14 03:50:54 +00:00
|
|
|
'state': wrapped_state,
|
2017-03-10 03:32:19 +00:00
|
|
|
'grant_type': 'authorization_code',
|
2015-02-04 06:45:08 +00:00
|
|
|
}
|
|
|
|
flask.current_app.logger.debug(
|
|
|
|
'Flask-Micropub: requesting access token from: %s, data: %s',
|
|
|
|
token_url, token_data)
|
|
|
|
token_response = requests.post(token_url, data=token_data)
|
|
|
|
flask.current_app.logger.debug(
|
|
|
|
'Flask-Micropub: token response: %d - %s',
|
|
|
|
token_response.status_code, token_response.text)
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2016-03-18 18:34:04 +00:00
|
|
|
if token_response.status_code < 200 or token_response.status_code >= 300:
|
2015-01-19 17:01:56 +00:00
|
|
|
return AuthResponse(
|
2016-01-27 15:24:55 +00:00
|
|
|
me=me,
|
|
|
|
state=state,
|
2015-01-19 17:01:56 +00:00
|
|
|
error='bad response from token endpoint: {}'
|
|
|
|
.format(token_response))
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2017-03-10 04:33:43 +00:00
|
|
|
try:
|
|
|
|
tdata = dict((k,[v]) for (k,v) in token_response.json().items())
|
|
|
|
except ValueError:
|
|
|
|
tdata = parse_qs(token_response.text)
|
2015-01-19 07:10:03 +00:00
|
|
|
if 'access_token' not in tdata:
|
2015-01-19 17:01:56 +00:00
|
|
|
return AuthResponse(
|
2016-01-27 15:24:55 +00:00
|
|
|
me=me,
|
|
|
|
state=state,
|
2015-01-19 17:01:56 +00:00
|
|
|
error='response from token endpoint missing access_token: {}'
|
|
|
|
.format(tdata))
|
2015-01-19 07:10:03 +00:00
|
|
|
|
2015-01-19 17:01:56 +00:00
|
|
|
# success!
|
2015-01-19 07:10:03 +00:00
|
|
|
access_token = tdata.get('access_token')[0]
|
2016-01-27 15:24:55 +00:00
|
|
|
confirmed_me = tdata.get('me')[0]
|
|
|
|
confirmed_scope = tdata.get('scope')[0]
|
2015-02-07 17:40:31 +00:00
|
|
|
return AuthResponse(
|
2016-01-27 15:24:55 +00:00
|
|
|
me=confirmed_me,
|
2015-02-07 17:40:31 +00:00
|
|
|
micropub_endpoint=micropub_url,
|
|
|
|
access_token=access_token,
|
2016-01-27 15:24:55 +00:00
|
|
|
scope=confirmed_scope,
|
|
|
|
state=state)
|
2015-01-19 07:10:03 +00:00
|
|
|
|
|
|
|
def _discover_endpoints(self, me):
|
|
|
|
me_response = requests.get(me)
|
2016-03-18 18:34:04 +00:00
|
|
|
if me_response.status_code < 200 or me_response.status_code >= 300:
|
2015-01-19 07:10:03 +00:00
|
|
|
return None, None, None
|
|
|
|
|
2016-03-18 16:30:49 +00:00
|
|
|
auth_endpoint = me_response.links.get('authorization_endpoint', {}).get('url')
|
|
|
|
token_endpoint = me_response.links.get('token_endpoint', {}).get('url')
|
|
|
|
micropub_endpoint = me_response.links.get('micropub', {}).get('url')
|
|
|
|
|
|
|
|
if not auth_endpoint or not token_endpoint or not micropub_endpoint:
|
|
|
|
soup = bs4.BeautifulSoup(me_response.text)
|
|
|
|
if not auth_endpoint:
|
|
|
|
auth_link = soup.find('link', {'rel': 'authorization_endpoint'})
|
|
|
|
auth_endpoint = auth_link and auth_link['href']
|
|
|
|
if not token_endpoint:
|
|
|
|
token_link = soup.find('link', {'rel': 'token_endpoint'})
|
|
|
|
token_endpoint = token_link and token_link['href']
|
|
|
|
if not micropub_endpoint:
|
|
|
|
micropub_link = soup.find('link', {'rel': 'micropub'})
|
|
|
|
micropub_endpoint = micropub_link and micropub_link['href']
|
|
|
|
|
|
|
|
return auth_endpoint, token_endpoint, micropub_endpoint
|
2015-01-19 17:01:56 +00:00
|
|
|
|
2015-02-07 20:23:06 +00:00
|
|
|
@staticmethod
|
|
|
|
def flask_endpoint_for_function(func):
|
|
|
|
for endpt, view_func in flask.current_app.view_functions.items():
|
|
|
|
if func == view_func:
|
|
|
|
return endpt
|
|
|
|
|
2015-01-19 17:01:56 +00:00
|
|
|
|
|
|
|
class AuthResponse:
|
|
|
|
"""Authorization response, passed to the authorized_handler endpoint.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
me (string): The authenticated user's URL. This will be non-None if and
|
|
|
|
only if the user was successfully authenticated.
|
2015-01-19 17:44:56 +00:00
|
|
|
micropub_endpoint (string): The endpoint to POST micropub requests to.
|
2015-01-19 17:01:56 +00:00
|
|
|
access_token (string): The authorized user's micropub access token.
|
2015-12-14 03:50:54 +00:00
|
|
|
state (string): The optional state that was passed to authorize.
|
2016-01-27 15:24:55 +00:00
|
|
|
scope (string): The scope that comes with the micropub access token
|
2015-01-19 17:01:56 +00:00
|
|
|
error (string): describes the error encountered if any. It is possible
|
|
|
|
that the authentication step will succeed but the access token step
|
|
|
|
will fail, in which case me will be non-None, and error will describe
|
|
|
|
this condition.
|
|
|
|
"""
|
2015-01-19 17:44:56 +00:00
|
|
|
def __init__(self, me=None, micropub_endpoint=None,
|
2016-01-27 15:24:55 +00:00
|
|
|
access_token=None, state=None, scope=None,
|
|
|
|
error=None):
|
2015-01-19 17:01:56 +00:00
|
|
|
self.me = me
|
2015-01-19 17:44:56 +00:00
|
|
|
self.micropub_endpoint = micropub_endpoint
|
2015-01-19 17:01:56 +00:00
|
|
|
self.access_token = access_token
|
2015-12-14 03:50:54 +00:00
|
|
|
self.next_url = self.state = state
|
2016-01-27 15:24:55 +00:00
|
|
|
self.scope = scope
|
2015-01-19 17:01:56 +00:00
|
|
|
self.error = error
|