From 25cd4f8201fc09352ba947e41fe4ec3c3175a336 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Aug 2018 11:58:56 +0200 Subject: [PATCH 01/10] Add no_firstrun_access decorator --- src/octoprint/server/util/flask.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 2ab536e36..8cca9c541 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1133,11 +1133,7 @@ def restricted_access(func): """ @functools.wraps(func) def decorated_view(*args, **kwargs): - # if OctoPrint hasn't been set up yet, abort - if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): - return flask.make_response("OctoPrint isn't setup yet", 403) - - return flask_login.login_required(func)(*args, **kwargs) + return flask_login.login_required(no_firstrun_access(func))(*args, **kwargs) return decorated_view @@ -1159,6 +1155,24 @@ def firstrun_only_access(func): return decorated_view +def no_firstrun_access(func): + """ + If you decorate a view with this, it will ensure that first setup as been done for + OctoPrint's Access Control. Otherwise it + will cause a HTTP 403 status code to be returned by the decorated resource. + """ + + @functools.wraps(func) + def decorated_view(*args, **kwargs): + # if OctoPrint hasn't been set up yet, abort + if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and \ + (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): + return flask.make_response("OctoPrint isn't setup yet", 403) + return func(*args, **kwargs) + + return decorated_view + + class AppSessionManager(object): VALIDITY_UNVERIFIED = 1 * 60 # 1 minute From 5a5785be4aa11c963068a7f7cac82cf3bcac3425 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Aug 2018 11:59:23 +0200 Subject: [PATCH 02/10] Appauth plugin: WIP --- src/octoprint/plugins/appauth/__init__.py | 269 ++++++++++++++++++ .../plugins/appauth/static/js/appauth.js | 169 +++++++++++ .../templates/appauth_usersettings.jinja2 | 42 +++ 3 files changed, 480 insertions(+) create mode 100644 src/octoprint/plugins/appauth/__init__.py create mode 100644 src/octoprint/plugins/appauth/static/js/appauth.js create mode 100644 src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 diff --git a/src/octoprint/plugins/appauth/__init__.py b/src/octoprint/plugins/appauth/__init__.py new file mode 100644 index 000000000..08d0bcf6b --- /dev/null +++ b/src/octoprint/plugins/appauth/__init__.py @@ -0,0 +1,269 @@ +# coding=utf-8 +from __future__ import absolute_import + +import flask +import threading +import os +from binascii import hexlify +from collections import defaultdict + +import octoprint.plugin +from octoprint.settings import valid_boolean_trues +from octoprint.server.util.flask import restricted_access, no_firstrun_access +from octoprint.server import NO_CONTENT, current_user, user_permission + + +class AppAlreadyExists(Exception): + pass + + +class PendingDecision(object): + def __init__(self, app_id, app_token, user_id, user_token): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + + def external(self): + return dict(app_id=self.app_id, + user_id=self.user_id, + user_token=self.user_token) + + +class ReadyDecision(object): + def __init__(self, app_id, app_token, user_id, api_key): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.api_key = api_key + + @classmethod + def for_pending(cls, pending, api_key): + return cls(pending.app_id, pending.app_token, pending.user_id, api_key) + + +class ActiveKey(object): + def __init__(self, app_id, api_key): + self.app_id = app_id + self.api_key = api_key + + def external(self): + return dict(app_id=self.app_id, + api_key=self.api_key) + + +class AppAuthPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin): + + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + ##-- AssetPlugin hooks + + def get_assets(self): + return dict(js=["js/appauth.js"]) + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if not "app" in data: + return flask.make_response("No app name provided", 400) + + app_name = data["app"] + user_id = None + if "user" in data: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access", + app_name=app_name, + user_token=user_token, + user_id=user_id)) + response = flask.jsonify(app_token=app_token) + response.status_code = 202 + response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + if self._is_pending(app_token): + return flask.make_response("Awaiting decision", 202) + + result = self._get_decision(app_token) + if result is not None: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if not "decision" in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return dict(generate=["app"], + revoke=["key"]) + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + return flask.jsonify(keys=map(lambda x: x.external(), self._api_keys_for_user(user_id)), + pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id))) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + self._delete_api_key(user_id, api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + api_key = self._generate_key() + try: + self._add_api_key(user_id, app_name.trim(), api_key) + except AppAlreadyExists: + return flask.abort(409) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token)) + + return app_token, user_token + + def _is_pending(self, app_token): + with self._pending_lock: + for data in self._pending_decisions: + if data.app_token == app_token: + return True + + return False + + def _get_pending(self, user_id): + result = [] + with self._pending_lock: + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + for data in self._pending_decisions: + if data.user_token == user_token and (data.user_id == user_id or data.user_id is None): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, self._generate_key())) + + with self._pending_lock: + self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions) + + return True + + def _get_decision(self, app_token): + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + self._add_api_key(decision.user_id, decision.app_id, decision.api_key) + + with self._ready_lock: + self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions) + + return decision.api_key + + def _add_api_key(self, user_id, app_name, api_key): + with self._keys_lock: + # TODO: persist to disk + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + raise AppAlreadyExists("app {} does already exist".format(app_name)) + self._keys[user_id].append(ActiveKey(app_name, api_key)) + + def _delete_api_key(self, user_id, api_key): + with self._keys_lock: + # TODO: persist to disk + self._keys[user_id] = filter(lambda x: x.api_key != api_key, self._keys[user_id]) + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if filter(lambda x: x.api_key == api_key, data): + return self._user_manager.findUser(userid=user_id) + return None + + def _api_keys_for_user(self, user_id): + with self._keys_lock: + return self._keys.get(user_id, []) + + def _generate_key(self): + return hexlify(os.urandom(16)) + +__plugin_name__ = "AppAuth Plugin" +__plugin_description__ = "TODO" +__plugin_author__ = "Gina Häußge, Aldo Hoeben" +__plugin_implementation__ = AppAuthPlugin() +__plugin_hooks__ = { + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key +} diff --git a/src/octoprint/plugins/appauth/static/js/appauth.js b/src/octoprint/plugins/appauth/static/js/appauth.js new file mode 100644 index 000000000..74ec1e6e1 --- /dev/null +++ b/src/octoprint/plugins/appauth/static/js/appauth.js @@ -0,0 +1,169 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintAppAuthClient = function(base) { + this.base = base; + }; + + OctoPrintAppAuthClient.prototype.getKeys = function(opts) { + return this.base.simpleApiGet("appauth", opts); + }; + + OctoPrintAppAuthClient.prototype.generateKey = function(app, opts) { + return this.base.simpleApiCommand("appauth", "generate", {"app": app}, opts); + }; + + OctoPrintAppAuthClient.prototype.revokeKey = function(key, opts) { + return this.base.simpleApiCommand("appauth", "revoke", {"key": key}, opts); + }; + + OctoPrintAppAuthClient.prototype.decide = function(token, decision, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appauth") + "decision/" + token, {decision: !!decision}, opts); + }; + + OctoPrintClient.registerPluginComponent("appauth", OctoPrintAppAuthClient); + return OctoPrintAppAuthClient; +}); + +$(function() { + function AppAuthViewModel(parameters) { + var self = this; + self.loginState = parameters[0]; + + self.keys = new ItemListHelper( + "plugin.appauth.keys", + { + "app": function (a, b) { + // sorts descending + if (a["app"] > b["app"]) return -1; + if (a["app"] < b["app"]) return 1; + return 0; + } + }, + { + }, + "app", + [], + [], + 10 + ); + self.pending = {}; + self.openRequests = {}; + + self.editorApp = ko.observable(); + + self.requestData = function() { + OctoPrint.plugins.appauth.getKeys() + .done(self.fromResponse); + }; + + self.fromResponse = function(response) { + self.keys.updateItems(response.keys); + self.pending = response.pending; + _.each(self.pending, function(data, token) { + self.openRequests[token] = self.promptForAccess(data.app_id, token); + }) + }; + + self.generateKey = function() { + return OctoPrint.plugins.appauth.generateKey(self.editorApp()) + .done(self.requestData); + }; + + self.revokeKey = function(key) { + return OctoPrint.plugins.appauth.revokeKey(key) + .done(self.requestData); + }; + + self.allowApp = function(token) { + return OctoPrint.plugins.appauth.decide(token, true) + .done(self.requestData); + }; + + self.denyApp = function(token) { + return OctoPrint.plugins.appauth.decide(token, false) + .done(self.requestData); + }; + + self.promptForAccess = function(app, token) { + var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API. Do you want to allow access to this application with your user account?"); + message = _.sprintf(message, {app: app}); + + return new PNotify({ + title: gettext("Access Request"), + text: message, + confirm: { + confirm: true, + buttons: [{ + text: gettext("Allow"), + click: function(notice) { + self.allowApp(token); + } + }, { + text: gettext("Deny"), + click: function(notice) { + self.denyApp(token); + } + }] + }, + buttons: { + sticker: false, + closer: false + } + }); + }; + + self.onUserSettingsShown = function() { + self.requestData(); + }; + + self.onUserLoggedIn = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (plugin !== "appauth") { + return; + } + + var app, token, user; + + if (data.type === "request_access" && self.loginState.isUser()) { + app = data.app_name; + token = data.user_token; + user = data.user_id; + + if (user && user !== self.loginState.username()) { + return; + } + + if (self.pending[token] === undefined) { + return; + } + + self.openRequests[token] = self.promptForAccess(app, token); + + } else if (data.type === "end_request") { + token = data.user_token; + + if (self.openRequests[token] !== undefined) { + // another instance responded to the access request before the current user did + if (self.openRequests[token].state !== "closed") { + self.openRequests[token].remove(); + } + delete self.openRequests[token] + } + } + }; + } + + OCTOPRINT_VIEWMODELS.push([ + AppAuthViewModel, + ["loginStateViewModel"], + ["#usersettings_plugin_appauth"] + ]); +}); diff --git a/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 b/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 new file mode 100644 index 000000000..aeb2f9e67 --- /dev/null +++ b/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 @@ -0,0 +1,42 @@ + + + + + + + + + + + + + +
{{ _('Application') }}{{ _('Action') }}

