Some permission changes & fixes

This commit is contained in:
Gina Häußge committed 2018-04-12 16:34:17 +02:00
1 parent 1852578136
commit 5a91b8db48
24 files changed
+362 -247

No files matched your search

+9 -9
View File
@@ -22,24 +22,24 @@ USER_GROUP = "Users"
DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
Permissions.CONNECTION,
Permissions.WEBCAM,
Permissions.UPLOAD,
Permissions.DOWNLOAD,
Permissions.DELETE,
Permissions.SELECT,
Permissions.FILES_UPLOAD,
Permissions.FILES_DOWNLOAD,
Permissions.FILES_DELETE,
Permissions.FILES_SELECT,
Permissions.PRINT,
Permissions.TERMINAL,
Permissions.MONITOR_TERMINAL,
Permissions.CONTROL,
Permissions.SLICE,
Permissions.TIMELAPSE,
Permissions.TIMELAPSE_LIST,
Permissions.TIMELAPSE_ADMIN]
"""Default user permissions are the legacy permissions from before 1.4.0"""
GUEST_GROUP = "Guests"
DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
Permissions.WEBCAM,
Permissions.DOWNLOAD,
Permissions.TIMELAPSE,
Permissions.TERMINAL]
Permissions.FILES_DOWNLOAD,
Permissions.TIMELAPSE_LIST,
Permissions.MONITOR_TERMINAL]
"""Default guest permissions are the legacy permissions from before 1.4.0"""
+79 -51
View File
@@ -11,7 +11,7 @@ from flask_babel import gettext
from flask_principal import Permission, PermissionDenied, RoleNeed, Need
from functools import wraps
from collections import OrderedDict
from collections import OrderedDict, defaultdict
from past.builtins import basestring
@@ -19,16 +19,24 @@ from past.builtins import basestring
class OctoPrintPermission(Permission):
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = dict()
ret_needs = defaultdict(list)
for need in needs:
if need.method not in ret_needs:
ret_needs[need.method] = []
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
@@ -36,7 +44,7 @@ class OctoPrintPermission(Permission):
self._key = None
Permission.__init__(self, *[RoleNeed(x) if not isinstance(x, Need) else x for x in needs])
Permission.__init__(self, *self.convert_to_needs(needs))
def as_dict(self):
return dict(
@@ -81,12 +89,10 @@ class OctoPrintPermission(Permission):
return p
def __repr__(self):
needs = []
for need in sorted(self.needs):
if need.method == 'role':
needs.append("RoleNeed('{0}')".format(need.value))
return '{}("{}", "{}", {})'.format(self.__class__.__name__, self.get_name(), self.get_description(), ', '.join(needs))
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
self.get_name(),
self.get_description(),
', '.join(map(repr, self.needs)))
def __hash__(self):
return self.get_name().__hash__()
@@ -285,75 +291,97 @@ class Permissions(object):
gettext("Allows to gather status information, e.g. job progress, "
"printer state, temperatures, ..."),
RoleNeed("status"))
CONNECTION = OctoPrintPermission("Connection",
gettext("Allows to connect to and disconnect and from a printer"),
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"))
WEBCAM = OctoPrintPermission("Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"))
SYSTEM = OctoPrintPermission("System",
gettext("Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"),
RoleNeed("system"))
UPLOAD = OctoPrintPermission("Upload",
RoleNeed("system"),
dangerous=True)
FILES_LIST = OctoPrintPermission("File List",
gettext("Allows to retrieve a list of all uploaded files, including"
"their metadata (e.g. date, file size, analysis results, ...)"),
RoleNeed("files_list"))
FILES_UPLOAD = OctoPrintPermission("File Upload",
gettext("Allows users to upload new files"),
RoleNeed("upload"))
DOWNLOAD = OctoPrintPermission("Download",
RoleNeed("files_upload"))
FILES_DOWNLOAD = OctoPrintPermission("File Download",
gettext("Allows users to download files. The GCODE viewer is "
"affected by this as well."),
RoleNeed("download"))
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
gettext("Allowed access to the GCODE viewer. Includes the \"Download\""
"permission."),
RoleNeed("gcodeviewer"), RoleNeed("download"))
DELETE = OctoPrintPermission("Delete",
RoleNeed("files_download"), FILES_LIST)
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files"),
RoleNeed("delete_file"))
SELECT = OctoPrintPermission("Select",
RoleNeed("files_delete"), FILES_LIST)
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("select"))
RoleNeed("files_select"), FILES_LIST)
PRINT = OctoPrintPermission("Print",
gettext("Allows to start a print job. Includes the \"Select\" "
gettext("Allows to start, pause and cancel a print job. Includes the \"Select\" "
"permission"),
RoleNeed("print"), RoleNeed("select"))
TERMINAL = OctoPrintPermission("Terminal",
RoleNeed("print"), FILES_SELECT)
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
gettext("Allows access to the GCODE viewer. Includes the \"File Download\""
"permission."),
RoleNeed("gcodeviewer"), FILES_DOWNLOAD)
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
gettext("Allows to watch the terminal tab but not to send commands "
"to the printer from it"),
RoleNeed("terminal"))
RoleNeed("monitor_terminal"))
CONTROL = OctoPrintPermission("Control",
gettext("Allows to control of the printer by using the control tab or "
"sending commands through the terminal. Includes the "
"\"Terminal\" permission"),
RoleNeed("control"), RoleNeed("terminal"))
gettext("Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."),
RoleNeed("control"))
SLICE = OctoPrintPermission("Slice",
gettext("Allows to slice files"),
RoleNeed("slice"))
TIMELAPSE = OctoPrintPermission("Timelapse",
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"))
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse"))
RoleNeed("timelapse_download"))
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
gettext("TODO"),
RoleNeed("timelapse_delete"))
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
gettext("Allows to change the timelapse settings, remove timelapses,"
"render unrendered timelapses. Includes the \"Timelapse\""
"permission"),
RoleNeed("timelapse_admin"), RoleNeed("timelapse"))
gettext("Allows to change the timelapse settings and"
"render unrendered timelapses. Includes the \"Timelapse List\","
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD)
SETTINGS = OctoPrintPermission("Settings",
gettext("Allows to manage settings"),
RoleNeed("settings"))
RoleNeed("settings"),
dangerous=True)
# TODO move to Logging plugin
LOGS = OctoPrintPermission("Logs",
gettext("Allows to download and remove logs"),
gettext("Allows to list, download and delete logs"),
RoleNeed("logs"))
CONTROL_ACCESS = CombinedOctoPrintPermission.from_permissions("Control Access",
CONTROL, WEBCAM)
CONNECTION_ACCESS = CombinedOctoPrintPermission.from_permissions("Connection Access",
CONNECTION, STATUS)
FILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Files Access",
UPLOAD, DOWNLOAD, DELETE, SELECT, PRINT,
CONTROL_ACCESS = CombinedOctoPrintPermission.from_permissions("Full Control Access",
CONTROL, MONITOR_TERMINAL, WEBCAM)
FILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Full Files Access",
FILES_UPLOAD, FILES_DOWNLOAD, FILES_DELETE, FILES_SELECT, PRINT,
SLICE)
PRINTERPROFILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Printerprofiles Access",
CONNECTION, SETTINGS)
TIMELAPSE_ACCESS = CombinedOctoPrintPermission.from_permissions("Timelapse Access",
TIMELAPSE, TIMELAPSE_ADMIN)
TIMELAPSE_ACCESS = CombinedOctoPrintPermission.from_permissions("Full Timelapse Access",
TIMELAPSE_LIST, TIMELAPSE_ADMIN)
class PermissionAlreadyExists(Exception):
-19
View File
@@ -1156,25 +1156,6 @@ class SessionUser(wrapt.ObjectProxy):
def __repr__(self):
return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created)
##~~ DummyUser object to use when accessControl is disabled
class DummyUser(User):
def __init__(self, groups):
User.__init__(self, "dummy", "", True, [], groups)
def check_password(self, passwordHash):
return True
class DummyIdentity(Identity):
def __init__(self):
Identity.__init__(self, "dummy")
def dummy_identity_loader():
return DummyIdentity()
##~~ Apiuser object to use when global api key is used to access the API
class ApiUser(User):
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import octoprint.plugin
from octoprint.events import Events
from octoprint.server import user_permission
from octoprint.access.permissions import Permissions
import flask
from flask_babel import gettext
@@ -65,10 +65,20 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
##~~ SimpleApiPlugin API
def on_api_get(self, request):
if not user_permission.can():
if not Permissions.PLUGIN_PRINTER_SAFETY_CHECK_DISPLAY.can():
return flask.make_response("Insufficient rights", 403)
return flask.jsonify(self._warnings)
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="DISPLAY",
name="Display printer safety warnings",
description=gettext("Allows to see printer safety warnings"),
roles=["display"])
]
##~~ Helpers
def _analyze_firmware_data(self, name, data):
@@ -107,4 +117,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n
"issue and inform you about that fact.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = PrinterSafetyCheckPlugin()
__plugin_hooks__ = {
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
+21 -7
View File
@@ -9,7 +9,7 @@ import uuid
from sockjs.tornado import SockJSRouter
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
from flask_login import LoginManager, current_user, session_protected, user_logged_out
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, Identity, AnonymousIdentity
from flask_babel import Babel, gettext, ngettext
from flask_assets import Environment, Bundle
from babel import Locale
@@ -555,8 +555,8 @@ class Server(object):
##~~ Permission validators
timelapse_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.TIMELAPSE))
download_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.DOWNLOAD))
timelapse_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST))
download_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.FILES_DOWNLOAD))
log_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.LOGS))
camera_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.WEBCAM))
@@ -1516,11 +1516,25 @@ class Server(object):
def anonymous_user_factory():
return users.AnonymousUser([groupManager.guest_group])
loginManager.anonymous_user = anonymous_user_factory # TODO: remove in 1.5.0
else:
def dummy_user_factory():
return users.DummyUser([groupManager.admin_group])
loginManager.anonymous_user = dummy_user_factory
principals.identity_loaders.appendleft(users.dummy_identity_loader)
class AdminUser(users.User):
def __init__(self):
users.User.__init__(self, "admin", "", True, [], [groupManager.admin_group])
def check_password(self, passwordHash):
return True
class AdminIdentity(Identity):
def __init__(self):
Identity.__init__(self, "admin")
def admin_identity_loader():
return AdminIdentity()
loginManager.anonymous_user = AdminUser
principals.identity_loaders.appendleft(admin_identity_loader)
loginManager.init_app(app, add_context_processor=False)
def _start_intermediary_server(self):
+2
View File
@@ -62,6 +62,8 @@ def add_group():
@api.route("/access/groups/<groupname>", methods=["GET"])
@restricted_access
@Permissions.SETTINGS.require(403)
def get_group(groupname):
group = groupManager.find_group(groupname)
if group is not None:
+8 -8
View File
@@ -89,7 +89,7 @@ def _create_etag(path, filter, recursive, lm=None):
@api.route("/files", methods=["GET"])
@Permissions.FILES_ACCESS.require(403)
@Permissions.FILES_LIST.require(403)
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
request.values.get("filter", False),
request.values.get("recursive", False),
@@ -110,7 +110,7 @@ def readGcodeFiles():
@api.route("/files/<string:origin>", methods=["GET"])
@Permissions.FILES_ACCESS.require(403)
@Permissions.FILES_LIST.require(403)
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
request.values.get("filter", False),
request.values.get("recursive", False),
@@ -260,7 +260,7 @@ def _isBusy(target, path):
@api.route("/files/<string:target>", methods=["POST"])
@restricted_access
@Permissions.UPLOAD.require(403)
@Permissions.FILES_UPLOAD.require(403)
def uploadGcodeFile(target):
input_name = "file"
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
@@ -284,7 +284,7 @@ def uploadGcodeFile(target):
return make_response("SD card support is disabled", 404)
sd = target == FileDestinations.SDCARD
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues and Permissions.SELECT.can()
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues and Permissions.FILES_SELECT.can()
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues and Permissions.PRINT.can()
if sd:
@@ -456,7 +456,7 @@ def uploadGcodeFile(target):
@api.route("/files/<string:target>/<path:filename>", methods=["GET"])
@Permissions.DOWNLOAD.require(403)
@Permissions.FILES_DOWNLOAD.require(403)
def readGcodeFile(target, filename):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
@@ -493,7 +493,7 @@ def gcodeFileCommand(filename, target):
return response
if command == "select":
with Permissions.SELECT.require(403):
with Permissions.FILES_SELECT.require(403):
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
@@ -661,7 +661,7 @@ def gcodeFileCommand(filename, target):
return make_response("No analysis possible for {} on {}".format(filename, target), 400)
elif command == "copy" or command == "move":
with Permissions.UPLOAD.require(403):
with Permissions.FILES_UPLOAD.require(403):
# Copy and move are only possible on local storage
if not target in [FileDestinations.LOCAL]:
return make_response("Unsupported target for {}: {}".format(command, target), 400)
@@ -738,7 +738,7 @@ def gcodeFileCommand(filename, target):
@api.route("/files/<string:target>/<path:filename>", methods=["DELETE"])
@Permissions.DELETE.require(403)
@Permissions.FILES_DELETE.require(403)
@restricted_access
def deleteGcodeFile(filename, target):
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
+2
View File
@@ -323,6 +323,7 @@ def printerSdCommand():
@api.route("/printer/sd", methods=["GET"])
@restricted_access
@Permissions.STATUS.require(403)
def printerSdState():
if not settings().getBoolean(["feature", "sdSupport"]):
@@ -396,6 +397,7 @@ def printerCommand():
return NO_CONTENT
@api.route("/printer/command/custom", methods=["GET"])
@restricted_access
@Permissions.CONTROL.require(403)
def getCustomControls():
# TODO: document me
+3 -1
View File
@@ -40,7 +40,8 @@ def _etag(lm=None):
@with_revalidation_checking(etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@Permissions.PRINTERPROFILES_ACCESS.require(403)
@restricted_access
@Permissions.CONNECTION.require(403)
def printerProfilesList():
all_profiles = printerProfileManager.get_all()
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
@@ -101,6 +102,7 @@ def printerProfilesAdd():
return jsonify(dict(profile=_convert_profile(saved_profile)))
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
@restricted_access
@Permissions.CONNECTION.require(403)
def printerProfilesGet(identifier):
profile = printerProfileManager.get(identifier)
+10 -1
View File
@@ -11,6 +11,7 @@ from werkzeug.exceptions import BadRequest
from octoprint.server import slicingManager
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
from octoprint.server.api import api, NO_CONTENT
from octoprint.access.permissions import Permissions
from octoprint.settings import settings as s, valid_boolean_trues
@@ -53,7 +54,7 @@ def _etag(configured, lm=None):
hash.update(slicer)
hash.update(str(slicer_impl.is_slicer_configured()))
hash.update(str(slicer == default_slicer))
hash.update(_DATA_FORMAT_VERSION) # increment version if we change the API format
return hash.hexdigest()
@@ -63,6 +64,7 @@ def _etag(configured, lm=None):
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("configured", "false") in valid_boolean_trues, lm=lm),
lastmodified_factory=lambda: _lastmodified(request.values.get("configured", "false") in valid_boolean_trues),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@Permissions.SLICE.require(403)
def slicingListAll():
from octoprint.filemanager import get_extensions
@@ -101,6 +103,8 @@ def slicingListAll():
return jsonify(result)
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
@restricted_access
@Permissions.SLICE.require(403)
def slicingListSlicerProfiles(slicer):
configured = False
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
@@ -112,6 +116,8 @@ def slicingListSlicerProfiles(slicer):
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
@restricted_access
@Permissions.SLICE.require(403)
def slicingGetSlicerProfile(slicer, name):
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
@@ -126,6 +132,7 @@ def slicingGetSlicerProfile(slicer, name):
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
@restricted_access
@Permissions.SETTINGS.require(403)
def slicingAddSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
@@ -161,6 +168,7 @@ def slicingAddSlicerProfile(slicer, name):
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
@restricted_access
@Permissions.SETTINGS.require(403)
def slicingPatchSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
@@ -204,6 +212,7 @@ def slicingPatchSlicerProfile(slicer, name):
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
@restricted_access
@Permissions.SETTINGS.require(403)
def slicingDelSlicerProfile(slicer, name):
try:
slicingManager.delete_profile(slicer, name)
+6 -4
View File
@@ -73,10 +73,11 @@ def _etag(unrendered, lm=None):
return hash.hexdigest()
@api.route("/timelapse", methods=["GET"])
@restricted_access
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm),
lastmodified_factory=lambda: _lastmodified(request.values.get("unrendered", "false") in valid_boolean_trues),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@Permissions.TIMELAPSE.require(403)
@Permissions.TIMELAPSE_LIST.require(403)
def getTimelapseData():
timelapse = octoprint.timelapse.current
config = _config_for_timelapse(timelapse)
@@ -121,14 +122,15 @@ def getTimelapseData():
@api.route("/timelapse/<filename>", methods=["GET"])
@Permissions.TIMELAPSE.require(403)
@restricted_access
@Permissions.TIMELAPSE_DOWNLOAD.require(403)
def downloadTimelapse(filename):
return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename)
@api.route("/timelapse/<filename>", methods=["DELETE"])
@restricted_access
@Permissions.TIMELAPSE_ADMIN.require(403)
@Permissions.TIMELAPSE_DELETE.require(403)
def deleteTimelapse(filename):
if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4", "m4v", "mkv"]):
timelapse_folder = settings().getBaseFolder("timelapse")
@@ -145,7 +147,7 @@ def deleteTimelapse(filename):
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
@restricted_access
@Permissions.TIMELAPSE_ADMIN.require(403)
@Permissions.TIMELAPSE_DELETE.require(403)
def deleteUnrenderedTimelapse(name):
octoprint.timelapse.delete_unrendered_timelapse(name)
return NO_CONTENT
+17 -42
View File
@@ -1,86 +1,61 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
from octoprint.util import deprecated
from octoprint.server.api import api
from octoprint.server.api import api_access as access
from octoprint.server.util.flask import restricted_access
from octoprint.access.permissions import Permissions
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.server.api import api
from flask import redirect, url_for
# NOTE: The redirects here should rather be 308 PERMANENT REDIRECT, however RFC7538 doesn't seem to be supported
# by all browsers yet. So we stick to 307 TEMPORARY REDIRECT as defined in RFC7231 although it's definitely not a
# temporary redirect we have here.
@api.route("/users", methods=["GET"])
@deprecated("/users has been moved to /access/users")
@restricted_access
@Permissions.SETTINGS.require(403)
def getUsers():
return access.get_users()
def deprecated_get_users():
return redirect(url_for("api.get_users"), code=307)
@api.route("/users", methods=["POST"])
@deprecated("/users has been moved to /access/users")
@restricted_access
@Permissions.SETTINGS.require(403)
def addUser():
return access.add_user()
return redirect(url_for("api.add_user"), code=307)
@api.route("/users/<username>", methods=["GET"])
@deprecated("/users/<username> has been moved to /access/users/<username>")
@restricted_access
def getUser(username):
return access.get_user(username)
return redirect(url_for("api.get_user", username=username), code=307)
@api.route("/users/<username>", methods=["PUT"])
@deprecated("/users/<username> has been moved to /access/users/<username>")
@restricted_access
@Permissions.SETTINGS.require(403)
def updateUser(username):
return access.update_user(username)
return redirect(url_for("api.update_user", username=username), code=307)
@api.route("/users/<username>", methods=["DELETE"])
@deprecated("/users/<username> has been moved to /access/users/<username>")
@restricted_access
@Permissions.SETTINGS.require(403)
def removeUser(username):
return access.remove_user(username)
return redirect(url_for("api.remove_user", username=username), code=307)
@api.route("/users/<username>/password", methods=["PUT"])
@deprecated("/users/<username> has been moved to /access/users/<username>")
@restricted_access
def changePasswordForUser(username):
return access.change_password_for_user(username)
return redirect(url_for("api.change_password_for_user", username=username), code=307)
@api.route("/users/<username>/settings", methods=["GET"])
@deprecated("/users/<username>/settings has been moved to /access/users/<username>/settings")
@restricted_access
def getSettingsForUser(username):
return access.get_settings_for_user(username)
return redirect(url_for("api.get_settings_for_user", username=username), code=307)
@api.route("/users/<username>/settings", methods=["PATCH"])
@deprecated("/users/<username>/settings has been moved to /access/users/<username>/settings")
@restricted_access
def changeSettingsForUser(username):
return access.change_settings_for_user(username)
return redirect(url_for("api.change_settings_for_user", username=username), code=307)
@api.route("/users/<username>/apikey", methods=["DELETE"])
@deprecated("/users/<username>/apikey has been moved to /access/users/<username>/apikey")
@restricted_access
def deleteApikeyForUser(username):
return access.delete_apikey_for_user(username)
return redirect(url_for("api.delete_apikey_for_user", username=username), code=307)
@api.route("/users/<username>/apikey", methods=["POST"])
@deprecated("/users/<username>/apikey has been moved to /access/users/<username>/apikey")
@restricted_access
def generateApikeyForUser(username):
return access.generate_apikey_for_user(username)
return redirect(url_for("api.generate_apikey_for_user", username=username), code=307)
+7 -5
View File
@@ -163,6 +163,11 @@ class JsonEncodingSessionWrapper(wrapt.ObjectProxy):
class PrinterStateConnection(sockjs.tornado.SockJSConnection,
octoprint.printer.PrinterCallback,
LoginStatusListener):
_emit_permissions = {"connected": [],
"reauthRequired": [],
"*": [Permissions.STATUS]}
def __init__(self, printer, fileManager, analysisQueue, userManager, groupManager, eventManager, pluginManager, session):
if isinstance(session, sockjs.tornado.session.Session):
session = JsonEncodingSessionWrapper(session)
@@ -260,7 +265,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection,
if not len(parts) == 2:
raise ValueError()
except ValueError:
self._logger.warn("Got invalid auto message from client {}, ignoring: {!r}".format(self._remoteAddress, message["auth"]))
self._logger.warn("Got invalid auth message from client {}, ignoring: {!r}".format(self._remoteAddress, message["auth"]))
else:
user_id, user_session = parts
user = self._userManager.find_user(userid=user_id, session=user_session)
@@ -268,7 +273,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection,
if user is not None:
self._user = user
self._reregister()
self._logger.info("User {} logged in on the socket".format(user.get_name()))
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(), self._remoteAddress))
else:
self._user = AnonymousUser([self._groupManager.guest_group])
self._reregister()
@@ -433,9 +438,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection,
def _sendReauthRequired(self, reason):
self._emit("reauthRequired", payload=dict(reason=reason))
_emit_permissions = {"connected": [],
"reauthRequired": [],
"*": [Permissions.STATUS]}
def _emit(self, type, payload=None, permissions=None):
if payload is None:
payload = dict()
+6 -8
View File
@@ -539,19 +539,17 @@ def _process_templates():
templates["sidebar"]["entries"]= dict(
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", template_header="sidebar/connection_header.jinja2")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.STATUS)")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2", styles_wrapper=["display: none;"],
data_bind="visible: loginState.hasPermissionKo(access.permissions.FILES_ACCESS)")
)
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.FILES_LIST)"))
)
# tabs
templates["tab"]["entries"] = dict(
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.STATUS)")),
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.WEBCAM) || loginState.hasPermissionKo(access.permissions.CONTROL)")),
gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.DOWNLOAD)")),
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.TERMINAL)")),
timelapse=(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE_ACCESS)"))
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)")),
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)")),
gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.GCODE_VIEWER)")),
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)")),
timelapse=(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.TIMELAPSE)"))
)
# settings dialog
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
+26 -20
View File
@@ -121,6 +121,28 @@ $(function() {
exports.onBrowserVisibilityChange = function(callback) {
browserVisibilityCallbacks.push(callback);
};
exports.updateTab = function() {
var tabs = $('#tabs');
var hashtag = window.location.hash;
if (hashtag) {
var selectedTab = tabs.find('a[href="' + hashtag + '"]:visible');
if (selectedTab.length) {
selectedTab.tab("show");
return;
}
}
var firstTab = tabs.find('a[data-toggle=tab]:visible').eq(0);
if (firstTab.length) {
var firstHash = firstTab[0].hash;
if (firstHash !== exports.selectedTab) {
firstTab.tab("show");
} else {
window.location.hash = firstHash;
}
}
};
return exports;
})();
@@ -512,13 +534,13 @@ $(function() {
var tabs = $('#tabs').find('a[data-toggle="tab"]');
tabs.on('show', function (e) {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
var previous = e.relatedTarget ? e.relatedTarget.hash : undefined;
onTabChange(current, previous);
});
tabs.on('shown', function (e) {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
var previous = e.relatedTarget ? e.relatedTarget.hash : undefined;
onAfterTabChange(current, previous);
// make sure we also update the hash but stick to the current scroll position
@@ -527,19 +549,6 @@ $(function() {
$('html,body').scrollTop(scrollmem);
});
onTabChange(OCTOPRINT_INITIAL_TAB);
onAfterTabChange(OCTOPRINT_INITIAL_TAB, undefined);
var changeTab = function() {
var hashtag = window.location.hash;
if (!hashtag) return;
var tab = $('#tabs').find('a[href="' + hashtag + '"]');
if (tab) {
tab.tab("show");
}
};
// Fix input element click problems on dropdowns
$(".dropdown input, .dropdown label").click(function(e) {
e.stopPropagation();
@@ -673,13 +682,9 @@ $(function() {
});
$(window).on("hashchange", function() {
changeTab();
OctoPrint.coreui.updateTab();
});
if (window.location.hash !== "") {
changeTab();
}
log.info("Application startup complete");
viewModelMap["uiStateViewModel"].loading(false);
@@ -687,6 +692,7 @@ $(function() {
// startup complete
callViewModels(allViewModels, "onStartupComplete");
setOnViewModels(allViewModels, "_startupComplete", true);
OctoPrint.coreui.updateTab();
};
var fetchSettings = function() {
@@ -50,7 +50,7 @@ $(function() {
self.refreshVisible = ko.observable(true);
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION_ACCESS)) {
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) {
return;
}
@@ -87,12 +87,16 @@ $(function() {
self._processStateData(data.state);
};
self.openOrCloseOnStateChange = function() {
self.openOrCloseOnStateChange = function(force) {
if (!self._startupComplete && !force) return;
var connectionTab = $("#connection");
if (self.isOperational() && connectionTab.hasClass("in")) {
connectionTab.collapse("hide");
self.refreshVisible(false);
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
connectionTab.collapse("show");
self.refreshVisible(true);
}
};
@@ -107,7 +111,7 @@ $(function() {
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
if (self.loginState.hasPermission(self.access.permissions.CONNECTION_ACCESS) && self.previousIsOperational !== self.isOperational()) {
if (self.previousIsOperational !== self.isOperational()) {
// only open or close if the panel is visible (for admins) and
// the state just changed to avoid thwarting manual open/close
self.openOrCloseOnStateChange();
@@ -164,20 +168,14 @@ $(function() {
connectionTab.on("hide", function() {
self.refreshVisible(false);
});
};
self.requestData();
self.onStartupComplete = function() {
self.openOrCloseOnStateChange(true);
};
self.onUserLoggedIn = function() {
if (self.loginState.hasPermission(self.access.permissions.CONNECTION_ACCESS)) {
self.openOrCloseOnStateChange();
}
};
self.onUserLoggedOut = function() {
if (self.loginState.hasPermission(self.access.permissions.CONNECTION_ACCESS)) {
self.openOrCloseOnStateChange();
}
self.requestData();
};
}
+36 -19
View File
@@ -77,7 +77,7 @@ $(function() {
self.addFolderDialog = undefined;
self.addFolderName = ko.observable(undefined);
self.enableAddFolder = ko.pureComputed(function() {
return self.loginState.hasPermission(self.access.permissions.UPLOAD) && self.addFolderName() && self.addFolderName().trim() !== "" && !self.addingFolder();
return self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD) && self.addFolderName() && self.addFolderName().trim() !== "" && !self.addingFolder();
});
self.allItems = ko.observable(undefined);
@@ -159,7 +159,7 @@ $(function() {
});
self.isLoadActionPossible = ko.pureComputed(function() {
return self.loginState.hasPermission(self.access.permissions.SELECT) && self.isOperational() && !self.isPrinting() && !self.isPaused() && !self.isLoading();
return self.loginState.hasPermission(self.access.permissions.FILES_SELECT) && self.isOperational() && !self.isPrinting() && !self.isPaused() && !self.isLoading();
});
self.isLoadAndPrintActionPossible = ko.pureComputed(function() {
@@ -211,7 +211,7 @@ $(function() {
self._focus = undefined;
self._switchToPath = undefined;
self.requestData = function(params) {
if (!self.loginState.hasPermission(self.access.permissions.FILES_ACCESS)) {
if (!self.loginState.hasPermission(self.access.permissions.FILES_LIST)) {
return;
}
@@ -350,6 +350,8 @@ $(function() {
};
self.showAddFolderDialog = function() {
if (!self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD)) return;
if (self.addFolderDialog) {
self.addFolderName("");
self.addFolderDialog.modal("show");
@@ -357,6 +359,8 @@ $(function() {
};
self.addFolder = function() {
if (!self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD)) return;
var name = self.addFolderName();
// "local" only for now since we only support local and sdcard,
@@ -389,6 +393,8 @@ $(function() {
};
self.removeFolder = function(folder, event) {
if (!self.loginState.hasPermission(self.access.permissions.FILES_DELETE)) return;
if (!folder) {
return;
}
@@ -412,6 +418,8 @@ $(function() {
};
self.loadFile = function(data, printAfterLoad) {
if (!self.loginState.hasPermission(self.access.permissions.FILES_SELECT)) return;
if (!data) {
return;
}
@@ -429,6 +437,8 @@ $(function() {
};
self.removeFile = function(file, event) {
if (!self.loginState.hasPermission(self.access.permissions.FILES_DELETE)) return;
if (!file) {
return;
}
@@ -441,6 +451,8 @@ $(function() {
};
self.sliceFile = function(file) {
if (!self.loginState.hasPermission(self.access.permissions.SLICE)) return;
if (!file) {
return;
}
@@ -449,14 +461,17 @@ $(function() {
};
self.initSdCard = function() {
if (!self.loginState.hasPermission(self.access.permissions.CONTROL)) return;
OctoPrint.printer.initSd();
};
self.releaseSdCard = function() {
if (!self.loginState.hasPermission(self.access.permissions.CONTROL)) return;
OctoPrint.printer.releaseSd();
};
self.refreshSdFiles = function() {
if (!self.loginState.hasPermission(self.access.permissions.CONTROL)) return;
OctoPrint.printer.refreshSd();
};
@@ -564,12 +579,12 @@ $(function() {
} else {
busy = _.contains(self.printerState.busyFiles(), data.origin + ":" + data.path);
}
return self.loginState.hasPermission(self.access.permissions.DELETE) && !busy;
return self.loginState.hasPermission(self.access.permissions.FILES_DELETE) && !busy;
};
self.enableSelect = function(data) {
return self.isLoadAndPrintActionPossible() && !self.listHelper.isSelected(data);
}
};
self.enablePrint = function(data) {
return self.loginState.hasPermission(self.access.permissions.PRINT) && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading());
@@ -778,25 +793,27 @@ $(function() {
return recursiveSearch(path.split("/"), root);
};
self.onUserLoggedIn = function(user) {
self.uploadButton.fileupload("enable");
if (self.uploadSdButton) {
self.uploadSdButton.fileupload("enable");
self.updateButtons = function() {
if (self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD)) {
self.uploadButton.fileupload("enable");
if (self.uploadSdButton) {
self.uploadSdButton.fileupload("enable");
}
} else {
self.uploadButton.fileupload("disable");
if (self.uploadSdButton) {
self.uploadSdButton.fileupload("disable");
}
}
};
// After login, request Data,
// if no permission existed to view any files and now exists the file list will be filled
self.onUserLoggedIn = function(user) {
self.updateButtons();
self.requestData();
};
self.onUserLoggedOut = function() {
self.uploadButton.fileupload("disable");
if (self.uploadSdButton) {
self.uploadSdButton.fileupload("disable");
}
// After logout, request Data,
// if no permission exists to view any files the files list will be cleared
self.updateButtons();
self.requestData();
};
@@ -855,7 +872,7 @@ $(function() {
self.dropOverlay.on('drop', self._forceEndDragNDrop);
function evaluateDropzones() {
var enableLocal = self.loginState.hasPermission(self.access.permissions.UPLOAD);
var enableLocal = self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD);
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady() && !self.isPrinting();
self._setDropzone("local", enableLocal);
@@ -6,7 +6,7 @@ $(function() {
self.loginPass = ko.observable("");
self.loginRemember = ko.observable(false);
self.loggedIn = ko.observable(false);
self.loggedIn = ko.observable(undefined);
self.username = ko.observable(undefined);
self.userneeds = ko.observable(undefined);
self.isAdmin = ko.observable(false);
@@ -61,7 +61,7 @@ $(function() {
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
if (!currentLoggedIn) {
if (!currentLoggedIn || currentLoggedIn === undefined) {
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in");
}
@@ -71,11 +71,12 @@ $(function() {
} else {
self.loggedIn(false);
self.updateCurrentUserData(response);
if (currentLoggedIn) {
if (currentLoggedIn || currentLoggedIn === undefined) {
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
}
OctoPrint.coreui.updateTab();
};
if (self.startupDeferred !== undefined) {
@@ -114,7 +115,7 @@ $(function() {
self.login = function(u, p, r, notifications) {
var username = u || self.loginUser();
var password = p || self.loginPass();
var remember = (r != undefined ? r : self.loginRemember());
var remember = (r !== undefined ? r : self.loginRemember());
notifications = notifications !== false;
return OctoPrint.browser.login(username, password, remember)
@@ -241,20 +242,20 @@ $(function() {
};
/////////////////////////////////////////////////////////////////////////////////////////////////
// //
// hasPermission: checks if the currently logged in user has a specific permission //
// This check is performed by testing if the necessary needs set is available //
// //
/////////////////////////////////////////////////////////////////////////////////////////////////
// //
// Possible function call and what it returns: //
// //
// loginState.hasPermission(access.permissions.SETTINGS) //
// - Returns true if the currently logged in user has SETTINGS permission //
// //
/////////////////////////////////////////////////////////////////////////////////////////////////
self.hasPermission = function(permission) {
/**
* Checks if the currently logged in user has a specific permission.
*
* This check is performed by testing if the necessary needs set is available.
*
* Example:
*
* loginState.hasPermission(access.permissions.SETTINGS)
*
* @param permission the permission to check for
* @returns true if the user has the specified permission, false otherwise
* @type {boolean}
*/
var userneeds = self.userneeds();
if (userneeds === undefined || permission === undefined)
return false;
@@ -270,11 +271,73 @@ $(function() {
});
};
// Knockout wrapper for the hasPermission function
self.hasAnyPermission = function() {
/**
* Checks if the currently logged in user has any of the specified permissions.
*
* Uses hasPermission for that.
*
* Example:
*
* loginState.hasAnyPermission(access.permission.CONTROL, access.permission.MONITOR_TERMINAL)
*
* @returns true if the user has any of the specified permissions, false otherwise
* @type {boolean}
*/
var result = false;
_.each(arguments, function(permission) {
result = result || self.hasPermission(permission);
});
return result;
};
self.hasAllPermissions = function() {
/**
* Checks if the currently logged in user has all of the specified permissions.
*
* Uses hasPermission for that.
*
* Example:
*
* loginState.hasAnyPermission(access.permission.CONTROL, access.permission.MONITOR_TERMINAL)
*
* @returns true if the user has all of the specified permissions, false otherwise
* @type {boolean}
*/
var result = true;
_.each(arguments, function(permission) {
result = result && self.hasPermission(permission);
});
return result;
};
self.hasPermissionKo = function(permission) {
/**
* Knockout wrapper for hasPermission
*/
return ko.pureComputed(function() {
return self.hasPermission(permission);
}).extend({ notify: 'always' });
}).extend({ notify: "always" });
};
self.hasAnyPermissionKo = function() {
/**
Knockout wrapper for hasAnyPermission
*/
var permissions = arguments;
return ko.pureComputed(function() {
return self.hasAnyPermission.apply(null, permissions);
}).extend({ notify: "always" });
};
self.hasAllPermissionsKo = function() {
/**
* Knockout wrapper for hasAllPermissions
*/
var permissions = arguments;
return ko.pureComputed(function() {
return self.hasAllPermissions.apply(null, permissions);
});
};
}
+4 -1
View File
@@ -1480,6 +1480,8 @@ input[type="number"].input-nospin {
// page wide login form
#page-container-needlogin {
background-color: #ffffff;
z-index: 12300;
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
@@ -1513,7 +1515,8 @@ input[type="number"].input-nospin {
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
background-color: #ffffff;
z-index: 12301;
.wrapper {
position: absolute;
+1 -1
View File
@@ -83,7 +83,7 @@
{% set entry, data = templates.tab.entries[key] %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<li id="{{ data._div }}_link"
class="{% if loop.first %}active{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
class="{% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
@@ -1,13 +1,13 @@
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()">{{ _('Serial Port') }}</label>
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()"></select>
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Serial Port') }}</label>
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label for="connection_printers" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select id="connection_printers" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()"></select>
<select id="connection_printers" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()"> {{ _('Save connection settings') }}
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Save connection settings') }}
</label>
<label class="checkbox">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)() && isErrorOrClosed()"> {{ _('Auto-connect on server startup') }}
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Auto-connect on server startup') }}
</label>
<button class="btn btn-block" id="printer_connect" data-bind="click: function() { if (loginState.hasPermission(access.permissions.CONNECTION)) { connect(); } }, text: buttonText, enable: loginState.hasPermissionKo(access.permissions.CONNECTION)">{{ _('Connect') }}</button>
<button class="btn btn-block" id="printer_connect" data-bind="click: connect, text: buttonText">{{ _('Connect') }}</button>
+7 -7
View File
@@ -19,9 +19,9 @@
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data') }}"><i class="fa fa-chevron-down"></i></div>
<a class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.DOWNLOAD), attr: {href: $root.downloadLink($data)}, css: {disabled: !$root.downloadLink($data)}" title="{{ _('Download') }}"><i class="fa fa-download"></i></a>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFile($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.SELECT), click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load') }}"><i class="fa fa-folder-open"></i></div>
<a class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DOWNLOAD), attr: {href: $root.downloadLink($data)}, css: {disabled: !$root.downloadLink($data)}" title="{{ _('Download') }}"><i class="fa fa-download"></i></a>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFile($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_SELECT), click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load') }}"><i class="fa fa-folder-open"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.PRINT), click: function() { if ($root.enableSelectAndPrint($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelectAndPrint($data)}" title="{{ _('Load and Print') }}"><i class="fa fa-print"></i></div>
</div>
</script>
@@ -32,8 +32,8 @@
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
<a class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.DOWNLOAD), attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="fa fa-download"></i></a>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFile($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
<a class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DOWNLOAD), attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="fa fa-download"></i></a>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFile($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.SLICE), click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}" title="{{ _('Slice') }}"><i class="fa fa-magic"></i></div>
</div>
</script>
@@ -43,14 +43,14 @@
<div class="internal" data-bind="visible: name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFolder($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFolder($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
</div>
</script>
</div>
<div class="text-right muted" data-bind="attr: {title: diskusageString}, css: {'text-error': diskusageCritical}, style: {'font-weight': diskusageCritical() || diskusageWarning() ? 'bold' : 'normal'}">
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span> / {{ _('Total') }}: <span data-bind="text: totalSpaceString"></span> <i class="fa fa-exclamation-triangle" data-bind="visible: diskusageWarning" style="display: none"></i></small>
</div>
<div style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.UPLOAD)">
<div style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.FILES_UPLOAD)">
<div class="row-fluid folder-button">
<span class="btn addfolder-button span12" data-bind="click: $root.showAddFolderDialog">
<i class="fa fa-folder"></i> {{ _('Create folder...') }}
@@ -34,7 +34,7 @@
</div>
{% if enableSdSupport %}
<div class="sd-trigger accordion-heading-button btn-group">
<div class="sd-trigger accordion-heading-button btn-group" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
<span class="icon-sd-black-14"></span>
</a>