♻ Implement login dialog through UiPlugin
Otherwise alternative UIs might still be wide open, and caching and such was also really painful to solve before. The LoginUI Plugin is pretty much just a distilled ForceLogin plugin. Also declared it as hidden so it won't show up/be manageable by the plugin manager.
This commit is contained in:
1 parent
38c09153ac
commit
a75c641c18
11 files changed
+364
-56
No files matched your search
@@ -130,6 +130,14 @@ class PluginInfo(object):
|
||||
Bundled plugins will automatically be assumed to be compatible.
|
||||
"""
|
||||
|
||||
attr_hidden = '__plugin_hidden__'
|
||||
"""
|
||||
Module attribute from which to determine if the plugin's hidden or not.
|
||||
|
||||
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
|
||||
and similar places.
|
||||
"""
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
""" Module attribute from which to retrieve the plugin's provided hooks. """
|
||||
|
||||
@@ -444,6 +452,18 @@ class PluginInfo(object):
|
||||
default=">=2.7,<3",
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def hidden(self):
|
||||
"""
|
||||
Hidden flag.
|
||||
|
||||
Returns:
|
||||
bool: Whether the plugin should be flagged as hidden or not
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_hidden,
|
||||
default=False,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
"""
|
||||
@@ -600,6 +620,16 @@ class PluginInfo(object):
|
||||
result[key] = a.value.args[0].s
|
||||
|
||||
break
|
||||
|
||||
for key in (self.__class__.attr_hidden,):
|
||||
for a in reversed(assignments):
|
||||
targets = extract_target_ids(a)
|
||||
if key in targets:
|
||||
if isinstance(a.value, ast.Name) and a.value.id in ("True", "False"):
|
||||
result[key] = bool(a.value.id)
|
||||
|
||||
break
|
||||
|
||||
except SyntaxError:
|
||||
self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key))
|
||||
self.invalid_syntax = True
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
from collections import defaultdict
|
||||
import threading
|
||||
|
||||
class LoginUiPlugin(octoprint.plugin.UiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
MAX_BACKLOG_LEN = 100
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._message_backlog = defaultdict(list)
|
||||
self._message_backlog_mutex = threading.RLock()
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
# we are only active if ACL is enabled AND configured
|
||||
return self._user_manager.enabled and self._user_manager.has_been_customized()
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/viewmodel.js"]
|
||||
)
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
if not self.active:
|
||||
# not active, not responsible
|
||||
return False
|
||||
|
||||
from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException
|
||||
from octoprint.server.util.flask import passive_login
|
||||
|
||||
# first try to login via api key & authorization header, just in case that's set
|
||||
try:
|
||||
if loginUserFromApiKey():
|
||||
# successful? No need for handling the UI
|
||||
return False
|
||||
except InvalidApiKeyException:
|
||||
pass # ignored
|
||||
|
||||
if loginUserFromAuthorizationHeader():
|
||||
# successful? No need for handling the UI
|
||||
return False
|
||||
|
||||
# then try a passive login
|
||||
passive_login()
|
||||
if Permissions.STATUS.can() and Permissions.SETTINGS_READ.can():
|
||||
# Status & settings_read permission? No need to handle UI
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
from flask import render_template, make_response
|
||||
|
||||
def add_additional_assets(hook):
|
||||
result = []
|
||||
for name, hook in self._plugin_manager.get_hooks(hook).items():
|
||||
try:
|
||||
assets = hook()
|
||||
if isinstance(assets, (tuple, list)):
|
||||
result += assets
|
||||
except:
|
||||
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
return result
|
||||
|
||||
additional_assets = []
|
||||
additional_assets += add_additional_assets("octoprint.plugin.loginui.theming")
|
||||
|
||||
# backwards compatibility to old forcelogin plugin which was replaced by this one
|
||||
additional_assets += add_additional_assets("octoprint.plugin.forcelogin.theming")
|
||||
|
||||
render_kwargs.update(dict(loginui_theming=additional_assets))
|
||||
return make_response(render_template("loginui_index.jinja2", **render_kwargs))
|
||||
|
||||
def get_ui_custom_tracked_files(self):
|
||||
from os.path import join as opj
|
||||
|
||||
paths = [opj("static", "css", "loginui.css"),
|
||||
opj("static", "js", "main.js"),
|
||||
opj("static", "js", "viewmodel.js"),
|
||||
opj("static", "less", "loginui.less"),
|
||||
opj("templates", "parts", "loginui_css.jinja2"),
|
||||
opj("templates", "parts", "loginui_javascripts.jinja2"),
|
||||
opj("templates", "loginui_index.jinja2")]
|
||||
|
||||
return [opj(self._basefolder, path) for path in paths]
|
||||
|
||||
def get_ui_preemptive_caching_enabled(self):
|
||||
return False
|
||||
|
||||
def get_sorting_key(self, context=None):
|
||||
if context == "UiPlugin.on_ui_render":
|
||||
# If a plugin *really* wants to come before this plugin, it'll have to turn to negative numbers.
|
||||
#
|
||||
# This is obviously discouraged for security reasons, but very specific setups might make it necessary,
|
||||
# so we make it possible. If this should get abused long term we can always turn this into -inf.
|
||||
return 0
|
||||
|
||||
__plugin_name__ = "Login UI"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Displays a standalone login UI if needed"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin there will be no dedicated login page for users in "
|
||||
"case anonymous read only access is disabled - instead your non logged in "
|
||||
"visitors will get a broken UI.")
|
||||
__plugin_hidden__ = True
|
||||
|
||||
__plugin_implementation__ = LoginUiPlugin()
|
||||
@@ -0,0 +1 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Will get included into the login dialog, NOT into the regular OctoPrint
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
var offlineElement = $("#login-offline");
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
|
||||
var username = usernameElement.val();
|
||||
var password = passwordElement.val();
|
||||
var remember = rememberElement.prop("checked");
|
||||
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
location.reload();
|
||||
})
|
||||
.fail(function() {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
overlayElement.removeClass("in");
|
||||
errorElement.addClass("in");
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
OctoPrint.socket.connect();
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* View model that takes care to redirect to / on logout in the regular
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
function LoginUiViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.onUserLoggedOut = self.onUserPermissionsChanged = function() {
|
||||
if (!self.loginState.hasAllPermissions(self.access.permissions.STATUS, self.access.permissions.SETTINGS_READ) && !CONFIG_FIRST_RUN) {
|
||||
location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: LoginUiViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
body {
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 0 auto 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e5e5e5;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
|
||||
.form-signin-heading, .checkbox {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
margin-bottom: 15px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
}
|
||||
|
||||
#login-error,
|
||||
#login-offline {
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
|
||||
&.in {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
|
||||
.outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
|
||||
.content {
|
||||
text-align: center;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-25
@@ -9,32 +9,9 @@
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
|
||||
|
||||
<!-- le CSS -->
|
||||
{% include "parts/loginui_css.jinja2" %}
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="forcelogin/css/forcelogin.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("static", filename="forcelogin/js/forcelogin.js") }}"></script>
|
||||
{% include "parts/loginui_javascripts.jinja2" %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
@@ -0,0 +1,10 @@
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("plugin.loginui.static", filename="css/loginui.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("plugin.loginui.static", filename="js/main.js") }}"></script>
|
||||
@@ -780,7 +780,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return True
|
||||
|
||||
def command_toggle(self, plugin, command):
|
||||
if plugin.key == "pluginmanager":
|
||||
if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled):
|
||||
return make_response("Can't enable/disable Plugin Manager", 400)
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
@@ -1161,7 +1161,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hidden = self._settings.get(["hidden"])
|
||||
result = []
|
||||
for key, plugin in plugins.items():
|
||||
if key in hidden:
|
||||
if key in hidden or (plugin.bundled and plugin.hidden):
|
||||
continue
|
||||
result.append(self._to_external_plugin(plugin))
|
||||
|
||||
@@ -1235,6 +1235,7 @@ __plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_hidden__ = True
|
||||
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
|
||||
@@ -12,7 +12,7 @@ import io
|
||||
from past.builtins import basestring
|
||||
|
||||
from collections import defaultdict
|
||||
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
|
||||
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort, Response
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -367,7 +367,7 @@ def index():
|
||||
|
||||
return view(now, request, render_kwargs)
|
||||
|
||||
def ui_view():
|
||||
def default_view():
|
||||
filtered_templates = _filter_templates(_templates[locale], default_template_filter)
|
||||
|
||||
wizard = wizard_active(filtered_templates)
|
||||
@@ -407,33 +407,6 @@ def index():
|
||||
dict())
|
||||
return preemptively_cached()
|
||||
|
||||
def login_view():
|
||||
return util.flask.add_non_caching_response_headers(make_response(render_template("forcelogin.jinja2")))
|
||||
|
||||
def evaluate_login():
|
||||
from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException
|
||||
from octoprint.server.util.flask import passive_login
|
||||
|
||||
# first try to login via api key & authorization header, just in case that's set
|
||||
try:
|
||||
loginUserFromApiKey()
|
||||
except InvalidApiKeyException:
|
||||
pass # ignored
|
||||
loginUserFromAuthorizationHeader()
|
||||
|
||||
# then try a passive login
|
||||
passive_login()
|
||||
|
||||
def default_view():
|
||||
evaluate_login()
|
||||
|
||||
if request.headers.get("X-Preemptive-Record", None) == "no" \
|
||||
or (Permissions.STATUS.can() and Permissions.SETTINGS_READ.can()) \
|
||||
or settings().getBoolean(["server", "firstRun"]):
|
||||
return ui_view()
|
||||
else:
|
||||
return login_view()
|
||||
|
||||
response = None
|
||||
|
||||
forced_view = request.headers.get("X-Force-View", None)
|
||||
@@ -445,8 +418,12 @@ def index():
|
||||
plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True)
|
||||
if plugin is not None and isinstance(plugin.implementation, octoprint.plugin.UiPlugin):
|
||||
response = plugin_view(plugin.implementation)
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
response.headers["X-Ui-Plugin"] = plugin._identifier
|
||||
else:
|
||||
response = default_view()
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
response.headers["X-Ui-Plugin"] = "_default"
|
||||
|
||||
else:
|
||||
# select view from plugins and fall back on default view if no plugin will handle it
|
||||
@@ -457,6 +434,8 @@ def index():
|
||||
# plugin claims responsibility, let it render the UI
|
||||
response = plugin_view(plugin)
|
||||
if response is not None:
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
response.headers["X-Ui-Plugin"] = plugin._identifier
|
||||
break
|
||||
else:
|
||||
_logger.warning("UiPlugin {} returned an empty response".format(plugin._identifier))
|
||||
@@ -465,6 +444,8 @@ def index():
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
else:
|
||||
response = default_view()
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
response.headers["X-Ui-Plugin"] = "_default"
|
||||
|
||||
if response is None:
|
||||
return abort(404)
|
||||
|
||||
Reference in new issue
Block a user