Flask wrapper¶
AuthlFlask is an easy-to-use wrapper for use with Flask . By
default it gives you a login form (with optional URL tester) and a login
endpoint that stores the verified identity in flask.session['me']. All this
behavior is configurable.
The basic usage is very simple:
import flask
import authl.flask
app = flask.Flask(__name__)
app.secret_key = "extremely secret"
authl.flask.setup(app, {
# Simple IndieAuth setup
'INDIEAUTH_CLIENT_ID': authl.flask.client_id,
# Minimal Fediverse setup
'FEDIVERSE_NAME': 'My website',
# Send email using localhost
'EMAIL_FROM': 'me@example.com',
'SMTP_HOST': 'localhost',
'SMTP_PORT': 25
}, tester_path='/test')
@app.route('/')
if 'me' in flask.session:
return 'Hello {me}. Want to <a href="{logout}">log out</a>?'.format(
me=flask.session['me'], logout=flask.url_for(
'logout', redir=flask.request.path[1:])
)
return 'You are not logged in. Want to <a href="{login}">log in</a>?'.format(
login=flask.url_for('authl.login', redir=flask.request.path[1:]))
@app.route('/logout')
def logout():
flask.session.clear()
return flask.redirect('/')
This gives you a very simple login form configured to work with IndieAuth,
Fediverse, and email at the default location of /login, and a logout
mechanism at /logout. The endpoint at /test can be used to test an
identity URL for login support.
- class authl.flask.AuthlFlask(app: Flask, config: Dict[str, Any], *, login_name: str = 'authl.login', login_path: str = '/login', callback_name: str = 'authl.callback', callback_path: str = '/cb', tester_name: str = 'authl.test', tester_path: str | None = None, login_render_func: Callable | None = None, notify_render_func: Callable | None = None, post_form_render_func: Callable | None = None, session_auth_name: str | None = 'me', force_https: bool = False, stylesheet: str | Callable | None = None, on_verified: Callable | None = None, make_permanent: bool = True, state_storage: Dict | None = None, token_storage: TokenStore | None = None, session_namespace='_authl')¶
Easy Authl wrapper for use with a Flask application.
- Parameters:
app (flask.Flask) – the application to attach to
config (dict) – Configuration directives for Authl’s handlers. See from_config for more information.
login_name (str) – The endpoint name for the login handler, for flask.url_for()
login_path (str) –
The mount point of the login endpoint
The login endpoint takes the following arguments (as specified via
flask.url_for()):me: The URL to initiate authentication forredir: Where to redirect the user to after successful login
callback_name (str) – The endpoint name for the callback handler, for flask.url_for()
callback_path (str) – The mount point of the callback handler endpoints. For example, if this is set to
/login_cbthen your actual handler callbacks will be at/login_cb/{cb_id}for the handler’scb_idproperty; for example, theauthl.handlers.email_addr.EmailAddresshandler’s callback will be mounted at/login_cb/e.tester_name (str) – The endpoint name for the URL tester, for flask.url_for()
tester_path (str) –
The mount point of the URL tester endpoint
The URL tester endpoint takes a query parameter of
urlwhich is the URL to check. It returns a JSON object that describes the detected handler (if any), with the following attributes:name: the service nameurl: a canonicized version of the URL
The URL tester endpoint will only be mounted if
tester_pathis specified. This will also enable a small asynchronous preview in the default login form.login_render_func (function) –
The function to call to render the login page; if not specified a default will be provided.
This function takes the following arguments; note that more may be added so it should also take a
**kwargsfor future compatibility:auth: theauthl.Authlobjectlogin_url: the URL to use for the login formtester_url: the URL to use for the test callbackredir: The redirection destination that the login URL willredirect them to
id_url: Any pre-filled value for the ID urlerror: Any error message that occurred
If
login_render_funcreturns a falsy value, the default login form will be used instead. This is useful for providing a conditional override, or as a rudimentary hook for analytics on the login flow or the like.notify_render_func (function) –
The function to call to render the user notification page; if not specified a default will be provided.
This function takes the following arguments:
cdata: the client data for the handler
post_form_render_func (function) –
The function to call to render a necessary post-login form; if not specified a default will be provided.
This function takes the following arguments:
message: the notification message for the userdata: the data to pass along in the POST requesturl: the URL to send the POST request to
session_auth_name (str) – The session parameter to use for the authenticated user. Set to None if you want to use your own session management.
force_https (bool) – Whether to force authentication to switch to a
https://connectionstylesheet (str) – the URL to use for the default page stylesheet; if not
on_verified (function) –
A function to call on successful login (called after setting the session value)
This function receives the
authl.disposition.Verifiedobject, and may return a Flask response of its own, which should ideally be aflask.redirect(). This can be used to capture more information about the user (such as filling out a user profile) or to redirect certain users to an administrative screen of some sort.make_permanent (bool) – Whether a session should persist past the browser window closing
token_storage (tokens.TokenStore) –
Storage for token data for methods which use it. Uses the same default as
authl.from_config().Note that if the default is used, the
app.secret_keyMUST be set before this class is initialized.state_storage – The mechanism to use for transactional state storage for login methods that need it. Defaults to using the Flask user session.
session_namespace – A namespace for Authl to keep a small amount of user session data in. Should never need to be changed.
- render_login_form(destination: str, error: str | None = None)¶
Renders the login form. This might be called by the Flask app if, for example, a page requires login to be seen.
- Parameters:
destination (str) – The redirection destination, as a full path (e.g.
'/path/to/view')error (str) – Any error message to display on the login form
- property stylesheet: str¶
The stylesheet to use for the Flask templates
- property url_scheme¶
Provide the _scheme parameter to be sent along to flask.url_for
- authl.flask.client_id()¶
A shim to generate a client ID based on the current site URL, for use with IndieAuth, Fediverse, and so on.
- authl.flask.load_template(filename: str) str¶
Load the built-in Flask template.
- Parameters:
filename (str) – The filename of the built-in template
Raises FileNotFoundError on no such template
- Returns:
the contents of the template.
- authl.flask.setup(app: Flask, config: Dict[str, Any], **kwargs) Authl¶
Simple setup function.
- Parameters:
app (flask.flask) – The Flask app to configure with Authl.
config (dict) – Configuration values for the Authl instance; see
authl.from_config()kwargs – Additional arguments to pass along to the
AuthlFlaskconstructor
- Returns:
The configured
authl.Authlinstance. Note that if you want theAuthlFlaskinstance you should instantiate that directly.