{{ _('API Key') }}:
+ + +
+ +
+
+ +
+ +
+
+ +
+
+ +
+
+
From 2a79d9183ab3afa685ede4dcac61269f1bc4955d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Aug 2018 22:02:18 +0200 Subject: [PATCH 03/10] New asset type "clientjs" for client library bits --- .../plugins/action_command_prompt/__init__.py | 3 +- .../static/clientjs/action_command_prompt.js | 25 ++++++ .../static/js/action_command_prompt.js | 26 ------ src/octoprint/plugins/backup/__init__.py | 1 + .../plugins/backup/static/clientjs/backup.js | 52 ++++++++++++ .../plugins/backup/static/js/backup.js | 53 ------------ src/octoprint/plugins/logging/__init__.py | 1 + .../logging/static/clientjs/logging.js | 68 +++++++++++++++ .../plugins/logging/static/js/logging.js | 69 --------------- src/octoprint/plugins/pi_support/__init__.py | 1 + .../pi_support/static/clientjs/pi_support.js | 19 +++++ .../pi_support/static/js/pi_support.js | 19 ----- .../plugins/pluginmanager/__init__.py | 1 + .../static/clientjs/pluginmanager.js | 82 ++++++++++++++++++ .../pluginmanager/static/js/pluginmanager.js | 83 ------------------ .../plugins/printer_safety_check/__init__.py | 1 + .../static/clientjs/printer_safety_check.js | 18 ++++ .../static/js/printer_safety_check.js | 19 ----- .../plugins/softwareupdate/__init__.py | 1 + .../static/clientjs/softwareupdate.js | 84 ++++++++++++++++++ .../static/js/softwareupdate.js | 85 ------------------- src/octoprint/server/__init__.py | 47 +++++----- src/octoprint/server/util/flask.py | 29 +++++++ 23 files changed, 410 insertions(+), 377 deletions(-) create mode 100644 src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js create mode 100644 src/octoprint/plugins/backup/static/clientjs/backup.js create mode 100644 src/octoprint/plugins/logging/static/clientjs/logging.js create mode 100644 src/octoprint/plugins/pi_support/static/clientjs/pi_support.js create mode 100644 src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js create mode 100644 src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js create mode 100644 src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 0dd9a4be2..8900c5d7a 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -49,7 +49,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ AssetPlugin def get_assets(self): - return dict(js=["js/action_command_prompt.js"]) + return dict(js=["js/action_command_prompt.js"], + clientjs=["clientjs/action_command_prompt.js"]) #~ SettingsPlugin diff --git a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js new file mode 100644 index 000000000..9ba9b4a14 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js @@ -0,0 +1,25 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintActionCommandPromptClient = function(base) { + this.base = base; + }; + + OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { + return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); + }; + + OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { + var data = { + choice: choice + }; + return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); + }; + + OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); + return OctoPrintActionCommandPromptClient; +}); diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js index 6298a5338..e077903a2 100644 --- a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js +++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js @@ -1,29 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintActionCommandPromptClient = function(base) { - this.base = base; - }; - - OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { - return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); - }; - - OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { - var data = { - choice: choice - }; - return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); - }; - - OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); - return OctoPrintActionCommandPromptClient; -}); - $(function() { function ActionCommandPromptViewModel(parameters) { var self = this; diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 47ceb0a31..e687b3b85 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -69,6 +69,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, def get_assets(self): return dict(js=["js/backup.js"], + clientjs=["clientjs/backup.js"], css=["css/backup.css"], less=["less/backup.less"]) diff --git a/src/octoprint/plugins/backup/static/clientjs/backup.js b/src/octoprint/plugins/backup/static/clientjs/backup.js new file mode 100644 index 000000000..5f2ee6e62 --- /dev/null +++ b/src/octoprint/plugins/backup/static/clientjs/backup.js @@ -0,0 +1,52 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintBackupClient = function(base) { + this.base = base; + this.url = this.base.getBlueprintUrl("backup"); + }; + + OctoPrintBackupClient.prototype.get = function(refresh, opts) { + return this.base.get(this.url, opts); + }; + + OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) { + exclude = exclude || []; + + var data = { + exclude: exclude + }; + + return this.base.postJson(this.url + "backup", data, opts); + }; + + OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) { + return this.base.delete(this.url + "backup/" + backup, opts); + }; + + OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) { + var data = { + path: backup + }; + + return this.base.postJson(this.url + "restore", data, opts); + }; + + OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) { + data = data || {}; + + var filename = data.filename || undefined; + return this.base.upload(this.url + "restore", file, filename, data); + }; + + OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) { + return this.base.delete(this.url + "unknown_plugins", opts); + }; + + OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient); + return OctoPrintBackupClient; +}); diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 61eedb240..dadd24c8c 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -1,56 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintBackupClient = function(base) { - this.base = base; - this.url = this.base.getBlueprintUrl("backup"); - }; - - OctoPrintBackupClient.prototype.get = function(refresh, opts) { - return this.base.get(this.url, opts); - }; - - OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) { - exclude = exclude || []; - - var data = { - exclude: exclude - }; - - return this.base.postJson(this.url + "backup", data, opts); - }; - - OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) { - return this.base.delete(this.url + "backup/" + backup, opts); - }; - - OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) { - var data = { - path: backup - }; - - return this.base.postJson(this.url + "restore", data, opts); - }; - - OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) { - data = data || {}; - - var filename = data.filename || undefined; - return this.base.upload(this.url + "restore", file, filename, data); - }; - - OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) { - return this.base.delete(this.url + "unknown_plugins", opts); - }; - - OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient); - return OctoPrintBackupClient; -}); - $(function() { function BackupViewModel(parameters) { var self = this; diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index ed11c1c28..9b7c9bd74 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -195,6 +195,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=["js/logging.js"], + clientjs=["clientjs/logging.js"], less=["less/logging.less"], css=["css/logging.css"]) diff --git a/src/octoprint/plugins/logging/static/clientjs/logging.js b/src/octoprint/plugins/logging/static/clientjs/logging.js new file mode 100644 index 000000000..23b90f85d --- /dev/null +++ b/src/octoprint/plugins/logging/static/clientjs/logging.js @@ -0,0 +1,68 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + + var OctoPrintLoggingClient = function(base) { + this.base = base; + + this.baseUrl = this.base.getBlueprintUrl("logging"); + this.logsUrl = this.baseUrl + "logs"; + this.setupUrl = this.baseUrl + "setup"; + }; + + OctoPrintLoggingClient.prototype.get = function(opts) { + return this.base.get(this.baseUrl, opts); + }; + + OctoPrintLoggingClient.prototype.listLogs = function(opts) { + return this.base.get(this.logsUrl, opts); + }; + + OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) { + var fileUrl = this.logsUrl + "/" + file; + return this.base.delete(fileUrl, opts); + }; + + OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) { + var fileUrl = this.logsUrl + "/" + file; + return this.base.download(fileUrl, opts); + }; + + OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) { + return this.base.putJson(this.setupUrl + "/levels", config, opts); + }; + + //~~ wrapper for backwards compatibility + + var DeprecatedOctoPrintLogsClient = function(base) { + this.base = base; + this.wrapped = this.base.plugins.logging; + }; + + DeprecatedOctoPrintLogsClient.prototype.list = function(opts) { + log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"); + return this.wrapped.listLogs(opts); + }; + + DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) { + log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"); + return this.wrapped.deleteLog(file, opts); + }; + + DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) { + log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"); + return this.wrapped.downloadLog(file, opts); + }; + + // register plugin component + OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient); + + // also register deprecated client under old endpoint + OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient); + + return OctoPrintLoggingClient; +}); diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index c4131debb..2f0f16988 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -1,72 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - - var OctoPrintLoggingClient = function(base) { - this.base = base; - - this.baseUrl = this.base.getBlueprintUrl("logging"); - this.logsUrl = this.baseUrl + "logs"; - this.setupUrl = this.baseUrl + "setup"; - }; - - OctoPrintLoggingClient.prototype.get = function(opts) { - return this.base.get(this.baseUrl, opts); - }; - - OctoPrintLoggingClient.prototype.listLogs = function(opts) { - return this.base.get(this.logsUrl, opts); - }; - - OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) { - var fileUrl = this.logsUrl + "/" + file; - return this.base.delete(fileUrl, opts); - }; - - OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) { - var fileUrl = this.logsUrl + "/" + file; - return this.base.download(fileUrl, opts); - }; - - OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) { - return this.base.putJson(this.setupUrl + "/levels", config, opts); - }; - - //~~ wrapper for backwards compatibility - - var DeprecatedOctoPrintLogsClient = function(base) { - this.base = base; - this.wrapped = this.base.plugins.logging; - }; - - DeprecatedOctoPrintLogsClient.prototype.list = function(opts) { - log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"); - return this.wrapped.listLogs(opts); - }; - - DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) { - log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"); - return this.wrapped.deleteLog(file, opts); - }; - - DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) { - log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"); - return this.wrapped.downloadLog(file, opts); - }; - - // register plugin component - OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient); - - // also register deprecated client under old endpoint - OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient); - - return OctoPrintLoggingClient; -}); - $(function() { function LoggingViewModel(parameters) { var self = this; diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index e0bd9ac10..28b4f3d03 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -193,6 +193,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, def get_assets(self): return dict( js=["js/pi_support.js"], + clientjs=["clientjs/pi_support.js"], css=["css/pi_support.css"] ) diff --git a/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js new file mode 100644 index 000000000..7c216aa0f --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js @@ -0,0 +1,19 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPiSupportClient = function(base) { + this.base = base; + }; + + OctoPrintPiSupportClient.prototype.get = function(opts) { + return this.base.get(this.base.getSimpleApiUrl("pi_support")); + }; + + OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); + return OctoPrintPiSupportClient; +}); + diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js index ced2a55e4..2516a4f77 100644 --- a/src/octoprint/plugins/pi_support/static/js/pi_support.js +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.js @@ -1,22 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPiSupportClient = function(base) { - this.base = base; - }; - - OctoPrintPiSupportClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("pi_support")); - }; - - OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); - return OctoPrintPiSupportClient; -}); - $(function() { function PiSupportViewModel(parameters) { diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index df4def7e6..c085c032e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -168,6 +168,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def get_assets(self): return dict( js=["js/pluginmanager.js"], + clientjs=["clientjs/pluginmanager.js"], css=["css/pluginmanager.css"], less=["less/pluginmanager.less"] ) diff --git a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js new file mode 100644 index 000000000..acaaf3590 --- /dev/null +++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js @@ -0,0 +1,82 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPluginManagerClient = function(base) { + this.base = base; + }; + + OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) { + var refresh_repo, refresh_notices; + if (_.isPlainObject(refresh)) { + refresh_repo = refresh.repo || false; + refresh_notices = refresh.notices || false; + } else { + refresh_repo = refresh; + refresh_notices = false; + } + + var query = []; + if (refresh_repo) query.push("refresh_repository=true"); + if (refresh_notices) query.push("refresh_notices=true"); + + return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts); + }; + + OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) { + return this.get(true, opts); + }; + + OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) { + return this.get(false, opts); + }; + + OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks + }; + return this.base.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks, + reinstall: plugin, + force: true + }; + return this.base.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "enable", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "disable", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.upload = function(file) { + return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file); + }; + + OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient); + return OctoPrintPluginManagerClient; +}); diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 5bf20baef..403aae500 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -1,86 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPluginManagerClient = function(base) { - this.base = base; - }; - - OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) { - var refresh_repo, refresh_notices; - if (_.isPlainObject(refresh)) { - refresh_repo = refresh.repo || false; - refresh_notices = refresh.notices || false; - } else { - refresh_repo = refresh; - refresh_notices = false; - } - - var query = []; - if (refresh_repo) query.push("refresh_repository=true"); - if (refresh_notices) query.push("refresh_notices=true"); - - return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts); - }; - - OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) { - return this.get(true, opts); - }; - - OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) { - return this.get(false, opts); - }; - - OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) { - var data = { - url: pluginUrl, - dependency_links: !!dependencyLinks - }; - return this.base.simpleApiCommand("pluginmanager", "install", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { - var data = { - url: pluginUrl, - dependency_links: !!dependencyLinks, - reinstall: plugin, - force: true - }; - return this.base.simpleApiCommand("pluginmanager", "install", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "enable", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "disable", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.upload = function(file) { - return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file); - }; - - OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient); - return OctoPrintPluginManagerClient; -}); - $(function() { function PluginManagerViewModel(parameters) { var self = this; diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 182f61a3e..677bef7fd 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -90,6 +90,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=("js/printer_safety_check.js",), + clientjs=("clientjs/printer_safety_check.js",), css=("css/printer_safety_check.css",), less=("less/printer_safety_check.less",)) diff --git a/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js new file mode 100644 index 000000000..5a52fc4f9 --- /dev/null +++ b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js @@ -0,0 +1,18 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPrinterSafetyCheckClient = function(base) { + this.base = base; + }; + + OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) { + return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts); + }; + + OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient); + return OctoPrintPrinterSafetyCheckClient; +}); diff --git a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js index c69bf8eb6..34e75aa97 100644 --- a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js +++ b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js @@ -1,22 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPrinterSafetyCheckClient = function(base) { - this.base = base; - }; - - OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts); - }; - - OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient); - return OctoPrintPrinterSafetyCheckClient; -}); - $(function() { function PrinterSafetyCheckViewModel(parameters) { var self = this; diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 2166d293b..bd13f2a3d 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -560,6 +560,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return dict( css=["css/softwareupdate.css"], js=["js/softwareupdate.js"], + clientjs=["clientjs/softwareupdate.js"], less=["less/softwareupdate.less"] ) diff --git a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js new file mode 100644 index 000000000..932dcf8ce --- /dev/null +++ b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js @@ -0,0 +1,84 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintSoftwareUpdateClient = function(base) { + this.base = base; + + var url = this.base.getBlueprintUrl("softwareupdate"); + this.checkUrl = url + "check"; + this.updateUrl = url + "update"; + }; + + OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) { + if (arguments.length == 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + entries = params.entries; + force = params.force; + opts = params.opts; + } + + entries = entries || []; + if (typeof entries == "string") { + entries = [entries]; + } + + var data = {}; + if (!!force) { + data.force = true; + } + if (entries && entries.length) { + data.check = entries.join(","); + } + return this.base.getWithQuery(this.checkUrl, data, opts); + }; + + OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + force = params.force; + opts = params.opts; + } + + return this.checkEntries({entries: [], force: force, opts: opts}); + }; + + OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + targets = params.targets; + force = params.force; + opts = params.opts; + } + + targets = targets || []; + if (typeof targets === "string") { + targets = [targets]; + } + + var data = { + targets: targets, + force: !!force + }; + return this.base.postJson(this.updateUrl, data, opts); + }; + + OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + force = params.force; + opts = params.opts; + } + + var data = { + force: !!force + }; + return this.base.postJson(this.updateUrl, data, opts); + }; + + OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient); + return OctoPrintSoftwareUpdateClient; +}); diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index d0484a5b8..fbe341dae 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -1,88 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintSoftwareUpdateClient = function(base) { - this.base = base; - - var url = this.base.getBlueprintUrl("softwareupdate"); - this.checkUrl = url + "check"; - this.updateUrl = url + "update"; - }; - - OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) { - if (arguments.length == 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - entries = params.entries; - force = params.force; - opts = params.opts; - } - - entries = entries || []; - if (typeof entries == "string") { - entries = [entries]; - } - - var data = {}; - if (!!force) { - data.force = true; - } - if (entries && entries.length) { - data.check = entries.join(","); - } - return this.base.getWithQuery(this.checkUrl, data, opts); - }; - - OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - force = params.force; - opts = params.opts; - } - - return this.checkEntries({entries: [], force: force, opts: opts}); - }; - - OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - targets = params.targets; - force = params.force; - opts = params.opts; - } - - targets = targets || []; - if (typeof targets === "string") { - targets = [targets]; - } - - var data = { - targets: targets, - force: !!force - }; - return this.base.postJson(this.updateUrl, data, opts); - }; - - OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - force = params.force; - opts = params.opts; - } - - var data = { - force: !!force - }; - return this.base.postJson(this.updateUrl, data, opts); - }; - - OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient); - return OctoPrintSoftwareUpdateClient; -}); - $(function() { function SoftwareUpdateViewModel(parameters) { var self = this; diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 3c3ccb5b5..b8432b43d 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1288,25 +1288,6 @@ class Server(object): "js/lib/loglevel.min.js", "js/lib/sockjs.js" ] - js_client = [ - "js/app/client/base.js", - "js/app/client/socket.js", - "js/app/client/browser.js", - "js/app/client/connection.js", - "js/app/client/control.js", - "js/app/client/files.js", - "js/app/client/job.js", - "js/app/client/languages.js", - "js/app/client/printer.js", - "js/app/client/printerprofiles.js", - "js/app/client/settings.js", - "js/app/client/slicing.js", - "js/app/client/system.js", - "js/app/client/timelapse.js", - "js/app/client/users.js", - "js/app/client/util.js", - "js/app/client/wizard.js" - ] css_libs = [ "css/bootstrap.min.css", @@ -1359,13 +1340,15 @@ class Server(object): js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"], filters="js_delimiter_bundler") + clientjs_core = dynamic_core_assets["clientjs"] + \ + all_assets_for_plugins(dynamic_plugin_assets["bundled"]["clientjs"]) + clientjs_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["clientjs"], + filters="js_delimiter_bundler") + js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters)) - js_client_bundle = Bundle(*js_client, - output="webassets/packed_client.js", - filters=",".join(js_filters)) js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters)) @@ -1381,6 +1364,21 @@ class Server(object): output="webassets/packed_app.js", filters=",".join(js_filters)) + js_client_core_bundle = Bundle(*clientjs_core, + output="webassets/packed_client_core.js", + filters=",".join(js_filters)) + + if len(clientjs_plugins) == 0: + js_client_plugins_bundle = Bundle(*[]) + else: + js_client_plugins_bundle = Bundle(*clientjs_plugins.values(), + output="webassets/packed_client_plugins.js", + filters=",".join(js_plugin_filters)) + + js_client_bundle = Bundle(js_client_core_bundle, js_client_plugins_bundle, + output="webassets/packed_client.js", + filters=",".join(js_filters)) + # -- CSS ------------------------------------------------------------------------------------------------------- css_filters = ["cssrewrite"] @@ -1440,6 +1438,11 @@ class Server(object): # -- asset registration ---------------------------------------------------------------------------------------- assets.register("js_libs", js_libs_bundle) + assets.register("js_client_core", js_client_core_bundle) + for plugin, bundle in clientjs_plugins.items(): + # register our collected clientjs plugin bundles so that they are bound to the environment + assets.register("js_client_plugin_{}".format(plugin), bundle) + assets.register("js_client_plugins", js_client_plugins_bundle) assets.register("js_client", js_client_bundle) assets.register("js_core", js_core_bundle) for plugin, bundle in js_plugins.items(): diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 8cca9c541..28eaa589f 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1335,6 +1335,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater): def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): assets = dict( js=[], + clientjs=[], css=[], less=[] ) @@ -1376,6 +1377,26 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): 'gcodeviewer/js/renderer.js' ] + assets["clientjs"] = [ + "js/app/client/base.js", + "js/app/client/socket.js", + "js/app/client/browser.js", + "js/app/client/connection.js", + "js/app/client/control.js", + "js/app/client/files.js", + "js/app/client/job.js", + "js/app/client/languages.js", + "js/app/client/printer.js", + "js/app/client/printerprofiles.js", + "js/app/client/settings.js", + "js/app/client/slicing.js", + "js/app/client/system.js", + "js/app/client/timelapse.js", + "js/app/client/users.js", + "js/app/client/util.js", + "js/app/client/wizard.js" + ] + if preferred_stylesheet == "less": assets["less"].append('less/octoprint.less') elif preferred_stylesheet == "css": @@ -1390,9 +1411,11 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): supported_stylesheets = ("css", "less") assets = dict(bundled=dict(js=DefaultOrderedDict(list), + clientjs=DefaultOrderedDict(list), css=DefaultOrderedDict(list), less=DefaultOrderedDict(list)), external=dict(js=DefaultOrderedDict(list), + clientjs=DefaultOrderedDict(list), css=DefaultOrderedDict(list), less=DefaultOrderedDict(list))) @@ -1422,6 +1445,12 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): continue assets[asset_key]["js"][name].append('plugin/{name}/{asset}'.format(**locals())) + if "clientjs" in all_assets: + for asset in all_assets["clientjs"]: + if not asset_exists("clientjs", asset): + continue + assets[asset_key]["clientjs"][name].append("plugin/{name}/{asset}".format(**locals())) + if preferred_stylesheet in all_assets: for asset in all_assets[preferred_stylesheet]: if not asset_exists(preferred_stylesheet, asset): From 61d037f188e7ea70e3b6e36936a53c75c019d2bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Aug 2018 22:02:40 +0200 Subject: [PATCH 04/10] Clientlib: support operation without api key --- src/octoprint/static/js/app/client/base.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/client/base.js b/src/octoprint/static/js/app/client/base.js index 2eb51d4d9..f8e6b3ae0 100644 --- a/src/octoprint/static/js/app/client/base.js +++ b/src/octoprint/static/js/app/client/base.js @@ -111,7 +111,9 @@ additional = additional || {}; var headers = $.extend({}, additional); - headers["X-Api-Key"] = this.options.apikey; + if (this.options.apikey) { + headers["X-Api-Key"] = this.options.apikey; + } if (this.options.locale !== undefined) { headers["X-Locale"] = this.options.locale; From 2343caea30071e42b51b6843fd95f0001f662795 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Aug 2018 22:04:34 +0200 Subject: [PATCH 05/10] New options for confirmation dialog * oncancel: callback to call when cancel button is pressed * noclose: don't allow dismissing/closing the dialog without having chosen to proceed or cancel --- src/octoprint/static/js/app/helpers.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 1eb161d05..7df9e46af 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -708,11 +708,19 @@ function showConfirmationDialog(msg, onacknowledge, options) { var proceed = options.proceed || gettext("Proceed"); var proceedClass = options.proceedClass || "danger"; var onproceed = options.onproceed || undefined; + var oncancel = options.oncancel || undefined; var onclose = options.onclose || undefined; var dialogClass = options.dialogClass || ""; var nofade = options.nofade || false; + var noclose = options.noclose || false; + + var modalHeader; + if (noclose) { + modalHeader = $('

