Merge devel into py23
This commit is contained in:
commit
819d690bc3
20 files changed
+178
-479
No files matched your search
@@ -1327,6 +1327,14 @@ octoprint.server.http.routes
|
||||
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
|
||||
to your defined handler class.
|
||||
|
||||
.. important::
|
||||
|
||||
If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
|
||||
needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of
|
||||
:class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`,
|
||||
:class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler`
|
||||
already implement this mixin.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
@@ -793,6 +793,39 @@ class FilebasedUserManager(UserManager):
|
||||
deleteApiKey = deprecated("deleteApiKey has been renamed to delete_api_key",
|
||||
includedoc="Replaced by :func:`delete_api_key`",
|
||||
since="1.4.0")(delete_api_key)
|
||||
addUser = deprecated("addUser has been renamed to add_user",
|
||||
includedoc="Replaced by :func:`add_user`",
|
||||
since="1.4.0")(add_user)
|
||||
changeUserActivation = deprecated("changeUserActivation has been renamed to change_user_activation",
|
||||
includedoc="Replaced by :func:`change_user_activation`",
|
||||
since="1.4.0")(change_user_activation)
|
||||
changeUserPassword = deprecated("changeUserPassword has been renamed to change_user_password",
|
||||
includedoc="Replaced by :func:`change_user_password`",
|
||||
since="1.4.0")(change_user_password)
|
||||
getUserSetting = deprecated("getUserSetting has been renamed to get_user_setting",
|
||||
includedoc="Replaced by :func:`get_user_setting`",
|
||||
since="1.4.0")(get_user_setting)
|
||||
getAllUserSettings = deprecated("getAllUserSettings has been renamed to get_all_user_settings",
|
||||
includedoc="Replaced by :func:`get_all_user_settings`",
|
||||
since="1.4.0")(get_all_user_settings)
|
||||
changeUserSetting = deprecated("changeUserSetting has been renamed to change_user_setting",
|
||||
includedoc="Replaced by :func:`change_user_setting`",
|
||||
since="1.4.0")(change_user_setting)
|
||||
changeUserSettings = deprecated("changeUserSettings has been renamed to change_user_settings",
|
||||
includedoc="Replaced by :func:`change_user_settings`",
|
||||
since="1.4.0")(change_user_settings)
|
||||
removeUser = deprecated("removeUser has been renamed to remove_user",
|
||||
includedoc="Replaced by :func:`remove_user`",
|
||||
since="1.4.0")(remove_user)
|
||||
findUser = deprecated("findUser has been renamed to find_user",
|
||||
includedoc="Replaced by :func:`find_user`",
|
||||
since="1.4.0")(find_user)
|
||||
getAllUsers = deprecated("getAllUsers has been renamed to get_all_users",
|
||||
includedoc="Replaced by :func:`get_all_users`",
|
||||
since="1.4.0")(get_all_users)
|
||||
hasBeenCustomized = deprecated("hasBeenCustomized has been renamed to has_been_customized",
|
||||
includedoc="Replaced by :func:`has_been_customized`",
|
||||
since="1.4.0")(has_been_customized)
|
||||
|
||||
##~~ Exceptions
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ class AclSubwizard(object):
|
||||
return True
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
return self._user_manager.enabled and not self._user_manager.has_been_customized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict(required=self._is_acl_wizard_required())
|
||||
@@ -72,7 +72,7 @@ class AclSubwizard(object):
|
||||
from flask import request, abort
|
||||
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
|
||||
|
||||
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized():
|
||||
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized():
|
||||
abort(404)
|
||||
|
||||
data = request.get_json()
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
# -*- 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
|
||||
|
||||
import flask
|
||||
import flask_login
|
||||
from flask_babel import gettext
|
||||
|
||||
from collections import defaultdict
|
||||
import threading
|
||||
import json
|
||||
|
||||
class ForceLoginPlugin(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()
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/viewmodel.js"]
|
||||
)
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
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
|
||||
result = passive_login()
|
||||
if hasattr(result, "status_code") and result.status_code == 200:
|
||||
try:
|
||||
data = json.loads(result.data)
|
||||
if "name" in data:
|
||||
# successful? No need for handling the UI
|
||||
return False
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to decode passive login response")
|
||||
|
||||
return True
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
from flask import render_template, make_response
|
||||
|
||||
"""
|
||||
Support theming of the login dialog, just in case the core UI is themed as well.
|
||||
|
||||
Example usage by a plugin:
|
||||
|
||||
def forcelogin_theming():
|
||||
from flask import url_for
|
||||
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.forcelogin.theming": forcelogin_theming
|
||||
}
|
||||
|
||||
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
|
||||
url_for like in the example above to be prepared for any configured prefix URLs.
|
||||
"""
|
||||
additional_assets = []
|
||||
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
|
||||
try:
|
||||
assets = hook()
|
||||
if isinstance(assets, (tuple, list)):
|
||||
additional_assets += assets
|
||||
except Exception:
|
||||
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
|
||||
|
||||
render_kwargs.update(dict(forcelogin_theming=additional_assets))
|
||||
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
|
||||
|
||||
def get_ui_custom_tracked_files(self):
|
||||
from os.path import join as opj
|
||||
|
||||
paths = [opj("static", "css", "forcelogin.css"),
|
||||
opj("static", "js", "main.js"),
|
||||
opj("static", "js", "viewmodel.js"),
|
||||
opj("static", "less", "forcelogin.less"),
|
||||
opj("templates", "parts", "forcelogin_css.jinja2"),
|
||||
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
|
||||
opj("templates", "forcelogin_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
|
||||
|
||||
def get_before_request_handlers(self):
|
||||
def check_login_required():
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return
|
||||
|
||||
if flask.request.endpoint in ("api.login",):
|
||||
return
|
||||
|
||||
user = flask_login.current_user
|
||||
if user is None or user.is_anonymous or not user.is_active:
|
||||
return flask.make_response("Forbidden", 403)
|
||||
|
||||
return [check_login_required]
|
||||
|
||||
def access_validator(self, request):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return
|
||||
|
||||
import tornado.web
|
||||
from octoprint.server.util.flask import get_flask_user_from_request
|
||||
|
||||
user = get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
def socket_register_validator(self, socket, user):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return True
|
||||
|
||||
return user is not None and not user.is_anonymous and user.is_active
|
||||
|
||||
def socket_authed(self, socket, user):
|
||||
with self._message_backlog_mutex:
|
||||
backlog = self._message_backlog.pop(socket, [])
|
||||
|
||||
if len(backlog):
|
||||
for message, payload in backlog:
|
||||
socket._do_emit(message, payload)
|
||||
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
|
||||
|
||||
def socket_emit_validator(self, socket, user, message, payload):
|
||||
if self._user_manager.enabled and not self._user_manager.has_been_customized():
|
||||
# ACL hasn't been configured yet, make an exception
|
||||
return True
|
||||
elif not self._user_manager.enabled:
|
||||
# ACL isn't enabled
|
||||
return True
|
||||
|
||||
if message in ("connected", "reauthRequired"):
|
||||
return True
|
||||
|
||||
if user is not None and not user.is_anonymous and user.is_active:
|
||||
return True
|
||||
|
||||
with self._message_backlog_mutex:
|
||||
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
|
||||
self._message_backlog[socket].append((message, payload))
|
||||
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
|
||||
else:
|
||||
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
|
||||
|
||||
return False
|
||||
|
||||
|
||||
__plugin_name__ = "Force Login"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Forces users to login, disables read-only mode."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
|
||||
"OctoPrint instance. Only disable this if you are comfortable with this, your "
|
||||
"OctoPrint instance is not publicly reachable on the internet and you fully "
|
||||
"trust everyone who has access to your local network!")
|
||||
|
||||
__plugin_implementation__ = ForceLoginPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
|
||||
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
|
||||
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
|
||||
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
|
||||
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
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}
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* 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.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
|
||||
// update the API key directly in jquery's ajax options too,
|
||||
// to ensure the fileupload plugin and any plugins still using
|
||||
// $.ajax directly still work fine too
|
||||
UI_API_KEY = payload["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
/*
|
||||
* View model that takes care to redirect to / on logout in the regular
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
function ForceLoginViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>OctoPrint Login</title>
|
||||
|
||||
{% include "parts/forcelogin_css.jinja2" %}
|
||||
|
||||
{% include "parts/forcelogin_javascripts.jinja2" %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
|
||||
|
||||
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
|
||||
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
|
||||
|
||||
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username') }}">
|
||||
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password') }}">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="login-overlay">
|
||||
<div class="background"></div>
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<i class="fa fa-spinner fa-spin fa-4x"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,10 +0,0 @@
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
|
||||
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
|
||||
|
||||
{% for url in forcelogin_theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
@@ -1,15 +0,0 @@
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
</script>
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
|
||||
@@ -573,8 +573,11 @@ class Server(object):
|
||||
ioloop = IOLoop()
|
||||
ioloop.install()
|
||||
|
||||
enable_cors = settings().getBoolean(["api", "allowCrossOrigin"])
|
||||
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
|
||||
session_kls=util.sockjs.ThreadSafeSession)
|
||||
session_kls=util.sockjs.ThreadSafeSession,
|
||||
user_settings=dict(websocket_allow_origin="*" if enable_cors else ""))
|
||||
|
||||
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
|
||||
|
||||
@@ -629,6 +632,7 @@ class Server(object):
|
||||
return joined
|
||||
|
||||
util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug
|
||||
util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
|
||||
@@ -1238,7 +1238,7 @@ def no_firstrun_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()):
|
||||
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized()):
|
||||
return flask.make_response("OctoPrint isn't setup yet", 403)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -72,11 +72,50 @@ class RequestlessExceptionLoggingMixin(tornado.web.RequestHandler):
|
||||
exc_info=(typ, value, tb))
|
||||
|
||||
|
||||
#~~ CORS support
|
||||
|
||||
|
||||
class CorsSupportMixin(tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ mixin that
|
||||
makes sure to set CORS headers similarily to the Flask backed API endpoints.
|
||||
"""
|
||||
|
||||
ENABLE_CORS = False
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
if self.request.method != "OPTIONS" and origin and self.ENABLE_CORS:
|
||||
self.set_header("Access-Control-Allow-Origin", origin)
|
||||
|
||||
@tornado.web.asynchronous
|
||||
def options(self, *args, **kwargs):
|
||||
if self.ENABLE_CORS:
|
||||
origin = self.request.headers.get("Origin")
|
||||
method = self.request.headers.get("Access-Control-Request-Method")
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
self.set_header("Access-Control-Allow-Origin", origin)
|
||||
# Allow the actual method
|
||||
self.set_header("Access-Control-Allow-Methods", method)
|
||||
# Allow for 10 seconds
|
||||
self.set_header("Access-Control-Max-Age", "10")
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
custom_headers = self.request.headers.get("Access-Control-Request-Headers")
|
||||
if custom_headers is not None:
|
||||
self.set_header("Access-Control-Allow-Headers", custom_headers)
|
||||
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
|
||||
|
||||
#~~ WSGI middleware
|
||||
|
||||
|
||||
@tornado.web.stream_request_body
|
||||
class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin):
|
||||
class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin):
|
||||
"""
|
||||
A ``RequestHandler`` similar to ``tornado.web.FallbackHandler`` which fetches any files contained in the request bodies
|
||||
of content type ``multipart``, stores them in temporary files and supplies the ``fallback`` with the file's ``name``,
|
||||
@@ -882,7 +921,9 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
class LargeResponseHandler(RequestlessExceptionLoggingMixin, tornado.web.StaticFileHandler):
|
||||
class LargeResponseHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin,
|
||||
tornado.web.StaticFileHandler):
|
||||
"""
|
||||
Customized `tornado.web.StaticFileHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#tornado.web.StaticFileHandler>`_
|
||||
that allows delivery of the requested resource as attachment and access and request path validation through
|
||||
@@ -976,7 +1017,9 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin, tornado.web.StaticF
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlProxyHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandler):
|
||||
class UrlProxyHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin,
|
||||
tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||
@@ -1069,7 +1112,18 @@ class UrlProxyHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandl
|
||||
return "%s%s" % (self._basename, extension)
|
||||
|
||||
|
||||
class StaticDataHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandler):
|
||||
class StaticDataHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin,
|
||||
tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that returns
|
||||
static ``data`` of a configured ``content_type``.
|
||||
|
||||
Arguments:
|
||||
data (str): The data with which to respond
|
||||
content_type (str): The content type with which to respond. Defaults to ``text/plain``
|
||||
"""
|
||||
|
||||
def initialize(self, data="", content_type="text/plain"):
|
||||
self.data = data
|
||||
self.content_type = content_type
|
||||
@@ -1082,7 +1136,16 @@ class StaticDataHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHan
|
||||
self.finish()
|
||||
|
||||
|
||||
class DeprecatedEndpointHandler(tornado.web.RequestHandler):
|
||||
class DeprecatedEndpointHandler(CorsSupportMixin,
|
||||
tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that redirects
|
||||
to another ``url`` and logs a deprecation warning.
|
||||
|
||||
Arguments:
|
||||
url (str): URL to which to redirect
|
||||
"""
|
||||
|
||||
def initialize(self, url):
|
||||
self._url = url
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -357,7 +357,7 @@ def index():
|
||||
_plugin_vars,
|
||||
now)
|
||||
render_kwargs.update(dict(
|
||||
enableWebcam=settings().getBoolean(["webcam", "enableWebcam"]) and bool(settings().get(["webcam", "stream"])),
|
||||
enableWebcam=settings().getBoolean(["webcam", "webcamEnabled"]) and bool(settings().get(["webcam", "stream"])),
|
||||
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
|
||||
enableAccessControl=enable_accesscontrol,
|
||||
accessControlActive=accesscontrol_active,
|
||||
@@ -419,10 +419,19 @@ def index():
|
||||
|
||||
|
||||
def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
global _logger
|
||||
|
||||
#~~ a bunch of settings
|
||||
|
||||
first_run = settings().getBoolean(["server", "firstRun"])
|
||||
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
|
||||
|
||||
locales = dict()
|
||||
for l in LOCALES:
|
||||
try:
|
||||
locales[l.language] = dict(language=l.language, display=l.display_name, english=l.english_name)
|
||||
except:
|
||||
_logger.exception("Error while collecting available locales")
|
||||
|
||||
permissions = [permission.as_dict() for permission in Permissions.all()]
|
||||
extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions()))
|
||||
|
||||
|
||||
@@ -71,9 +71,6 @@ $(function() {
|
||||
callViewModels(self.allViewModels, "onUserPermissionsChanged");
|
||||
log.info("User needs for " + response.name + " changed");
|
||||
}
|
||||
if (response.session) {
|
||||
OctoPrint.socket.sendAuth(response.name, response.session);
|
||||
}
|
||||
|
||||
if (response.session) {
|
||||
OctoPrint.socket.sendAuth(response.name, response.session);
|
||||
|
||||
@@ -40,9 +40,9 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UiStateViewModel,
|
||||
["loginStateViewModel", "accessViewModel"],
|
||||
["#page-container-main", "#page-container-loading", "#page-container-needlogin"]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: UiStateViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#page-container-main", "#page-container-loading", "#page-container-needlogin"]
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> {{ _('Allow <a href="%(url)s">Cross Origin Resource Sharing (CORS)</a>', url = "https://en.wikipedia.org/wiki/Cross-origin_resource_sharing") }}
|
||||
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> {{ _('Allow <a href="%(url)s">Cross Origin Resource Sharing (CORS)</a>', url = "https://en.wikipedia.org/wiki/Cross-origin_resource_sharing") }} <label class="label label-info">{{ _('Needs restart') }}</label>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+41
-2
@@ -14,6 +14,15 @@ import logging
|
||||
|
||||
from tornado.web import asynchronous, RequestHandler
|
||||
|
||||
try:
|
||||
# python 3
|
||||
# noinspection PyCompatibility
|
||||
from urllib.parse import urlparse
|
||||
except ImportError:
|
||||
# python 2
|
||||
# noinspection PyCompatibility
|
||||
from urlparse import urlparse
|
||||
|
||||
CACHE_TIME = 31536000
|
||||
|
||||
LOG = logging.getLogger("tornado.general")
|
||||
@@ -128,5 +137,35 @@ class PreflightHandler(BaseHandler):
|
||||
|
||||
def verify_origin(self):
|
||||
"""Verify if request can be served"""
|
||||
# TODO: Verify origin
|
||||
return True
|
||||
|
||||
# adapted from sockjs.tornado.websocket.SockJSWebSocketHandler
|
||||
|
||||
origin = self.request.headers.get('Origin', '*')
|
||||
|
||||
# first check if connection from the same domain
|
||||
same_domain = self.check_origin(origin)
|
||||
if same_domain:
|
||||
return True
|
||||
|
||||
# this is cross-origin connection - check using SockJS server settings
|
||||
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
|
||||
if allow_origin == "":
|
||||
return False
|
||||
elif allow_origin == "*":
|
||||
return True
|
||||
else:
|
||||
parsed_origin = urlparse(origin)
|
||||
origin = parsed_origin.netloc
|
||||
origin = origin.lower()
|
||||
return origin in allow_origin
|
||||
|
||||
def check_origin(self, origin):
|
||||
# adapted from tornado.websocket.WebSocketHandler
|
||||
parsed_origin = urlparse(origin)
|
||||
origin = parsed_origin.netloc
|
||||
origin = origin.lower()
|
||||
|
||||
host = self.request.headers.get("Host")
|
||||
|
||||
# Check to see that origin matches host directly, including ports
|
||||
return origin == host
|
||||
+3
-1
@@ -26,7 +26,9 @@ class SockJSWebSocketHandler(websocket.WebSocketHandler):
|
||||
|
||||
# this is cross-origin connection - check using SockJS server settings
|
||||
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
|
||||
if allow_origin == "*":
|
||||
if allow_origin == "":
|
||||
return False
|
||||
elif allow_origin == "*":
|
||||
return True
|
||||
else:
|
||||
parsed_origin = urlparse(origin)
|
||||
|
||||
Reference in new issue
Block a user