55 lines
1.9 KiB
Python
55 lines
1.9 KiB
Python
from flask import Blueprint, current_app, redirect, url_for, request
|
|
|
|
blueprint = Blueprint(
|
|
'matrix_iframe',
|
|
__name__,
|
|
template_folder='templates',
|
|
static_folder='static',
|
|
static_url_path='/static/matrix_iframe',
|
|
)
|
|
|
|
def init_app(app, server_url='', room_alias='', login_endpoint=None):
|
|
"""
|
|
Register the Matrix chat blueprint with a Flask app.
|
|
|
|
The blueprint serves static assets (JS + CSS) and injects
|
|
matrix_chat_available, matrix_server_url, and matrix_room_alias
|
|
into every template context so the host app's layout can mount
|
|
the chat overlay widget.
|
|
|
|
Args:
|
|
server_url: Matrix homeserver base URL, e.g. "https://matrix.sticknife.com"
|
|
room_alias: Matrix room alias, e.g. "#sticknife-library:matrix.sticknife.com"
|
|
login_endpoint: Flask endpoint to redirect unauthenticated users to,
|
|
e.g. "web.login". If None, no auth guard is applied.
|
|
"""
|
|
app.config.setdefault('MATRIX_SERVER_URL', server_url)
|
|
app.config.setdefault('MATRIX_ROOM_ALIAS', room_alias)
|
|
app.config.setdefault('MATRIX_CHAT_LOGIN_ENDPOINT', login_endpoint)
|
|
app.register_blueprint(blueprint)
|
|
|
|
|
|
@blueprint.app_context_processor
|
|
def _inject_matrix_chat():
|
|
"""Injects matrix chat config into every template when the blueprint is registered."""
|
|
return {
|
|
'matrix_chat_available': True,
|
|
'matrix_server_url': current_app.config.get('MATRIX_SERVER_URL', ''),
|
|
'matrix_room_alias': current_app.config.get('MATRIX_ROOM_ALIAS', ''),
|
|
}
|
|
|
|
|
|
@blueprint.before_request
|
|
def _auth_guard():
|
|
login_endpoint = current_app.config.get('MATRIX_CHAT_LOGIN_ENDPOINT')
|
|
if not login_endpoint:
|
|
return
|
|
try:
|
|
from flask_login import current_user
|
|
if not current_user.is_authenticated:
|
|
return redirect(url_for(login_endpoint, next=request.url))
|
|
except ImportError:
|
|
pass
|
|
|
|
|