' + title + '

'); + } else { + modalHeader = $('

' + title + '

'); + } - var modalHeader = $('

' + title + '

'); var modalBody; if (html) { modalBody = $(html); @@ -740,7 +748,13 @@ function showConfirmationDialog(msg, onacknowledge, options) { onclose(event); } }); - modal.modal("show"); + + var modalOptions = {}; + if (noclose) { + modalOptions.backdrop = "static"; + modalOptions.keyboard = false; + } + modal.modal(modalOptions); proceedButton.click(function(e) { e.preventDefault(); @@ -749,6 +763,11 @@ function showConfirmationDialog(msg, onacknowledge, options) { } modal.modal("hide"); }); + cancelButton.click(function(e) { + if (oncancel && _.isFunction(oncancel)) { + oncancel(e); + } + }); return modal; } From b0028cd3fb64ed68c73e386b82566d7c39bf90c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Aug 2018 22:05:28 +0200 Subject: [PATCH 06/10] AppAuth: workflow fully implemented & client lib --- src/octoprint/plugins/appauth/__init__.py | 37 +++++---- .../appauth/static/clientjs/appauth.js | 83 +++++++++++++++++++ .../plugins/appauth/static/js/appauth.js | 41 ++------- 3 files changed, 109 insertions(+), 52 deletions(-) create mode 100644 src/octoprint/plugins/appauth/static/clientjs/appauth.js diff --git a/src/octoprint/plugins/appauth/__init__.py b/src/octoprint/plugins/appauth/__init__.py index 08d0bcf6b..398f2005f 100644 --- a/src/octoprint/plugins/appauth/__init__.py +++ b/src/octoprint/plugins/appauth/__init__.py @@ -31,15 +31,14 @@ class PendingDecision(object): class ReadyDecision(object): - def __init__(self, app_id, app_token, user_id, api_key): + def __init__(self, app_id, app_token, user_id): self.app_id = app_id self.app_token = app_token self.user_id = user_id - self.api_key = api_key @classmethod - def for_pending(cls, pending, api_key): - return cls(pending.app_id, pending.app_token, pending.user_id, api_key) + def for_pending(cls, pending, user_id): + return cls(pending.app_id, pending.app_token, user_id) class ActiveKey(object): @@ -70,7 +69,8 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, ##-- AssetPlugin hooks def get_assets(self): - return dict(js=["js/appauth.js"]) + return dict(js=["js/appauth.js"], + clientjs=["clientjs/appauth.js"]) ##~~ BlueprintPlugin mixin @@ -101,10 +101,12 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, @no_firstrun_access def handle_decision_poll(self, app_token): if self._is_pending(app_token): - return flask.make_response("Awaiting decision", 202) + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response result = self._get_decision(app_token) - if result is not None: + if result: return flask.jsonify(api_key=result) return flask.abort(404) @@ -159,11 +161,7 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, if not app_name: return flask.abort(400) - api_key = self._generate_key() - try: - self._add_api_key(user_id, app_name.trim(), api_key) - except AppAlreadyExists: - return flask.abort(409) + self._add_api_key(user_id, app_name.trim()) return NO_CONTENT @@ -210,7 +208,7 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, if decision: with self._ready_lock: - self._ready_decisions.append(ReadyDecision.for_pending(pending, self._generate_key())) + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) with self._pending_lock: self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions) @@ -226,20 +224,23 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, else: return False # not found - self._add_api_key(decision.user_id, decision.app_id, decision.api_key) + api_key = self._add_api_key(decision.user_id, decision.app_id) with self._ready_lock: self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions) - return decision.api_key + return api_key - def _add_api_key(self, user_id, app_name, api_key): + def _add_api_key(self, user_id, app_name): with self._keys_lock: # TODO: persist to disk for key in self._keys[user_id]: if key.app_id.lower() == app_name.lower(): - raise AppAlreadyExists("app {} does already exist".format(app_name)) - self._keys[user_id].append(ActiveKey(app_name, api_key)) + return key.api_key + + key = ActiveKey(app_name, self._generate_key()) + self._keys[user_id].append(key) + return key.api_key def _delete_api_key(self, user_id, api_key): with self._keys_lock: diff --git a/src/octoprint/plugins/appauth/static/clientjs/appauth.js b/src/octoprint/plugins/appauth/static/clientjs/appauth.js new file mode 100644 index 000000000..57800af43 --- /dev/null +++ b/src/octoprint/plugins/appauth/static/clientjs/appauth.js @@ -0,0 +1,83 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintAppAuthClient = function(base) { + this.base = base; + }; + + OctoPrintAppAuthClient.prototype.getKeys = function(opts) { + return this.base.simpleApiGet("appauth", opts); + }; + + OctoPrintAppAuthClient.prototype.generateKey = function(app, opts) { + return this.base.simpleApiCommand("appauth", "generate", {"app": app}, opts); + }; + + OctoPrintAppAuthClient.prototype.revokeKey = function(key, opts) { + return this.base.simpleApiCommand("appauth", "revoke", {"key": key}, opts); + }; + + OctoPrintAppAuthClient.prototype.decide = function(token, decision, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appauth") + "decision/" + token, {decision: !!decision}, opts); + }; + + OctoPrintAppAuthClient.prototype.request = function(app, opts) { + return this.requestForUser(app, undefined, opts); + }; + + OctoPrintAppAuthClient.prototype.requestForUser = function(app, user, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appauth") + "request", {app: app, user: user}, opts); + }; + + OctoPrintAppAuthClient.prototype.checkDecision = function(token, opts) { + return this.base.get(this.base.getBlueprintUrl("appauth") + "request/" + token, opts); + }; + + OctoPrintAppAuthClient.prototype.authenticate = function(app, user) { + var deferred = $.Deferred(); + var client = this; + + client.requestForUser(app, user) + .done(function(response) { + var token = response.app_token; + if (!token) { + // no token received, something went wrong + deferred.reject(); + return; + } + + var interval = 1000; + var poll = function() { + client.checkDecision(token) + .done(function(response) { + if (response.api_key) { + // got a decision, resolve the promise + deferred.resolve(response.api_key); + } else { + // no decision yet, poll a bit more + deferred.notify(); + window.setTimeout(poll, interval); + } + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + }; + window.setTimeout(poll, interval); + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + + return deferred.promise(); + }; + + OctoPrintClient.registerPluginComponent("appauth", OctoPrintAppAuthClient); + return OctoPrintAppAuthClient; +}); diff --git a/src/octoprint/plugins/appauth/static/js/appauth.js b/src/octoprint/plugins/appauth/static/js/appauth.js index 74ec1e6e1..1cc353935 100644 --- a/src/octoprint/plugins/appauth/static/js/appauth.js +++ b/src/octoprint/plugins/appauth/static/js/appauth.js @@ -1,34 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintAppAuthClient = function(base) { - this.base = base; - }; - - OctoPrintAppAuthClient.prototype.getKeys = function(opts) { - return this.base.simpleApiGet("appauth", opts); - }; - - OctoPrintAppAuthClient.prototype.generateKey = function(app, opts) { - return this.base.simpleApiCommand("appauth", "generate", {"app": app}, opts); - }; - - OctoPrintAppAuthClient.prototype.revokeKey = function(key, opts) { - return this.base.simpleApiCommand("appauth", "revoke", {"key": key}, opts); - }; - - OctoPrintAppAuthClient.prototype.decide = function(token, decision, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appauth") + "decision/" + token, {decision: !!decision}, opts); - }; - - OctoPrintClient.registerPluginComponent("appauth", OctoPrintAppAuthClient); - return OctoPrintAppAuthClient; -}); - $(function() { function AppAuthViewModel(parameters) { var self = this; @@ -90,23 +59,27 @@ $(function() { }; self.promptForAccess = function(app, token) { - var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API. Do you want to allow access to this application with your user account?"); + var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API."); message = _.sprintf(message, {app: app}); - + message = "

