From a75c641c189a1107e46bb47a08201e4d4ed397ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 25 Feb 2020 15:33:42 +0100 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=20Implement=20login=20dialog=20throug?= =?UTF-8?q?h=20UiPlugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/octoprint/plugin/core.py | 30 +++++ src/octoprint/plugins/loginui/__init__.py | 120 ++++++++++++++++++ .../plugins/loginui/static/css/loginui.css | 1 + .../plugins/loginui/static/js/main.js | 59 +++++++++ .../plugins/loginui/static/js/viewmodel.js | 24 ++++ .../plugins/loginui/static/less/loginui.less | 90 +++++++++++++ .../loginui/templates/loginui_index.jinja2} | 27 +--- .../templates/parts/loginui_css.jinja2 | 10 ++ .../parts/loginui_javascripts.jinja2 | 15 +++ .../plugins/pluginmanager/__init__.py | 5 +- src/octoprint/server/views.py | 39 ++---- 11 files changed, 364 insertions(+), 56 deletions(-) create mode 100644 src/octoprint/plugins/loginui/__init__.py create mode 100644 src/octoprint/plugins/loginui/static/css/loginui.css create mode 100644 src/octoprint/plugins/loginui/static/js/main.js create mode 100644 src/octoprint/plugins/loginui/static/js/viewmodel.js create mode 100644 src/octoprint/plugins/loginui/static/less/loginui.less rename src/octoprint/{templates/forcelogin.jinja2 => plugins/loginui/templates/loginui_index.jinja2} (64%) create mode 100644 src/octoprint/plugins/loginui/templates/parts/loginui_css.jinja2 create mode 100644 src/octoprint/plugins/loginui/templates/parts/loginui_javascripts.jinja2 diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index d6f2ee3b8..f7956fe5e 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -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 diff --git a/src/octoprint/plugins/loginui/__init__.py b/src/octoprint/plugins/loginui/__init__.py new file mode 100644 index 000000000..1e8bf018b --- /dev/null +++ b/src/octoprint/plugins/loginui/__init__.py @@ -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() diff --git a/src/octoprint/plugins/loginui/static/css/loginui.css b/src/octoprint/plugins/loginui/static/css/loginui.css new file mode 100644 index 000000000..73e8fe2af --- /dev/null +++ b/src/octoprint/plugins/loginui/static/css/loginui.css @@ -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} \ No newline at end of file diff --git a/src/octoprint/plugins/loginui/static/js/main.js b/src/octoprint/plugins/loginui/static/js/main.js new file mode 100644 index 000000000..b053fafa6 --- /dev/null +++ b/src/octoprint/plugins/loginui/static/js/main.js @@ -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(); +}); diff --git a/src/octoprint/plugins/loginui/static/js/viewmodel.js b/src/octoprint/plugins/loginui/static/js/viewmodel.js new file mode 100644 index 000000000..2e1df3d9c --- /dev/null +++ b/src/octoprint/plugins/loginui/static/js/viewmodel.js @@ -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"] + }); +}); diff --git a/src/octoprint/plugins/loginui/static/less/loginui.less b/src/octoprint/plugins/loginui/static/less/loginui.less new file mode 100644 index 000000000..615f51202 --- /dev/null +++ b/src/octoprint/plugins/loginui/static/less/loginui.less @@ -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; + } + } + } + } +} diff --git a/src/octoprint/templates/forcelogin.jinja2 b/src/octoprint/plugins/loginui/templates/loginui_index.jinja2 similarity index 64% rename from src/octoprint/templates/forcelogin.jinja2 rename to src/octoprint/plugins/loginui/templates/loginui_index.jinja2 index 48c3a3ab2..05448dd47 100644 --- a/src/octoprint/templates/forcelogin.jinja2 +++ b/src/octoprint/plugins/loginui/templates/loginui_index.jinja2 @@ -9,32 +9,9 @@ - + {% include "parts/loginui_css.jinja2" %} - - - - - - {% for url in forcelogin_theming %} - - {% endfor %} - - - - - - - - - - {% assets "js_client" %} - - {% endassets %} - - + {% include "parts/loginui_javascripts.jinja2" %}
diff --git a/src/octoprint/plugins/loginui/templates/parts/loginui_css.jinja2 b/src/octoprint/plugins/loginui/templates/parts/loginui_css.jinja2 new file mode 100644 index 000000000..fd1539e75 --- /dev/null +++ b/src/octoprint/plugins/loginui/templates/parts/loginui_css.jinja2 @@ -0,0 +1,10 @@ + + + + + + + +{% for url in forcelogin_theming %} + +{% endfor %} diff --git a/src/octoprint/plugins/loginui/templates/parts/loginui_javascripts.jinja2 b/src/octoprint/plugins/loginui/templates/parts/loginui_javascripts.jinja2 new file mode 100644 index 000000000..768433232 --- /dev/null +++ b/src/octoprint/plugins/loginui/templates/parts/loginui_javascripts.jinja2 @@ -0,0 +1,15 @@ + + + + + + + + +{% assets "js_client" %} + +{% endassets %} + + diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 575222b7e..21a9c4dd2 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -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__ diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index f2f667039..60aa35401 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -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)