" + message + "

" + gettext("Do you want to allow access to this application with your user account?") + "

"; return new PNotify({ title: gettext("Access Request"), text: message, + hide: false, + icon: "fa fa-key", confirm: { confirm: true, buttons: [{ text: gettext("Allow"), click: function(notice) { self.allowApp(token); + notice.remove(); } }, { text: gettext("Deny"), click: function(notice) { self.denyApp(token); + notice.remove(); } }] }, @@ -141,7 +114,7 @@ $(function() { return; } - if (self.pending[token] === undefined) { + if (self.pending[token] !== undefined) { return; } From 2f1d71a98ccb77211be549194562426bd6156c26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Aug 2018 20:22:40 +0200 Subject: [PATCH 07/10] appauth -> appkeys --- .../templates/appauth_usersettings.jinja2 | 42 ---------------- .../plugins/{appauth => appkeys}/__init__.py | 22 ++++++--- .../static/clientjs/appkeys.js} | 34 ++++++------- .../plugins/appkeys/static/css/appkeys.css | 1 + .../static/js/appkeys.js} | 20 ++++---- .../plugins/appkeys/static/less/appkeys.less | 12 +++++ .../templates/appkeys_usersettings.jinja2 | 49 +++++++++++++++++++ 7 files changed, 104 insertions(+), 76 deletions(-) delete mode 100644 src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 rename src/octoprint/plugins/{appauth => appkeys}/__init__.py (92%) rename src/octoprint/plugins/{appauth/static/clientjs/appauth.js => appkeys/static/clientjs/appkeys.js} (66%) create mode 100644 src/octoprint/plugins/appkeys/static/css/appkeys.css rename src/octoprint/plugins/{appauth/static/js/appauth.js => appkeys/static/js/appkeys.js} (89%) create mode 100644 src/octoprint/plugins/appkeys/static/less/appkeys.less create mode 100644 src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 diff --git a/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 b/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 deleted file mode 100644 index aeb2f9e67..000000000 --- a/src/octoprint/plugins/appauth/templates/appauth_usersettings.jinja2 +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - -
{{ _('Application') }}{{ _('Action') }}

{{ _('API Key') }}:
- - -
- -
-
- -
- -
-
- -
-
- -
-
-
diff --git a/src/octoprint/plugins/appauth/__init__.py b/src/octoprint/plugins/appkeys/__init__.py similarity index 92% rename from src/octoprint/plugins/appauth/__init__.py rename to src/octoprint/plugins/appkeys/__init__.py index 398f2005f..27c261b69 100644 --- a/src/octoprint/plugins/appauth/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -6,6 +6,7 @@ import threading import os from binascii import hexlify from collections import defaultdict +from flask_babel import gettext import octoprint.plugin from octoprint.settings import valid_boolean_trues @@ -51,7 +52,7 @@ class ActiveKey(object): api_key=self.api_key) -class AppAuthPlugin(octoprint.plugin.AssetPlugin, +class AppKeysPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin): @@ -66,11 +67,18 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, self._keys = defaultdict(list) self._keys_lock = threading.RLock() - ##-- AssetPlugin hooks + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="usersettings", name=gettext("Application Keys"), custom_bindings=False)] + + ##~~ AssetPlugin def get_assets(self): - return dict(js=["js/appauth.js"], - clientjs=["clientjs/appauth.js"]) + return dict(js=["js/appkeys.js"], + clientjs=["clientjs/appkeys.js"], + less=["less/appkeys.less"], + css=["css/appkeys.css"]) ##~~ BlueprintPlugin mixin @@ -161,7 +169,7 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, if not app_name: return flask.abort(400) - self._add_api_key(user_id, app_name.trim()) + self._add_api_key(user_id, app_name.strip()) return NO_CONTENT @@ -261,10 +269,10 @@ class AppAuthPlugin(octoprint.plugin.AssetPlugin, def _generate_key(self): return hexlify(os.urandom(16)) -__plugin_name__ = "AppAuth Plugin" +__plugin_name__ = "Application Keys Plugin" __plugin_description__ = "TODO" __plugin_author__ = "Gina Häußge, Aldo Hoeben" -__plugin_implementation__ = AppAuthPlugin() +__plugin_implementation__ = AppKeysPlugin() __plugin_hooks__ = { "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key } diff --git a/src/octoprint/plugins/appauth/static/clientjs/appauth.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js similarity index 66% rename from src/octoprint/plugins/appauth/static/clientjs/appauth.js rename to src/octoprint/plugins/appkeys/static/clientjs/appkeys.js index 57800af43..1e70f4b89 100644 --- a/src/octoprint/plugins/appauth/static/clientjs/appauth.js +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -5,39 +5,39 @@ factory(global.OctoPrintClient); } })(this, function(OctoPrintClient) { - var OctoPrintAppAuthClient = function(base) { + var OctoPrintAppKeysClient = function(base) { this.base = base; }; - OctoPrintAppAuthClient.prototype.getKeys = function(opts) { - return this.base.simpleApiGet("appauth", opts); + OctoPrintAppKeysClient.prototype.getKeys = function(opts) { + return this.base.simpleApiGet("appkeys", opts); }; - OctoPrintAppAuthClient.prototype.generateKey = function(app, opts) { - return this.base.simpleApiCommand("appauth", "generate", {"app": app}, opts); + OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { + return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); }; - OctoPrintAppAuthClient.prototype.revokeKey = function(key, opts) { - return this.base.simpleApiCommand("appauth", "revoke", {"key": key}, opts); + OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) { + return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); }; - OctoPrintAppAuthClient.prototype.decide = function(token, decision, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appauth") + "decision/" + token, {decision: !!decision}, opts); + OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts); }; - OctoPrintAppAuthClient.prototype.request = function(app, opts) { + OctoPrintAppKeysClient.prototype.request = function(app, opts) { return this.requestForUser(app, undefined, opts); }; - OctoPrintAppAuthClient.prototype.requestForUser = function(app, user, opts) { - return this.base.postJson(this.base.getBlueprintUrl("appauth") + "request", {app: app, user: user}, opts); + OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts); }; - OctoPrintAppAuthClient.prototype.checkDecision = function(token, opts) { - return this.base.get(this.base.getBlueprintUrl("appauth") + "request/" + token, opts); + OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) { + return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts); }; - OctoPrintAppAuthClient.prototype.authenticate = function(app, user) { + OctoPrintAppKeysClient.prototype.authenticate = function(app, user) { var deferred = $.Deferred(); var client = this; @@ -78,6 +78,6 @@ return deferred.promise(); }; - OctoPrintClient.registerPluginComponent("appauth", OctoPrintAppAuthClient); - return OctoPrintAppAuthClient; + OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient); + return OctoPrintAppKeysClient; }); diff --git a/src/octoprint/plugins/appkeys/static/css/appkeys.css b/src/octoprint/plugins/appkeys/static/css/appkeys.css new file mode 100644 index 000000000..20673bafa --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/css/appkeys.css @@ -0,0 +1 @@ +#settings_plugin_appauth_keys_table .settings_plugin_appauth_keys_actions{width:75px;text-align:center}#settings_plugin_appauth_keys_table .settings_plugin_appauth_keys_actions a{color:#000} \ No newline at end of file diff --git a/src/octoprint/plugins/appauth/static/js/appauth.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js similarity index 89% rename from src/octoprint/plugins/appauth/static/js/appauth.js rename to src/octoprint/plugins/appkeys/static/js/appkeys.js index 1cc353935..015493f8f 100644 --- a/src/octoprint/plugins/appauth/static/js/appauth.js +++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js @@ -1,10 +1,10 @@ $(function() { - function AppAuthViewModel(parameters) { + function AppKeysViewModel(parameters) { var self = this; self.loginState = parameters[0]; self.keys = new ItemListHelper( - "plugin.appauth.keys", + "plugin.appkeys.keys", { "app": function (a, b) { // sorts descending @@ -26,7 +26,7 @@ $(function() { self.editorApp = ko.observable(); self.requestData = function() { - OctoPrint.plugins.appauth.getKeys() + OctoPrint.plugins.appkeys.getKeys() .done(self.fromResponse); }; @@ -39,22 +39,22 @@ $(function() { }; self.generateKey = function() { - return OctoPrint.plugins.appauth.generateKey(self.editorApp()) + return OctoPrint.plugins.appkeys.generateKey(self.editorApp()) .done(self.requestData); }; self.revokeKey = function(key) { - return OctoPrint.plugins.appauth.revokeKey(key) + return OctoPrint.plugins.appkeys.revokeKey(key) .done(self.requestData); }; self.allowApp = function(token) { - return OctoPrint.plugins.appauth.decide(token, true) + return OctoPrint.plugins.appkeys.decide(token, true) .done(self.requestData); }; self.denyApp = function(token) { - return OctoPrint.plugins.appauth.decide(token, false) + return OctoPrint.plugins.appkeys.decide(token, false) .done(self.requestData); }; @@ -99,7 +99,7 @@ $(function() { }; self.onDataUpdaterPluginMessage = function(plugin, data) { - if (plugin !== "appauth") { + if (plugin !== "appkeys") { return; } @@ -135,8 +135,8 @@ $(function() { } OCTOPRINT_VIEWMODELS.push([ - AppAuthViewModel, + AppKeysViewModel, ["loginStateViewModel"], - ["#usersettings_plugin_appauth"] + ["#usersettings_plugin_appkeys"] ]); }); diff --git a/src/octoprint/plugins/appkeys/static/less/appkeys.less b/src/octoprint/plugins/appkeys/static/less/appkeys.less new file mode 100644 index 000000000..1b871993f --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/less/appkeys.less @@ -0,0 +1,12 @@ +#settings_plugin_appauth_keys_table { + .settings_plugin_appauth_keys_app { + } + .settings_plugin_appauth_keys_actions { + width: 75px; + text-align: center; + + a { + color: black; + } + } +} diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 new file mode 100644 index 000000000..0eae9334d --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 @@ -0,0 +1,49 @@ +{{ _('Registered application keys') }} + +
+

{{ _('There are no application keys registered yet.') }}

+
+
+ + + + + + + + + + + + + +
{{ _('Application identifier') }}{{ _('Action') }}

{{ _('API Key') }}:
+ +
+ +{{ _('Manually generate an application key') }} + +
+
+ +
+ +
+
+ +
+
+ +
+
+
From 224674f27e26d41b087bc7824dff221a3c976674 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Aug 2018 20:35:16 +0200 Subject: [PATCH 08/10] Appkeys: fix template config --- src/octoprint/plugins/appkeys/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 27c261b69..91b0ca960 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -70,7 +70,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, ##~~ TemplatePlugin def get_template_configs(self): - return [dict(type="usersettings", name=gettext("Application Keys"), custom_bindings=False)] + return [dict(type="usersettings", name=gettext("Application Keys"))] ##~~ AssetPlugin From 2ca63febee440cb3294f3f4c57c8f308ee595504 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Aug 2018 20:45:16 +0200 Subject: [PATCH 09/10] Appkeys: allow fetching of all keys Also added TODO list ;) --- src/octoprint/plugins/appkeys/__init__.py | 35 ++++++++++++++++--- .../appkeys/static/clientjs/appkeys.js | 4 +++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 91b0ca960..2666047b9 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -11,7 +11,18 @@ from flask_babel import gettext import octoprint.plugin from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import restricted_access, no_firstrun_access -from octoprint.server import NO_CONTENT, current_user, user_permission +from octoprint.server import NO_CONTENT, current_user, admin_permission + + +""" +TODO: + * add key persistence + * add central management settings panel for *all* user's keys + * bulk delete: delete all, all on page, all by user? + * write documentation + * API docs + * JS client docs +""" class AppAlreadyExists(Exception): @@ -43,13 +54,15 @@ class ReadyDecision(object): class ActiveKey(object): - def __init__(self, app_id, api_key): + def __init__(self, app_id, api_key, user_id): self.app_id = app_id self.api_key = api_key + self.user_id = user_id def external(self): return dict(app_id=self.app_id, - api_key=self.api_key) + api_key=self.api_key, + user_id=self.user_id) class AppKeysPlugin(octoprint.plugin.AssetPlugin, @@ -148,7 +161,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, if not user_id: return flask.abort(403) - return flask.jsonify(keys=map(lambda x: x.external(), self._api_keys_for_user(user_id)), + if request.values.get("all") in valid_boolean_trues and admin_permission.can(): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify(keys=map(lambda x: x.external(), keys), pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id))) def on_api_command(self, command, data): @@ -246,7 +264,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, if key.app_id.lower() == app_name.lower(): return key.api_key - key = ActiveKey(app_name, self._generate_key()) + key = ActiveKey(app_name, self._generate_key(), user_id) self._keys[user_id].append(key) return key.api_key @@ -266,6 +284,13 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, with self._keys_lock: return self._keys.get(user_id, []) + def _all_api_keys(self): + with self._keys_lock: + result = [] + for user_id, keys in self._keys.items(): + result += keys + return result + def _generate_key(self): return hexlify(os.urandom(16)) diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js index 1e70f4b89..580ad1364 100644 --- a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -13,6 +13,10 @@ return this.base.simpleApiGet("appkeys", opts); }; + OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) { + return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts); + }; + OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); }; From 4a36a3eed2b94e25da967630ce9b4e90eb495714 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 3 Sep 2018 18:38:36 +0200 Subject: [PATCH 10/10] Appkeys: Add key persistence --- src/octoprint/plugins/appkeys/__init__.py | 54 ++++++++++++++++++++++- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 2666047b9..5f491db96 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -4,6 +4,9 @@ from __future__ import absolute_import import flask import threading import os +import yaml +import codecs +import time from binascii import hexlify from collections import defaultdict from flask_babel import gettext @@ -12,6 +15,7 @@ import octoprint.plugin from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import restricted_access, no_firstrun_access from octoprint.server import NO_CONTENT, current_user, admin_permission +from octoprint.util import atomic_write """ @@ -64,6 +68,14 @@ class ActiveKey(object): api_key=self.api_key, user_id=self.user_id) + def internal(self): + return dict(app_id=self.app_id, + api_key=self.api_key) + + @classmethod + def for_internal(cls, internal, user_id): + return cls(internal["app_id"], internal["api_key"], user_id) + class AppKeysPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, @@ -80,6 +92,12 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, self._keys = defaultdict(list) self._keys_lock = threading.RLock() + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + ##~~ TemplatePlugin def get_template_configs(self): @@ -259,19 +277,19 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, def _add_api_key(self, user_id, app_name): with self._keys_lock: - # TODO: persist to disk for key in self._keys[user_id]: if key.app_id.lower() == app_name.lower(): return key.api_key key = ActiveKey(app_name, self._generate_key(), user_id) self._keys[user_id].append(key) + self._save_keys() return key.api_key def _delete_api_key(self, user_id, api_key): with self._keys_lock: - # TODO: persist to disk self._keys[user_id] = filter(lambda x: x.api_key != api_key, self._keys[user_id]) + self._save_keys() def _user_for_api_key(self, api_key): with self._keys_lock: @@ -294,6 +312,38 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, def _generate_key(self): return hexlify(os.urandom(16)) + def _load_keys(self): + with self._keys_lock: + if not os.path.exists(self._key_path): + return + + try: + with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f: + persisted = yaml.safe_load(f) + except: + self._logger.exception("Could not load application keys from {}".format(self._key_path)) + return + + if not isinstance(persisted, dict): + return + + keys = dict() + for user_id, persisted_keys in persisted.items(): + keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] + self._keys = keys + + def _save_keys(self): + with self._keys_lock: + to_persist = dict() + for user_id, keys in self._keys.items(): + to_persist[user_id] = [x.internal() for x in keys] + + try: + with atomic_write(self._key_path) as f: + yaml.safe_dump(to_persist, f) + except: + self._logger.exception("Could not write application keys to {}".format(self._key_path)) + __plugin_name__ = "Application Keys Plugin" __plugin_description__ = "TODO" __plugin_author__ = "Gina Häußge, Aldo Hoeben"