Merge branch 'dev/granularPermissions' into devel
# Conflicts: # src/octoprint/server/api/files.py # src/octoprint/server/api/job.py # src/octoprint/static/js/app/viewmodels/users.js
This commit is contained in:
commit
d8eb57548d
99 files changed
+5806
-2273
No files matched your search
+43
-30
@@ -220,6 +220,11 @@ onUserLoggedIn(user)
|
||||
onUserLoggedOut()
|
||||
Called when a user gets logged out of the web app.
|
||||
|
||||
onUserPermissionsChanged(user)
|
||||
Called when a change in the permissions of the current user is detected. The user data of the just logged in user
|
||||
will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
|
||||
group is modified. In this case ``user`` will be undefined.
|
||||
|
||||
onTabChange(next, current)
|
||||
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
|
||||
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
|
||||
@@ -313,13 +318,13 @@ Web interface startup
|
||||
|
||||
sequenceDiagram
|
||||
participant Main
|
||||
participant onServerConnect
|
||||
participant fetchSettings
|
||||
participant bindViewModels
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
participant SettingsViewModel
|
||||
participant UiStateViewModel
|
||||
|
||||
Note right of DataUpdater: connectCallback = undefined
|
||||
Note over DataUpdater: connectCallback = undefined
|
||||
Note over UiStateViewModel: loaded = false
|
||||
|
||||
activate Main
|
||||
|
||||
@@ -337,52 +342,60 @@ Web interface startup
|
||||
Main->>+DataUpdater: connectCallback = onServerConnect
|
||||
Note right of DataUpdater: connectCallback = onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
Main->>+onServerConnect: call
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
onServerConnect-->>Main: ok
|
||||
deactivate onServerConnect
|
||||
Main->>+Main: onServerConnect
|
||||
Main->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>Main: ok
|
||||
Main-->>Main: ok
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over Main,LoginStateViewModel: Session available!
|
||||
LoginStateViewModel-X+onServerConnect: done
|
||||
Note over Main,UiStateViewModel: Session available!
|
||||
LoginStateViewModel-X+Main: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
Main->>+DataUpdater: initialized
|
||||
Note right of DataUpdater: initialized = true
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>-onServerConnect: ok
|
||||
onServerConnect-X+Main: done
|
||||
deactivate onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
|
||||
Main->>+fetchSettings: call
|
||||
Note right of fetchSettings: trigger onStartup
|
||||
Main->>+Main: fetchSettings
|
||||
Note right of Main: trigger onStartup
|
||||
|
||||
fetchSettings-->>Main: ok
|
||||
Main->>+SettingsViewModel: requestData
|
||||
SettingsViewModel-->>Main: ok
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
|
||||
fetchSettings->>+fetchSettings: asynchronous settings fetch
|
||||
fetchSettings->>+bindViewModels: call
|
||||
SettingsViewModel->>+SettingsViewModel: asynchronous settings fetch
|
||||
Note over Main,UiStateViewModel: Settings available!
|
||||
SettingsViewModel-X+Main: done
|
||||
deactivate SettingsViewModel
|
||||
deactivate SettingsViewModel
|
||||
|
||||
Main->>+Main: bindViewModels
|
||||
|
||||
loop for each view model
|
||||
bindViewModels->bindViewModels: trigger onBeforeBinding
|
||||
bindViewModels->bindViewModels: trigger onBoundTo
|
||||
bindViewModels->bindViewModels: trigger onAfterBinding
|
||||
Main->Main: trigger onBeforeBinding
|
||||
Main->Main: trigger onBoundTo
|
||||
Main->Main: trigger onAfterBinding
|
||||
end
|
||||
|
||||
bindViewModels->bindViewModels: trigger onAllBound
|
||||
Main->Main: trigger onAllBound
|
||||
opt User is logged in
|
||||
bindViewModels->>+LoginStateViewModel: onAllBound
|
||||
Main->>+LoginStateViewModel: onAllBound
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
LoginStateViewModel-->>-bindViewModels: ok
|
||||
LoginStateViewModel-->>-Main: ok
|
||||
end
|
||||
bindViewModels->bindViewModels: trigger onStartupComplete
|
||||
bindViewModels-->>-fetchSettings: ok
|
||||
|
||||
deactivate fetchSettings
|
||||
deactivate fetchSettings
|
||||
Main->>+UiStateViewModel: loaded
|
||||
Note right of UiStateViewModel: loaded = true
|
||||
UiStateViewModel-->>-Main: ok
|
||||
|
||||
Main->Main: trigger onStartupComplete
|
||||
deactivate Main
|
||||
deactivate Main
|
||||
|
||||
|
||||
.. _sec-plugins-viewmodels-reconnect:
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
ADMIN_GROUP = "admins"
|
||||
USER_GROUP = "users"
|
||||
GUEST_GROUP = "guests"
|
||||
@@ -0,0 +1,506 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
import yaml
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from flask_principal import Need, Permission
|
||||
|
||||
DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN]
|
||||
"""Default admin permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.CONNECTION,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_UPLOAD,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.FILES_DELETE,
|
||||
Permissions.FILES_SELECT,
|
||||
Permissions.PRINT,
|
||||
Permissions.MONITOR_TERMINAL,
|
||||
Permissions.CONTROL,
|
||||
Permissions.SLICE,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.TIMELAPSE_ADMIN]
|
||||
"""Default user permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.MONITOR_TERMINAL]
|
||||
"""Default guest permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
|
||||
GroupNeed = partial(Need, 'group')
|
||||
GroupNeed.__doc__ = """A need with the method preset to `"group"`."""
|
||||
|
||||
|
||||
class GroupPermission(Permission):
|
||||
def __init__(self, key):
|
||||
need = GroupNeed(key)
|
||||
super(GroupPermission, self).__init__(need)
|
||||
|
||||
|
||||
class GroupManager(object):
|
||||
@classmethod
|
||||
def default_permissions_for_group(cls, group):
|
||||
result = []
|
||||
for permission in Permissions.all():
|
||||
if group in permission.default_groups:
|
||||
result.append(permission)
|
||||
return result
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._group_change_listeners = []
|
||||
self._init_defaults()
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return []
|
||||
|
||||
@property
|
||||
def admin_group(self):
|
||||
return self.find_group(ADMIN_GROUP)
|
||||
|
||||
@property
|
||||
def user_group(self):
|
||||
return self.find_group(USER_GROUP)
|
||||
|
||||
@property
|
||||
def guest_group(self):
|
||||
return self.find_group(GUEST_GROUP)
|
||||
|
||||
def _init_defaults(self):
|
||||
self.add_group(ADMIN_GROUP,
|
||||
"Admins",
|
||||
"Administrators",
|
||||
self.default_permissions_for_group(ADMIN_GROUP),
|
||||
changeable=False,
|
||||
removable=False,
|
||||
save=False)
|
||||
self.add_group(USER_GROUP,
|
||||
"Users",
|
||||
"All logged in users",
|
||||
self.default_permissions_for_group(USER_GROUP),
|
||||
default=True,
|
||||
removable=False,
|
||||
toggleable=False,
|
||||
save=False)
|
||||
self.add_group(GUEST_GROUP,
|
||||
"Guests",
|
||||
"Anyone who is not currently logged in",
|
||||
self.default_permissions_for_group(GUEST_GROUP),
|
||||
removable=False,
|
||||
toggleable=False,
|
||||
save=False)
|
||||
|
||||
def register_listener(self, listener):
|
||||
self._group_change_listeners.append(listener)
|
||||
|
||||
def unregister_listener(self, listener):
|
||||
self._group_change_listeners.remove(listener)
|
||||
|
||||
def add_group(self, key, name, description, permissions, default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def remove_group(self, key, save=True, notify=True):
|
||||
pass
|
||||
|
||||
def find_group(self, key):
|
||||
return None
|
||||
|
||||
def _to_permissions(self, *permissions):
|
||||
return filter(lambda x: x is not None,
|
||||
[Permissions.find(permission) for permission in permissions])
|
||||
|
||||
def _from_permissions(self, *permissions):
|
||||
return [permission.key for permission in permissions]
|
||||
|
||||
def _to_group(self, group):
|
||||
# noinspection PyCompatibility
|
||||
if isinstance(group, Group):
|
||||
return group
|
||||
elif isinstance(group, basestring):
|
||||
return self.find_group(group)
|
||||
elif isinstance(group, dict):
|
||||
return self.find_group(group.get("key"))
|
||||
else:
|
||||
return None
|
||||
|
||||
def _notify_listeners(self, action, group, *args, **kwargs):
|
||||
method = "on_group_{}".format(action)
|
||||
for listener in self._group_change_listeners:
|
||||
try:
|
||||
getattr(listener, method)(group, *args, **kwargs)
|
||||
except:
|
||||
self._logger.exception("Error notifying listener {!r} via {}".format(listener, method))
|
||||
|
||||
class GroupChangeListener(object):
|
||||
|
||||
def on_group_added(self, group):
|
||||
pass
|
||||
|
||||
def on_group_removed(self, group):
|
||||
pass
|
||||
|
||||
def on_group_permissions_changed(self, group, added=None, removed=None):
|
||||
pass
|
||||
|
||||
|
||||
class FilebasedGroupManager(GroupManager):
|
||||
def __init__(self, path=None):
|
||||
if path is None:
|
||||
path = settings().get(["accessControl", "groupfile"])
|
||||
if path is None:
|
||||
path = os.path.join(settings().getBaseFolder("base"), "groups.yaml")
|
||||
|
||||
self._groupfile = path
|
||||
self._groups = dict()
|
||||
self._dirty = False
|
||||
|
||||
GroupManager.__init__(self)
|
||||
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with open(self._groupfile, "r") as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if not "groups" in data:
|
||||
groups = data
|
||||
data = dict(groups=groups)
|
||||
|
||||
groups = data.get("groups", dict())
|
||||
tracked_permissions = data.get("tracked", list())
|
||||
|
||||
for key, attributes in groups.items():
|
||||
if key in self._groups:
|
||||
# group is already there (from the defaults most likely)
|
||||
if not self._groups[key].is_changeable():
|
||||
# group may not be changed -> bail
|
||||
continue
|
||||
|
||||
removable = self._groups[key].is_removable()
|
||||
changeable = self._groups[key].is_changeable()
|
||||
toggleable = self._groups[key].is_toggleable()
|
||||
else:
|
||||
removable = True
|
||||
changeable = True
|
||||
toggleable = True
|
||||
|
||||
permissions = self._to_permissions(*attributes.get("permissions", []))
|
||||
default_permissions = self.default_permissions_for_group(key)
|
||||
for permission in default_permissions:
|
||||
if not permission.key in tracked_permissions and not permission in permissions:
|
||||
permissions.append(permission)
|
||||
|
||||
self._groups[key] = Group(key, attributes.get("name", ""),
|
||||
description=attributes.get("description", ""),
|
||||
permissions=permissions,
|
||||
default=attributes.get("default", False),
|
||||
removable=removable,
|
||||
changeable=changeable,
|
||||
toggleable=toggleable)
|
||||
except:
|
||||
self._logger.exception("Error while loading groups from file {}".format(self._groupfile))
|
||||
|
||||
def _save(self, force=False):
|
||||
if self._groupfile is None or not self._dirty and not force:
|
||||
return
|
||||
|
||||
groups = dict()
|
||||
for key in self._groups.keys():
|
||||
group = self._groups[key]
|
||||
groups[key] = dict(
|
||||
name=group._name,
|
||||
description=group._description,
|
||||
permissions=self._from_permissions(*group._permissions),
|
||||
default=group._default
|
||||
)
|
||||
|
||||
data = dict(groups=groups,
|
||||
tracked=[x.key for x in Permissions.all()])
|
||||
|
||||
with atomic_write(self._groupfile, "wb", permissions=0o600, max_permissions=0o666) as f:
|
||||
import yaml
|
||||
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return list(self._groups.values())
|
||||
|
||||
@property
|
||||
def default_groups(self):
|
||||
return [group for group in self._groups.values() if group.is_default()]
|
||||
|
||||
def find_group(self, key):
|
||||
if key is None:
|
||||
return None
|
||||
return self._groups.get(key)
|
||||
|
||||
def add_group(self, key, name, description, permissions, default=False, removable=True,
|
||||
changeable=True, toggleable=True, overwrite=False, notify=True, save=True):
|
||||
if key in self._groups.keys() and not overwrite:
|
||||
raise GroupAlreadyExists(key)
|
||||
|
||||
if not permissions:
|
||||
permissions = []
|
||||
|
||||
permissions = self._to_permissions(*permissions)
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
group = Group(key, name,
|
||||
description=description,
|
||||
permissions=permissions,
|
||||
default=default,
|
||||
changeable=changeable,
|
||||
removable=removable,
|
||||
toggleable=toggleable)
|
||||
self._groups[key] = group
|
||||
|
||||
if save:
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
self._notify_listeners("added", group)
|
||||
|
||||
def remove_group(self, key, save=True, notify=True):
|
||||
"""Removes a Group by key"""
|
||||
group = self._to_group(key)
|
||||
if group is None:
|
||||
raise UnknownGroup(key)
|
||||
|
||||
if not group.is_removable():
|
||||
raise GroupUnremovable(key)
|
||||
|
||||
del self._groups[key]
|
||||
self._dirty = True
|
||||
|
||||
if save:
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
self._notify_listeners("removed", group)
|
||||
|
||||
def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True):
|
||||
group = self._to_group(key)
|
||||
if group is None:
|
||||
raise UnknownGroup(key)
|
||||
|
||||
if not group.is_changeable():
|
||||
raise GroupCantBeChanged(key)
|
||||
|
||||
if description is not None and description != group.get_description():
|
||||
group.change_description(description)
|
||||
self._dirty = True
|
||||
|
||||
notifications = []
|
||||
|
||||
if permissions is not None:
|
||||
permissions = self._to_permissions(*permissions)
|
||||
assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
removed_permissions = list(set(group._permissions) - set(permissions))
|
||||
added_permissions = list(set(permissions) - set(group._permissions))
|
||||
|
||||
if removed_permissions:
|
||||
self._dirty |= group.remove_permissions_from_group(removed_permissions)
|
||||
if added_permissions:
|
||||
self._dirty |= group.add_permissions_to_group(added_permissions)
|
||||
|
||||
notifications.append((("permissions_changed", group),
|
||||
dict(added=added_permissions, removed=removed_permissions)))
|
||||
|
||||
if default is not None:
|
||||
group.change_default(default)
|
||||
self._dirty = True
|
||||
|
||||
if self._dirty:
|
||||
if save:
|
||||
self._save()
|
||||
|
||||
if notify:
|
||||
for args, kwargs in notifications:
|
||||
self._notify_listeners(*args, **kwargs)
|
||||
|
||||
|
||||
class GroupAlreadyExists(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group %s already exists" % key)
|
||||
|
||||
|
||||
class UnknownGroup(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Unknown group: %s" % key)
|
||||
|
||||
|
||||
class GroupUnremovable(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group can't be removed: %s" % key)
|
||||
|
||||
|
||||
class GroupCantBeChanged(Exception):
|
||||
def __init__(self, key):
|
||||
Exception.__init__(self, "Group can't be changed: %s" % key)
|
||||
|
||||
|
||||
class Group(object):
|
||||
def __init__(self, key, name, description="", permissions=None, default=False, removable=True, changeable=True, toggleable=True):
|
||||
self._key = key
|
||||
self._name = name
|
||||
self._description = description
|
||||
self._permissions = permissions
|
||||
self._default = default
|
||||
self._removable = removable
|
||||
self._changeable = changeable
|
||||
self._toggleable = toggleable
|
||||
|
||||
def as_dict(self):
|
||||
from octoprint.access.permissions import OctoPrintPermission
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
description=self._description,
|
||||
permissions=map(lambda p: p.key, self._permissions),
|
||||
needs=OctoPrintPermission.convert_needs_to_dict(self.needs),
|
||||
default=self._default,
|
||||
removable=self._removable,
|
||||
changeable=self._changeable,
|
||||
toggleable=self._toggleable
|
||||
)
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return self._key
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def get_description(self):
|
||||
return self._description
|
||||
|
||||
def is_default(self):
|
||||
return self._default
|
||||
|
||||
def is_changeable(self):
|
||||
return self._changeable
|
||||
|
||||
def is_removable(self):
|
||||
return self._removable
|
||||
|
||||
def is_toggleable(self):
|
||||
return self._toggleable
|
||||
|
||||
def add_permissions_to_group(self, permissions):
|
||||
"""Adds a list of permissions to a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the permissions variable is of type list
|
||||
if not isinstance(permissions, list):
|
||||
permissions = [permissions]
|
||||
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
dirty = False
|
||||
for permission in permissions:
|
||||
if permissions not in self.permissions:
|
||||
self._permissions.append(permission)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def remove_permissions_from_group(self, permissions):
|
||||
"""Removes a list of permissions from a group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
# Make sure the permissions variable is of type list
|
||||
if not isinstance(permissions, list):
|
||||
permissions = [permissions]
|
||||
|
||||
assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
|
||||
|
||||
dirty = False
|
||||
for permission in permissions:
|
||||
if permission in self._permissions:
|
||||
self._permissions.remove(permission)
|
||||
dirty = True
|
||||
|
||||
return dirty
|
||||
|
||||
def change_default(self, default):
|
||||
"""Changes the default flag of a Group"""
|
||||
if not self.is_changeable():
|
||||
raise GroupCantBeChanged(self.key)
|
||||
|
||||
self._default = default
|
||||
|
||||
def change_description(self, description):
|
||||
"""Changes the description of a group"""
|
||||
self._description = description
|
||||
|
||||
@property
|
||||
def permissions(self):
|
||||
if Permissions.ADMIN in self._permissions:
|
||||
return Permissions.all()
|
||||
|
||||
return filter(lambda p: p is not None, self._permissions)
|
||||
|
||||
@property
|
||||
def needs(self):
|
||||
needs = set()
|
||||
needs.add(GroupNeed(self.key))
|
||||
for p in self.permissions:
|
||||
needs = needs.union(p.needs)
|
||||
|
||||
return needs
|
||||
|
||||
def has_permission(self, permission):
|
||||
if Permissions.ADMIN.get_name() in self._permissions:
|
||||
return True
|
||||
|
||||
return permission.needs.issubset(self.needs)
|
||||
|
||||
def __repr__(self):
|
||||
return '{}("{}", "{}", description="{}", permissions={!r}, ' \
|
||||
'default={}, removable={}, changeable={})'.format(self.__class__.__name__,
|
||||
self._key,
|
||||
self._name,
|
||||
self._description,
|
||||
self._permissions,
|
||||
bool(self._default),
|
||||
bool(self._removable),
|
||||
bool(self._changeable))
|
||||
|
||||
def __hash__(self):
|
||||
return self.key.__hash__()
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, Group) and other.key == self.key
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from flask import g, abort
|
||||
from flask_babel import gettext
|
||||
from flask_principal import Permission, PermissionDenied, RoleNeed, Need
|
||||
|
||||
from functools import wraps
|
||||
from collections import OrderedDict, defaultdict
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP
|
||||
|
||||
|
||||
class OctoPrintPermission(Permission):
|
||||
@classmethod
|
||||
def convert_needs_to_dict(cls, needs):
|
||||
ret_needs = defaultdict(list)
|
||||
for need in needs:
|
||||
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:
|
||||
# noinspection PyCompatibility
|
||||
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
|
||||
self._dangerous = kwargs.pop("dangerous", False) == True
|
||||
self._default_groups = kwargs.pop("default_groups", [])
|
||||
|
||||
self._key = None
|
||||
|
||||
Permission.__init__(self, *self.convert_to_needs(needs))
|
||||
|
||||
def as_dict(self):
|
||||
return dict(
|
||||
key=self.key,
|
||||
name=self.get_name(),
|
||||
dangerous=self._dangerous,
|
||||
default_groups=self._default_groups,
|
||||
description=self.get_description(),
|
||||
needs=self.convert_needs_to_dict(self.needs)
|
||||
)
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return self._key
|
||||
|
||||
@key.setter
|
||||
def key(self, value):
|
||||
self._key = value
|
||||
|
||||
@property
|
||||
def default_groups(self):
|
||||
return self._default_groups
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def get_description(self):
|
||||
return self._description
|
||||
|
||||
def union(self, other):
|
||||
"""Create a new OctoPrintPermission with the requirements of the union of this
|
||||
and other.
|
||||
|
||||
:param other: The other permission
|
||||
"""
|
||||
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
|
||||
p.excludes.update(self.excludes.union(other.excludes))
|
||||
return p
|
||||
|
||||
def difference(self, other):
|
||||
"""Create a new OctoPrintPermission consisting of requirements in this
|
||||
permission and not in the other.
|
||||
"""
|
||||
|
||||
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
|
||||
p.excludes.update(self.excludes.difference(other.excludes))
|
||||
return p
|
||||
|
||||
def __repr__(self):
|
||||
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__()
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
|
||||
|
||||
|
||||
class PluginOctoPrintPermission(OctoPrintPermission):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.plugin = kwargs.pop("plugin", None)
|
||||
OctoPrintPermission.__init__(self, *args, **kwargs)
|
||||
|
||||
def as_dict(self):
|
||||
result = OctoPrintPermission.as_dict(self)
|
||||
result["plugin"] = self.plugin
|
||||
return result
|
||||
|
||||
|
||||
class PluginIdentityContext(object):
|
||||
"""Identity context for not initialized Permissions
|
||||
|
||||
Needed to support @Permissions.PLUGIN_X_Y.require()
|
||||
|
||||
Will search the permission when needed
|
||||
"""
|
||||
def __init__(self, key, http_exception=None):
|
||||
self.key = key
|
||||
self.http_exception = http_exception
|
||||
"""The permission of this principal
|
||||
"""
|
||||
|
||||
@property
|
||||
def identity(self):
|
||||
"""The identity of this principal
|
||||
"""
|
||||
return g.identity
|
||||
|
||||
def can(self):
|
||||
"""Whether the identity has access to the permission
|
||||
"""
|
||||
permission = getattr(Permissions, self.key)
|
||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
||||
raise UnknownPermission(self.key)
|
||||
|
||||
return permission.can()
|
||||
|
||||
def __call__(self, f):
|
||||
@wraps(f)
|
||||
def _decorated(*args, **kw):
|
||||
with self:
|
||||
rv = f(*args, **kw)
|
||||
return rv
|
||||
|
||||
return _decorated
|
||||
|
||||
def __enter__(self):
|
||||
permission = getattr(Permissions, self.key)
|
||||
if permission is None or isinstance(permission, PluginPermissionDecorator):
|
||||
raise UnknownPermission(self.key)
|
||||
|
||||
# check the permission here
|
||||
if not permission.can():
|
||||
if self.http_exception:
|
||||
abort(self.http_exception, permission)
|
||||
raise PermissionDenied(permission)
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
|
||||
class PluginPermissionDecorator(Permission):
|
||||
"""Decorator Class for not initialized Permissions
|
||||
|
||||
Needed to support @Permissions.PLUGIN_X_Y.require()
|
||||
"""
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
|
||||
def require(self, http_exception=None):
|
||||
return PluginIdentityContext(self.key, http_exception)
|
||||
|
||||
|
||||
class PermissionsMetaClass(type):
|
||||
permissions = OrderedDict()
|
||||
|
||||
def __new__(mcs, name, bases, args):
|
||||
cls = type.__new__(mcs, name, bases, args)
|
||||
|
||||
for key, value in args.items():
|
||||
if isinstance(value, OctoPrintPermission):
|
||||
value.key = key
|
||||
mcs.permissions[key] = value
|
||||
delattr(cls, key)
|
||||
|
||||
return cls
|
||||
|
||||
def __setattr__(cls, key, value):
|
||||
if isinstance(value, OctoPrintPermission):
|
||||
if key in cls.permissions:
|
||||
raise PermissionAlreadyExists(key)
|
||||
value.key = key
|
||||
cls.permissions[key] = value
|
||||
|
||||
def __getattr__(cls, key):
|
||||
permission = cls.permissions.get(key)
|
||||
|
||||
if key.startswith("PLUGIN_") and permission is None:
|
||||
return PluginPermissionDecorator(key)
|
||||
|
||||
return permission
|
||||
|
||||
def all(cls):
|
||||
return cls.permissions.values()
|
||||
|
||||
def filter(cls, cb):
|
||||
return filter(cb, cls.all())
|
||||
|
||||
def find(cls, p, filter=None):
|
||||
key = None
|
||||
if isinstance(p, OctoPrintPermission):
|
||||
key = p.key
|
||||
elif isinstance(p, dict):
|
||||
key = p.get("key")
|
||||
elif isinstance(p, basestring):
|
||||
key = p
|
||||
|
||||
if key is None:
|
||||
return None
|
||||
|
||||
return cls.match(lambda p: p.key == key, filter=filter)
|
||||
|
||||
def match(cls, match, filter=None):
|
||||
if callable(filter):
|
||||
permissions = cls.filter(filter)
|
||||
else:
|
||||
permissions = cls.all()
|
||||
|
||||
for permission in permissions:
|
||||
if match(permission):
|
||||
return permission
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class Permissions(object):
|
||||
__metaclass__ = PermissionsMetaClass
|
||||
|
||||
# Special permission
|
||||
ADMIN = OctoPrintPermission("Admin",
|
||||
gettext("Admin is allowed to do everything"),
|
||||
RoleNeed("admin"),
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
|
||||
STATUS = OctoPrintPermission("Status",
|
||||
gettext("Allows to gather status information, e.g. job progress, "
|
||||
"printer state, temperatures, ..."),
|
||||
RoleNeed("status"),
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
|
||||
CONNECTION = OctoPrintPermission("Connection",
|
||||
gettext("Allows to connect to and disconnect from a printer"),
|
||||
RoleNeed("connection"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
WEBCAM = OctoPrintPermission("Webcam",
|
||||
gettext("Allows to watch the webcam stream"),
|
||||
RoleNeed("webcam"),
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
|
||||
SYSTEM = OctoPrintPermission("System",
|
||||
gettext("Allows to run system commands, e.g. restart OctoPrint, "
|
||||
"shutdown or reboot the system"),
|
||||
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"),
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
FILES_UPLOAD = OctoPrintPermission("File Upload",
|
||||
gettext("Allows users to upload new files"),
|
||||
RoleNeed("files_upload"),
|
||||
default_groups=[USER_GROUP])
|
||||
FILES_DOWNLOAD = OctoPrintPermission("File Download",
|
||||
gettext("Allows users to download files. The GCODE viewer is "
|
||||
"affected by this as well."),
|
||||
RoleNeed("files_download"), FILES_LIST,
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
FILES_DELETE = OctoPrintPermission("File Delete",
|
||||
gettext("Allows users to delete files"),
|
||||
RoleNeed("files_delete"), FILES_LIST,
|
||||
default_groups=[USER_GROUP])
|
||||
FILES_SELECT = OctoPrintPermission("File Select",
|
||||
gettext("Allows to select a file for printing"),
|
||||
RoleNeed("files_select"), FILES_LIST,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
PRINT = OctoPrintPermission("Print",
|
||||
gettext("Allows to start, pause and cancel a print job. Includes the \"Select\" "
|
||||
"permission"),
|
||||
RoleNeed("print"), FILES_SELECT,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
|
||||
gettext("Allows access to the GCODE viewer. Includes the \"File Download\""
|
||||
"permission."),
|
||||
RoleNeed("gcodeviewer"), FILES_DOWNLOAD,
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
|
||||
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
|
||||
gettext("Allows to watch the terminal tab but not to send commands "
|
||||
"to the printer from it"),
|
||||
RoleNeed("monitor_terminal"),
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
|
||||
CONTROL = OctoPrintPermission("Control",
|
||||
gettext("Allows to control of the printer by using the temperature controls,"
|
||||
"the control tab or sending commands through the terminal."),
|
||||
RoleNeed("control"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
SLICE = OctoPrintPermission("Slice",
|
||||
gettext("Allows to slice files"),
|
||||
RoleNeed("slice"),
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
|
||||
gettext("Allows to list timelapse videos"),
|
||||
RoleNeed("timelapse_list"),
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
|
||||
gettext("Allows to download timelapse videos"),
|
||||
RoleNeed("timelapse_download"),
|
||||
default_groups=[USER_GROUP, GUEST_GROUP])
|
||||
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
|
||||
gettext("Allows to delete timelapse videos and unrendered timelapses"),
|
||||
RoleNeed("timelapse_delete"),
|
||||
default_groups=[USER_GROUP])
|
||||
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
|
||||
gettext("Allows to change the timelapse settings and delete or "
|
||||
"render unrendered timelapses. Includes the \"Timelapse List\","
|
||||
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
|
||||
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
|
||||
default_groups=[USER_GROUP])
|
||||
|
||||
SETTINGS = OctoPrintPermission("Settings",
|
||||
gettext("Allows to manage settings"),
|
||||
RoleNeed("settings"),
|
||||
dangerous=True)
|
||||
|
||||
|
||||
|
||||
class PermissionAlreadyExists(Exception):
|
||||
def __init__(self, permission):
|
||||
Exception.__init__(self, "Permission %s already exists" % permission)
|
||||
|
||||
|
||||
class UnknownPermission(Exception):
|
||||
def __init__(self, permissionname):
|
||||
Exception.__init__(self, "Unknown permission: %s" % permissionname)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -234,12 +234,12 @@ class EventManager(object):
|
||||
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||
"""
|
||||
|
||||
if not callback in self._registeredListeners[event]:
|
||||
# callback not subscribed to event, just return
|
||||
return
|
||||
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
|
||||
try:
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
|
||||
except ValueError:
|
||||
# not registered
|
||||
pass
|
||||
|
||||
def join(self, timeout=None):
|
||||
self._worker.join(timeout)
|
||||
|
||||
@@ -94,7 +94,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
"octoprint.printer.factory",
|
||||
"octoprint.access.permissions"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
|
||||
@@ -1499,7 +1499,8 @@ class PluginManager(object):
|
||||
def register_message_receiver(self, client):
|
||||
"""
|
||||
Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two
|
||||
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself).
|
||||
input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one
|
||||
optional keyword argument, ``permissions`` (an optional list of permissions to test against).
|
||||
"""
|
||||
|
||||
if client is None:
|
||||
@@ -1511,20 +1512,25 @@ class PluginManager(object):
|
||||
Unregisters a ``client`` for receiving plugin messages.
|
||||
"""
|
||||
|
||||
self.registered_clients.remove(client)
|
||||
try:
|
||||
self.registered_clients.remove(client)
|
||||
except ValueError:
|
||||
# not registered
|
||||
pass
|
||||
|
||||
def send_plugin_message(self, plugin, data):
|
||||
def send_plugin_message(self, plugin, data, permissions=None):
|
||||
"""
|
||||
Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them
|
||||
with the two arguments.
|
||||
with the three arguments.
|
||||
|
||||
Arguments:
|
||||
plugin (str): The sending plugin's identifier.
|
||||
data (object): The message.
|
||||
permissions (list): A list of permissions to test against in the client.
|
||||
"""
|
||||
|
||||
for client in self.registered_clients:
|
||||
try: client(plugin, data)
|
||||
try: client(plugin, data, permissions=permissions)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
def _sort_hooks(self, hook):
|
||||
|
||||
@@ -1483,6 +1483,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
from flask_login import current_user
|
||||
import copy
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
data = copy.deepcopy(self._settings.get_all_data(merged=True))
|
||||
if self.config_version_key in data:
|
||||
@@ -1528,7 +1530,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
node[key] = None
|
||||
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
|
||||
admin=lambda: current_user is not None and not current_user.is_anonymous and current_user.is_admin,
|
||||
admin=lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS),
|
||||
never=lambda: False)
|
||||
|
||||
for level, condition in conditions.items():
|
||||
@@ -1604,8 +1606,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
|
||||
|
||||
Override this in your plugin's implementation to restrict whether a path should only be returned to logged in
|
||||
users & admins, only to admins, or never on the REST API.
|
||||
Override this in your plugin's implementation to restrict whether a path should only be returned to users with
|
||||
the SETTINGS permission, any logged in users, or never on the REST API.
|
||||
|
||||
Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of
|
||||
the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin``
|
||||
|
||||
@@ -20,12 +20,13 @@ import flask
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
|
||||
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
@@ -42,6 +43,22 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._slugify = Slugify()
|
||||
self._slugify.safe_chars = "-_."
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="READ",
|
||||
name="Read announcements",
|
||||
description=gettext("Allows to read announcements"),
|
||||
roles=["read"]),
|
||||
dict(key="MANAGE",
|
||||
name="Manage announcement subscriptions",
|
||||
description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" "
|
||||
"permission"),
|
||||
roles=["manage"],
|
||||
permissions=["PLUGIN_ANNOUNCEMENTS_READ"])
|
||||
]
|
||||
|
||||
# StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
@@ -127,14 +144,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
|
||||
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.isAdmin")
|
||||
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)")
|
||||
]
|
||||
|
||||
# Blueprint Plugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def get_channel_data(self):
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
|
||||
@@ -194,8 +211,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
unless=lambda: force)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
|
||||
def channel_command(self, channel):
|
||||
from octoprint.server.util.flask import get_json_command_from_request
|
||||
from octoprint.server import NO_CONTENT
|
||||
@@ -212,6 +229,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._mark_read_until(channel, until)
|
||||
|
||||
elif command == "toggle":
|
||||
if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can():
|
||||
return flask.make_response("Insufficient rights", 403)
|
||||
self._toggle(channel)
|
||||
|
||||
return NO_CONTENT
|
||||
@@ -495,3 +514,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin you might miss i
|
||||
"regarding security or other critical issues concerning OctoPrint.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = AnnouncementPlugin()
|
||||
|
||||
__plugin_hooks__ = {
|
||||
'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.channels = new ItemListHelper(
|
||||
"plugin.announcements.channels",
|
||||
@@ -67,7 +68,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.markRead = function(channel, until) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
|
||||
|
||||
@@ -89,7 +90,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleChannel = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
|
||||
|
||||
@@ -114,7 +115,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.retrieveData = function(force) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels";
|
||||
if (force) {
|
||||
@@ -132,7 +133,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
|
||||
|
||||
@@ -153,7 +154,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showAnnouncementDialog = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
// lazy load images that still need lazy-loading
|
||||
$("#plugin_announcements_dialog_content article img").lazyload();
|
||||
@@ -190,7 +191,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.displayAnnouncements = function(channels) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
|
||||
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
|
||||
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
|
||||
@@ -317,12 +318,12 @@ $(function() {
|
||||
self.settings.show("settings_plugin_announcements");
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.retrieveData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.hideAnnouncements();
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) {
|
||||
self.hideAnnouncements();
|
||||
} else {
|
||||
self.retrieveData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
@@ -340,7 +341,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: AnnouncementsViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
{% include "snippets/settings/cura/profiles.jinja2" %}
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }"><i class="fa fa-plus"></i> {{ _('Import Profile...') }}</button>
|
||||
|
||||
<div style="clear: both">
|
||||
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
|
||||
|
||||
@@ -7,11 +7,13 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import redirect_to_tornado, require_firstrun
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from flask_babel import gettext
|
||||
|
||||
from werkzeug.utils import secure_filename
|
||||
from werkzeug.exceptions import BadRequest
|
||||
import yaml
|
||||
@@ -27,9 +29,20 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="MANAGE",
|
||||
name="Logging management",
|
||||
description=gettext("Allows to download and delete log files and list and set log levels."),
|
||||
roles=["manage"])
|
||||
]
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_all(self):
|
||||
files = self._getLogFiles()
|
||||
free, total = self._get_usage()
|
||||
@@ -39,22 +52,22 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
setup=dict(loggers=loggers, levels=levels))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_log_files(self):
|
||||
files = self._getLogFiles()
|
||||
free, total = self._get_usage()
|
||||
return jsonify(files=files, free=free, total=total)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def download_log(self, filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def delete_log(self, filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
if not os.path.exists(secure):
|
||||
@@ -65,22 +78,22 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_setup(self):
|
||||
loggers = self._get_available_loggers()
|
||||
levels = self._get_logging_levels()
|
||||
return jsonify(loggers=loggers, levels=levels)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def get_logging_levels_api(self):
|
||||
return jsonify(self._get_logging_levels())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def set_logging_levels_api(self):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
@@ -204,4 +217,11 @@ __plugin_description__ = "Provides access to OctoPrint's logs and logging config
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve "
|
||||
"OctoPrint's logs or modify the current logging levels through "
|
||||
"the web interface.")
|
||||
__plugin_implementation__ = LoggingPlugin()
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = LoggingPlugin()
|
||||
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -11,8 +11,8 @@ import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util.pip import LocalPipCaller
|
||||
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible
|
||||
from octoprint.util.platform import get_os
|
||||
@@ -98,6 +98,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
# set a maximum body size of 50 MB for plugin archive uploads
|
||||
return [("POST", r"/upload_archive", 50 * 1024 * 1024)]
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="MANAGE",
|
||||
name="Manage plugins",
|
||||
description=gettext("Allows to enable, disable and uninstall installed plugins."),
|
||||
roles=["manage"]),
|
||||
dict(key="INSTALL",
|
||||
name="Install new plugins",
|
||||
description=gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."),
|
||||
roles=["install"],
|
||||
permissions=["PLUGIN_PLUGINMANAGER_MANAGE"],
|
||||
dangerous=True)
|
||||
]
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
@@ -167,8 +183,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ BlueprintPlugin
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403)
|
||||
def upload_archive(self):
|
||||
import flask
|
||||
|
||||
@@ -222,7 +238,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
}
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not admin_permission.can():
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
from octoprint.server import safe_mode
|
||||
@@ -276,7 +292,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
unless=lambda: refresh_repository or refresh_notices)(view)()
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not admin_permission.can():
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
@@ -284,6 +300,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return make_response("Printer is currently printing or paused", 409)
|
||||
|
||||
if command == "install":
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
url = data["url"]
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
@@ -964,6 +982,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
versions=notification.get("versions", []),
|
||||
important=notification.get("important", False))
|
||||
|
||||
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
@@ -977,5 +997,6 @@ def __plugin_load__():
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
|
||||
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
|
||||
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
@@ -89,6 +89,7 @@ $(function() {
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.printerState = parameters[2];
|
||||
self.systemViewModel = parameters[3];
|
||||
self.access = parameters[4];
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
@@ -425,7 +426,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function(options) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -449,7 +450,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.togglePlugin = function(data) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -509,7 +510,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.installFromRepository = function(data) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -521,7 +522,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -583,7 +584,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.uninstallPlugin = function(data) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -614,7 +615,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.refreshRepository = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) {
|
||||
return;
|
||||
}
|
||||
self.requestData({refresh_repo: true});
|
||||
@@ -1074,18 +1075,14 @@ $(function() {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
if (user.admin) {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
if (self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
self.requestData({eval_notices: true});
|
||||
} else {
|
||||
self.onUserLoggedOut();
|
||||
self._resetNotifications();
|
||||
}
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self._resetNotifications();
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
};
|
||||
@@ -1126,7 +1123,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1166,7 +1163,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PluginManagerViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"],
|
||||
elements: ["#settings_plugin_pluginmanager"]
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,8 @@ __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 import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
import flask
|
||||
from flask_babel import gettext
|
||||
@@ -85,7 +86,7 @@ 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)
|
||||
|
||||
@@ -96,6 +97,17 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
self._run_checks("received", line)
|
||||
return line
|
||||
|
||||
# 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"],
|
||||
default_groups=[USER_GROUP])
|
||||
]
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _run_checks(self, check_type, *args, **kwargs):
|
||||
@@ -141,6 +153,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = PrinterSafetyCheckPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received
|
||||
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
|
||||
@@ -23,11 +23,12 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.printerState = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.warnings = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.isUser()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PRINTER_SAFETY_CHECK_DISPLAY)) {
|
||||
self.warnings([]);
|
||||
return;
|
||||
}
|
||||
@@ -51,11 +52,7 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
@@ -71,7 +68,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterSafetyCheckViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel"],
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "accessViewModel"],
|
||||
elements: ["#sidebar_plugin_printer_safety_check_wrapper"]
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,15 +23,15 @@ from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
|
||||
from octoprint.server import VERSION, REVISION, BRANCH
|
||||
from octoprint.access import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import dict_merge, to_unicode
|
||||
import octoprint.settings
|
||||
|
||||
|
||||
##~~ Plugin
|
||||
|
||||
|
||||
class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
@@ -77,6 +77,22 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks)
|
||||
self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks)
|
||||
|
||||
# Additional permissions hook
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
dict(key="CHECK",
|
||||
name="Check",
|
||||
description=gettext("Allows to check for software updates"),
|
||||
roles=["check"],
|
||||
default_groups=[USER_GROUP]),
|
||||
dict(key="UPDATE",
|
||||
name="Update",
|
||||
description=gettext("Allows to perform software updates"),
|
||||
roles=["update"],
|
||||
dangerous=True)
|
||||
]
|
||||
|
||||
def on_startup(self, host, port):
|
||||
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024)
|
||||
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
@@ -472,7 +488,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
#~~ BluePrint API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
|
||||
def check_for_update(self):
|
||||
if "check" in flask.request.values:
|
||||
check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(","))
|
||||
@@ -528,8 +545,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
|
||||
def perform_update(self):
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
@@ -1027,7 +1044,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# we force an exact version & python unequality check, to be able to downgrade
|
||||
result["force_exact_version"] = True
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
elif check.get("pip", None):
|
||||
# we force python unequality check for pip installs, to be able to downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
@@ -1159,7 +1175,8 @@ def __plugin_load__():
|
||||
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.cli.commands": cli.commands
|
||||
"octoprint.cli.commands": cli.commands,
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.printerState = parameters[1];
|
||||
self.settings = parameters[2];
|
||||
self.access = parameters[3];
|
||||
self.popup = undefined;
|
||||
|
||||
self.forceUpdate = false;
|
||||
@@ -172,12 +173,12 @@ $(function() {
|
||||
return _.filter(self.versions.items(), function(info) { return info.updateAvailable && info.updatePossible; });
|
||||
});
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self._closePopup();
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
if (self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)) {
|
||||
self.performCheck();
|
||||
} else {
|
||||
self._closePopup();
|
||||
}
|
||||
};
|
||||
|
||||
self._showPopup = function(options, eventListeners, singleButtonNotify) {
|
||||
@@ -308,7 +309,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE) && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
if (data.status === "updateAvailable" || data.status === "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
@@ -327,7 +328,7 @@ $(function() {
|
||||
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) {
|
||||
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
|
||||
}
|
||||
|
||||
@@ -341,7 +342,7 @@ $(function() {
|
||||
var eventListeners = {};
|
||||
|
||||
var singleButtonNotify = false;
|
||||
if (data.status === "updatePossible" && self.loginState.isAdmin()) {
|
||||
if (data.status === "updatePossible" && self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) {
|
||||
// if update is possible and user is admin, add action buttons for ignore and update
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
@@ -402,7 +403,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
|
||||
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK) && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
self.checking(true);
|
||||
OctoPrint.plugins.softwareupdate.check(force)
|
||||
@@ -453,8 +454,6 @@ $(function() {
|
||||
self._markNotificationAsSeen = function(data) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
if (!self.loginState.isUser())
|
||||
return false;
|
||||
|
||||
var currentString = localStorage["plugin.softwareupdate.seen_information"];
|
||||
var current;
|
||||
@@ -476,9 +475,6 @@ $(function() {
|
||||
|
||||
var knownData = JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);
|
||||
|
||||
if (!self.loginState.isUser())
|
||||
return true;
|
||||
|
||||
var userData = knownData[self.loginState.username()];
|
||||
if (userData === undefined)
|
||||
return false;
|
||||
@@ -503,7 +499,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.performUpdate = function(force, items) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) return;
|
||||
|
||||
self.updateInProgress = true;
|
||||
|
||||
@@ -539,11 +535,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.update = function(force) {
|
||||
if (self.updateInProgress) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (self.updateInProgress || !self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_PERFORM)) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
@@ -573,7 +565,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self._showWorkingDialog = function(title) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_PERFORM)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -854,7 +846,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SoftwareUpdateViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"],
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
|
||||
});
|
||||
});
|
||||
@@ -580,6 +580,15 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def send_initial_callback(self, callback):
|
||||
"""
|
||||
Sends the initial printer update to :class:`PrinterCallback`.
|
||||
|
||||
Arguments:
|
||||
callback (PrinterCallback): The callback object to send initial data to.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class PrinterCallback(object):
|
||||
def on_printer_add_log(self, data):
|
||||
|
||||
@@ -132,13 +132,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
def register_callback(self, callback, *args, **kwargs):
|
||||
if not isinstance(callback, PrinterCallback):
|
||||
self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface")
|
||||
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregister_callback(self, callback, *args, **kwargs):
|
||||
if callback in self._callbacks:
|
||||
try:
|
||||
self._callbacks.remove(callback)
|
||||
except ValueError:
|
||||
# not registered
|
||||
pass
|
||||
|
||||
def send_initial_callback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
|
||||
@@ -9,7 +9,7 @@ import uuid
|
||||
from octoprint.vendor.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
|
||||
@@ -20,6 +20,12 @@ from collections import defaultdict, OrderedDict
|
||||
from builtins import bytes, range
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.util
|
||||
import octoprint.util.net
|
||||
|
||||
from octoprint.server import util
|
||||
from octoprint.util.json import JsonEncoding
|
||||
|
||||
import os
|
||||
import logging
|
||||
import logging.config
|
||||
@@ -37,6 +43,7 @@ NO_CONTENT = ("", 204)
|
||||
NOT_MODIFIED = ("Not Modified", 304)
|
||||
|
||||
app = Flask("octoprint")
|
||||
|
||||
assets = None
|
||||
babel = None
|
||||
debug = False
|
||||
@@ -48,30 +55,44 @@ fileManager = None
|
||||
slicingManager = None
|
||||
analysisQueue = None
|
||||
userManager = None
|
||||
permissionManager = None
|
||||
groupManager = None
|
||||
eventManager = None
|
||||
loginManager = None
|
||||
pluginManager = None
|
||||
appSessionManager = None
|
||||
pluginLifecycleManager = None
|
||||
preemptiveCache = None
|
||||
jsonEncoder = None
|
||||
jsonDecoder = None
|
||||
connectivityChecker = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
user_permission = Permission(RoleNeed("user"))
|
||||
|
||||
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
|
||||
import octoprint.access.permissions as permissions
|
||||
import octoprint.access.groups as groups
|
||||
|
||||
# we set admin_permission to a GroupPermission with the default admin group
|
||||
admin_permission = octoprint.util.variable_deprecated("admin_permission has been deprecated, "
|
||||
"please use individual Permissions instead",
|
||||
since="1.4.0")(groups.GroupPermission(groups.ADMIN_GROUP))
|
||||
|
||||
# we set user_permission to a GroupPermission with the default user group
|
||||
user_permission = octoprint.util.variable_deprecated("user_permission has been deprecated, "
|
||||
"please use individual Permissions instead",
|
||||
since="1.4.0")(groups.GroupPermission(groups.USER_GROUP))
|
||||
|
||||
# only import further octoprint stuff down here, as it might depend on things defined above to be initialized already
|
||||
from octoprint import __version__, __branch__, __display_version__, __revision__
|
||||
from octoprint.printer.profile import PrinterProfileManager
|
||||
from octoprint.printer.standard import Printer
|
||||
from octoprint.settings import settings
|
||||
import octoprint.users as users
|
||||
import octoprint.access.users as users
|
||||
import octoprint.access.groups as groups
|
||||
import octoprint.events as events
|
||||
import octoprint.plugin
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.util
|
||||
import octoprint.util.net
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
@@ -79,8 +100,6 @@ from octoprint.server.util import enforceApiKeyRequestHandler, loginFromApiKeyRe
|
||||
corsResponseHandler
|
||||
from octoprint.server.util.flask import PreemptiveCache
|
||||
|
||||
from . import util
|
||||
|
||||
UI_API_KEY = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
|
||||
VERSION = __version__
|
||||
@@ -95,13 +114,11 @@ LANGUAGES = set()
|
||||
def on_identity_loaded(sender, identity):
|
||||
user = load_user(identity.id)
|
||||
if user is None:
|
||||
return
|
||||
user = userManager.anonymous_user_factory()
|
||||
|
||||
identity.provides.add(UserNeed(user.get_id()))
|
||||
if user.is_user:
|
||||
identity.provides.add(RoleNeed("user"))
|
||||
if user.is_admin:
|
||||
identity.provides.add(RoleNeed("admin"))
|
||||
for need in user.needs:
|
||||
identity.provides.add(need)
|
||||
|
||||
|
||||
def _clear_identity(sender):
|
||||
@@ -127,11 +144,11 @@ def on_user_logged_out(sender, user=None):
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id == "_api":
|
||||
return users.ApiUser()
|
||||
if id is None or not userManager.enabled:
|
||||
return None
|
||||
|
||||
if not userManager.enabled:
|
||||
return users.DummyUser()
|
||||
if id == "_api":
|
||||
return users.ApiUser([groupManager.admin_group])
|
||||
|
||||
if session and "usersession.id" in session:
|
||||
sessionid = session["usersession.id"]
|
||||
@@ -139,9 +156,9 @@ def load_user(id):
|
||||
sessionid = None
|
||||
|
||||
if sessionid:
|
||||
user = userManager.findUser(userid=id, session=sessionid)
|
||||
user = userManager.find_user(userid=id, session=sessionid)
|
||||
else:
|
||||
user = userManager.findUser(userid=id)
|
||||
user = userManager.find_user(userid=id)
|
||||
|
||||
if user and user.is_active:
|
||||
return user
|
||||
@@ -202,12 +219,16 @@ class Server(object):
|
||||
global slicingManager
|
||||
global analysisQueue
|
||||
global userManager
|
||||
global permissionManager
|
||||
global groupManager
|
||||
global eventManager
|
||||
global loginManager
|
||||
global pluginManager
|
||||
global appSessionManager
|
||||
global pluginLifecycleManager
|
||||
global preemptiveCache
|
||||
global jsonEncoder
|
||||
global jsonDecoder
|
||||
global connectivityChecker
|
||||
global debug
|
||||
global safe_mode
|
||||
@@ -283,6 +304,19 @@ class Server(object):
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
|
||||
|
||||
JsonEncoding.add_encoder(users.User, lambda obj: obj.as_dict())
|
||||
JsonEncoding.add_encoder(groups.Group, lambda obj: obj.as_dict())
|
||||
JsonEncoding.add_encoder(permissions.OctoPrintPermission, lambda obj: obj.as_dict())
|
||||
|
||||
# start regular check if we are connected to the internet
|
||||
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
|
||||
connectivityChecker = self._connectivity_checker
|
||||
|
||||
def on_settings_update(*args, **kwargs):
|
||||
@@ -304,17 +338,6 @@ class Server(object):
|
||||
|
||||
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
|
||||
|
||||
# setup access control
|
||||
userManagerName = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except:
|
||||
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
|
||||
userManager = octoprint.users.FilebasedUserManager()
|
||||
finally:
|
||||
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
|
||||
|
||||
components = dict(
|
||||
plugin_manager=pluginManager,
|
||||
printer_profile_manager=printerProfileManager,
|
||||
@@ -325,12 +348,41 @@ class Server(object):
|
||||
app_session_manager=appSessionManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
preemptive_cache=preemptiveCache,
|
||||
json_encoder=jsonEncoder,
|
||||
json_decoder=jsonDecoder,
|
||||
connectivity_checker=connectivityChecker,
|
||||
environment_detector=self._environment_detector
|
||||
)
|
||||
|
||||
#~~ setup access control
|
||||
|
||||
# get additional permissions from plugins
|
||||
self._setup_plugin_permissions()
|
||||
|
||||
# create group manager instance
|
||||
group_manager_factories = pluginManager.get_hooks("octoprint.access.groups.factory")
|
||||
for name, factory in group_manager_factories.items():
|
||||
try:
|
||||
groupManager = factory(components, self._settings)
|
||||
if groupManager is not None:
|
||||
self._logger.debug("Created group manager instance from factory {}".format(name))
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Error while creating group manager instance from factory {}".format(name))
|
||||
else:
|
||||
group_manager_name = self._settings.get(["accessControl", "groupManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(group_manager_name)
|
||||
groupManager = clazz()
|
||||
except AttributeError as e:
|
||||
self._logger.exception("Could not instantiate group manager {}, "
|
||||
"falling back to FilebasedGroupManager!".format(group_manager_name))
|
||||
groupManager = octoprint.access.groups.FilebasedGroupManager()
|
||||
components.update(dict(group_manager=groupManager))
|
||||
|
||||
# create user manager instance
|
||||
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory")
|
||||
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory") # legacy, set first so that new wins
|
||||
user_manager_factories.update(pluginManager.get_hooks("octoprint.access.users.factory"))
|
||||
for name, factory in user_manager_factories.items():
|
||||
try:
|
||||
userManager = factory(components, self._settings)
|
||||
@@ -340,14 +392,14 @@ class Server(object):
|
||||
except:
|
||||
self._logger.exception("Error while creating user manager instance from factory {}".format(name))
|
||||
else:
|
||||
name = self._settings.get(["accessControl", "userManager"])
|
||||
user_manager_name = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(name)
|
||||
userManager = clazz()
|
||||
clazz = octoprint.util.get_class(user_manager_name)
|
||||
userManager = clazz(groupManager)
|
||||
except:
|
||||
self._logger.exception(
|
||||
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name))
|
||||
userManager = octoprint.users.FilebasedUserManager()
|
||||
self._logger.exception("Could not instantiate user manager {}, "
|
||||
"falling back to FilebasedUserManager!".format(user_manager_name))
|
||||
userManager = octoprint.access.users.FilebasedUserManager(groupManager)
|
||||
finally:
|
||||
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
|
||||
components.update(dict(user_manager=userManager))
|
||||
@@ -513,8 +565,12 @@ class Server(object):
|
||||
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
|
||||
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
|
||||
user_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||
##~~ Permission validators
|
||||
|
||||
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.PLUGIN_LOGGING_MANAGE))
|
||||
camera_permission_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.permission_validator, permissions.Permissions.WEBCAM))
|
||||
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
|
||||
status_code=404))
|
||||
@@ -534,22 +590,24 @@ class Server(object):
|
||||
# various downloads
|
||||
# .mpg and .mp4 timelapses:
|
||||
(r"/downloads/timelapse/([^/]*\.m(.*))", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
timelapse_permission_validator,
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
|
||||
as_attachment=True,
|
||||
name_generator=download_name_generator),
|
||||
download_permission_validator,
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
additional_mime_types)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs"),
|
||||
mime_type_guesser=lambda *args, **kwargs: "text/plain"),
|
||||
download_handler_kwargs,
|
||||
admin_validator)),
|
||||
log_permission_validator)),
|
||||
# camera snapshot
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict(dict(url=self._settings.get(["webcam", "snapshot"]),
|
||||
as_attachment=True),
|
||||
user_validator)),
|
||||
as_attachment=True),
|
||||
camera_permission_validator)),
|
||||
# generated webassets
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
|
||||
|
||||
@@ -765,7 +823,7 @@ class Server(object):
|
||||
|
||||
def _create_socket_connection(self, session):
|
||||
global printer, fileManager, analysisQueue, userManager, eventManager
|
||||
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager,
|
||||
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, groupManager,
|
||||
eventManager, pluginManager, session)
|
||||
|
||||
def _check_for_root(self):
|
||||
@@ -784,10 +842,10 @@ class Server(object):
|
||||
if hasattr(g, "identity") and g.identity and userManager.enabled:
|
||||
userid = g.identity.id
|
||||
try:
|
||||
user_language = userManager.getUserSetting(userid, ("interface", "language"))
|
||||
user_language = userManager.get_user_setting(userid, ("interface", "language"))
|
||||
if user_language is not None and not user_language == "_default":
|
||||
return Locale.negotiate([user_language], LANGUAGES)
|
||||
except octoprint.users.UnknownUser:
|
||||
except octoprint.access.users.UnknownUser:
|
||||
pass
|
||||
|
||||
default_language = self._settings.get(["appearance", "defaultLanguage"])
|
||||
@@ -814,11 +872,12 @@ class Server(object):
|
||||
|
||||
s = settings()
|
||||
|
||||
# setup octoprint's flask json serialization/deserialization
|
||||
app.json_encoder = OctoPrintJsonEncoder
|
||||
|
||||
app.debug = self._debug
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
|
||||
app.json_encoder = OctoPrintJsonEncoder
|
||||
|
||||
secret_key = s.get(["server", "secretKey"])
|
||||
if not secret_key:
|
||||
import string
|
||||
@@ -1161,7 +1220,6 @@ class Server(object):
|
||||
if self._settings.getBoolean(["devel", "webassets", "clean_on_startup"]):
|
||||
import shutil
|
||||
import errno
|
||||
import sys
|
||||
|
||||
for entry in ("webassets", ".webassets-cache"):
|
||||
path = os.path.join(base_folder, entry)
|
||||
@@ -1304,7 +1362,8 @@ class Server(object):
|
||||
"js/app/client/timelapse.js",
|
||||
"js/app/client/users.js",
|
||||
"js/app/client/util.js",
|
||||
"js/app/client/wizard.js"
|
||||
"js/app/client/wizard.js",
|
||||
"js/app/client/access.js"
|
||||
]
|
||||
|
||||
css_libs = [
|
||||
@@ -1467,16 +1526,13 @@ class Server(object):
|
||||
loginManager.session_protection = "basic"
|
||||
|
||||
loginManager.user_callback = load_user
|
||||
loginManager.anonymous_user = users.AnonymousUser # TODO: remove in 1.5.0
|
||||
loginManager.unauthorized_callback = unauthorized_user
|
||||
loginManager.anonymous_user = userManager.anonymous_user_factory
|
||||
|
||||
# login users authenticated by basic auth
|
||||
if self._settings.get(["accessControl", "trustBasicAuthentication"]):
|
||||
loginManager.request_callback = load_user_from_request
|
||||
|
||||
if not userManager.enabled:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app, add_context_processor=False)
|
||||
|
||||
def _start_intermediary_server(self):
|
||||
@@ -1605,6 +1661,114 @@ class Server(object):
|
||||
self._intermediary_server.server_close()
|
||||
self._logger.info("Intermediary server shut down")
|
||||
|
||||
def _setup_plugin_permissions(self):
|
||||
global pluginManager
|
||||
|
||||
from octoprint.access.permissions import PluginOctoPrintPermission
|
||||
|
||||
def permission_key(plugin, definition):
|
||||
return "PLUGIN_{}_{}".format(plugin.upper(), definition["key"].upper())
|
||||
|
||||
def permission_name(plugin, definition):
|
||||
return "{}: {}".format(plugin, definition["name"])
|
||||
|
||||
def permission_role(plugin, role):
|
||||
return "plugin_{}_{}".format(plugin, role)
|
||||
|
||||
def process_regular_permission(plugin_info, definition):
|
||||
permissions = []
|
||||
for key in definition.get("permissions", []):
|
||||
permission = octoprint.access.permissions.Permissions.find(key)
|
||||
|
||||
if permission is None:
|
||||
# if there is still no permission found, postpone this - maybe it is a permission from
|
||||
# another plugin that hasn't been loaded yet
|
||||
return False
|
||||
|
||||
permissions.append(permission)
|
||||
|
||||
roles = definition.get("roles", [])
|
||||
description = definition.get("description", "")
|
||||
dangerous = definition.get("dangerous", False) == True
|
||||
default_groups = definition.get("default_groups", [])
|
||||
|
||||
roles_and_permissions = [permission_role(plugin_info.key, role) for role in roles] + permissions
|
||||
|
||||
key = permission_key(plugin_info.key, definition)
|
||||
permission = PluginOctoPrintPermission(permission_name(plugin_info.name, definition),
|
||||
description,
|
||||
plugin=plugin_info.key,
|
||||
dangerous=dangerous,
|
||||
default_groups=default_groups,
|
||||
*roles_and_permissions)
|
||||
setattr(octoprint.access.permissions.Permissions,
|
||||
key,
|
||||
PluginOctoPrintPermission(permission_name(plugin_info.name, definition),
|
||||
description,
|
||||
plugin=plugin_info.key,
|
||||
dangerous=dangerous,
|
||||
default_groups=default_groups,
|
||||
*roles_and_permissions))
|
||||
|
||||
self._logger.info("Added new permission from plugin {}: {} (needs: {!r})".format(plugin_info.key,
|
||||
key,
|
||||
", ".join(map(repr, permission.needs))))
|
||||
return True
|
||||
|
||||
postponed = []
|
||||
|
||||
hooks = pluginManager.get_hooks("octoprint.access.permissions")
|
||||
for name, factory in hooks.items():
|
||||
try:
|
||||
if isinstance(factory, (tuple, list)):
|
||||
additional_permissions = list(factory)
|
||||
elif callable(factory):
|
||||
additional_permissions = factory()
|
||||
else:
|
||||
raise ValueError("factory must be either a callable, tuple or list")
|
||||
|
||||
if not isinstance(additional_permissions, (tuple, list)):
|
||||
raise ValueError("factory result must be either a tuple or a list of permission definition dicts")
|
||||
|
||||
plugin_info = pluginManager.get_plugin_info(name)
|
||||
for p in additional_permissions:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
|
||||
if not "key" in p or not "name" in p:
|
||||
continue
|
||||
|
||||
if not process_regular_permission(plugin_info, p):
|
||||
postponed.append((plugin_info, p))
|
||||
except:
|
||||
self._logger.exception("Error while creating permission instance/s from {}".format(name))
|
||||
|
||||
# final resolution passes
|
||||
pass_number = 1
|
||||
still_postponed = []
|
||||
while len(postponed):
|
||||
start_length = len(postponed)
|
||||
self._logger.debug("Plugin permission resolution pass #{}, "
|
||||
"{} unresolved permissions...".format(pass_number, start_length))
|
||||
|
||||
for plugin_info, definition in postponed:
|
||||
if not process_regular_permission(plugin_info, definition):
|
||||
still_postponed.append((plugin_info, definition))
|
||||
|
||||
self._logger.debug("... pass #{} done, {} permissions left to resolve".format(pass_number,
|
||||
len(still_postponed)))
|
||||
|
||||
if len(still_postponed) == start_length:
|
||||
# no change, looks like some stuff is unresolvable - let's bail
|
||||
for plugin_info, definition in still_postponed:
|
||||
self._logger.warn("Unable to resolve permission from {}: {!r}".format(plugin_info.key, definition))
|
||||
break
|
||||
|
||||
postponed = still_postponed
|
||||
still_postponed = []
|
||||
pass_number += 1
|
||||
|
||||
|
||||
class LifecycleManager(object):
|
||||
def __init__(self, plugin_manager):
|
||||
self._plugin_manager = plugin_manager
|
||||
|
||||
@@ -6,21 +6,19 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import netaddr
|
||||
import sarge
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g
|
||||
from flask_login import login_user, logout_user, current_user
|
||||
from flask_principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.util as util
|
||||
import octoprint.users
|
||||
import octoprint.access.users
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request, passive_login
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
|
||||
#~~ init api blueprint, including sub modules
|
||||
@@ -33,6 +31,7 @@ from . import connection as api_connection
|
||||
from . import files as api_files
|
||||
from . import settings as api_settings
|
||||
from . import timelapse as api_timelapse
|
||||
from . import access as api_access
|
||||
from . import users as api_users
|
||||
from . import slicing as api_slicing
|
||||
from . import printer_profiles as api_printer_profiles
|
||||
@@ -74,7 +73,7 @@ def pluginData(name):
|
||||
#~~ commands for plugins
|
||||
|
||||
@api.route("/plugin/<string:name>", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
def pluginCommand(name):
|
||||
api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations(lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin)
|
||||
|
||||
@@ -89,7 +88,7 @@ def pluginCommand(name):
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin:
|
||||
if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can():
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
@@ -105,7 +104,7 @@ def pluginCommand(name):
|
||||
|
||||
@api.route("/setup/wizard", methods=["GET"])
|
||||
def wizardState():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not admin_permission.can():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can():
|
||||
abort(403)
|
||||
|
||||
seen_wizards = s().get(["server", "seenWizards"])
|
||||
@@ -129,7 +128,7 @@ def wizardState():
|
||||
|
||||
@api.route("/setup/wizard", methods=["POST"])
|
||||
def wizardFinish():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not admin_permission.can():
|
||||
if not s().getBoolean(["server", "firstRun"]) and not Permissions.ADMIN.can():
|
||||
abort(403)
|
||||
|
||||
data = dict()
|
||||
@@ -170,13 +169,12 @@ def wizardFinish():
|
||||
|
||||
|
||||
@api.route("/state", methods=["GET"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
def apiPrinterState():
|
||||
return make_response(("/api/state has been deprecated, use /api/printer instead", 405, []))
|
||||
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
return jsonify({
|
||||
"server": octoprint.server.VERSION,
|
||||
@@ -205,9 +203,9 @@ def login():
|
||||
if "usersession.id" in session:
|
||||
_logout(current_user)
|
||||
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
user = octoprint.server.userManager.find_user(username)
|
||||
if user is not None:
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager.check_password(username, password):
|
||||
if not user.is_active:
|
||||
return make_response(("Your account is deactivated", 403, []))
|
||||
|
||||
@@ -217,16 +215,16 @@ def login():
|
||||
g.user = user
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
return jsonify(user)
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
|
||||
elif "passive" in data:
|
||||
return passive_login()
|
||||
return NO_CONTENT
|
||||
|
||||
return make_response("Neither user and pass attributes nor passive flag present", 400)
|
||||
|
||||
|
||||
@api.route("/logout", methods=["POST"])
|
||||
@restricted_access
|
||||
def logout():
|
||||
# logout from user manager...
|
||||
_logout(current_user)
|
||||
@@ -234,7 +232,7 @@ def logout():
|
||||
# ... and from flask login (and principal)
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
return jsonify(octoprint.access.users.AnonymousUser([octoprint.server.groupManager.guest_group]))
|
||||
|
||||
|
||||
def _logout(user):
|
||||
@@ -247,8 +245,8 @@ def _logout(user):
|
||||
|
||||
|
||||
@api.route("/util/test", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.ADMIN.require(403)
|
||||
def utilTestPath():
|
||||
valid_commands = dict(
|
||||
path=["path"],
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, abort, make_response
|
||||
from werkzeug.exceptions import BadRequest
|
||||
from flask_login import current_user
|
||||
|
||||
import octoprint.access.groups as groups
|
||||
import octoprint.access.users as users
|
||||
|
||||
from octoprint.server import SUCCESS, groupManager, userManager
|
||||
from octoprint.server.api import api, valid_boolean_trues
|
||||
from octoprint.server.util.flask import require_firstrun
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
#~~ permission api
|
||||
|
||||
@api.route("/access/permissions", methods=["GET"])
|
||||
def get_permissions():
|
||||
return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()])
|
||||
|
||||
#~~ group api
|
||||
|
||||
@api.route("/access/groups", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_groups():
|
||||
return jsonify(groups=map(lambda g: g.as_dict(), groupManager.groups))
|
||||
|
||||
|
||||
@api.route("/access/groups", methods=["POST"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_group():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "key" in data:
|
||||
return make_response("Missing mandatory key field", 400)
|
||||
if not "name" in data:
|
||||
return make_response("Missing mandatory name field", 400)
|
||||
if not "permissions" in data:
|
||||
return make_response("Missing mandatory permissions field", 400)
|
||||
|
||||
key = data["key"]
|
||||
name = data["name"]
|
||||
description = data.get("description", "")
|
||||
permissions = data["permissions"]
|
||||
default = data.get("default", False)
|
||||
|
||||
try:
|
||||
groupManager.add_group(key, name, description=description, permissions=permissions, default=default)
|
||||
except groups.GroupAlreadyExists:
|
||||
abort(409)
|
||||
return get_groups()
|
||||
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_group(key):
|
||||
group = groupManager.find_group(key)
|
||||
if group is not None:
|
||||
return jsonify(group)
|
||||
else:
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def update_group(key):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
try:
|
||||
kwargs = dict()
|
||||
|
||||
if "permissions" in data:
|
||||
kwargs["permissions"] = data["permissions"]
|
||||
|
||||
if "default" in data:
|
||||
kwargs["default"] = data["default"] in valid_boolean_trues
|
||||
|
||||
if "description" in data:
|
||||
kwargs["description"] = data["description"]
|
||||
|
||||
groupManager.update_group(key, **kwargs)
|
||||
|
||||
return get_groups()
|
||||
except groups.GroupCantBeChanged:
|
||||
abort(403)
|
||||
except groups.UnknownGroup:
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def remove_group(key):
|
||||
try:
|
||||
groupManager.remove_group(key)
|
||||
return get_groups()
|
||||
except groups.UnknownGroup:
|
||||
abort(404)
|
||||
except groups.GroupUnremovable:
|
||||
abort(403)
|
||||
|
||||
#~~ user api
|
||||
|
||||
@api.route("/access/users", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def get_users():
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
return jsonify(users=map(lambda u: u.as_dict(), userManager.get_all_users()))
|
||||
|
||||
|
||||
@api.route("/access/users", methods=["POST"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_user():
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "name" in data:
|
||||
return make_response("Missing mandatory name field", 400)
|
||||
if not "password" in data:
|
||||
return make_response("Missing mandatory password field", 400)
|
||||
if not "active" in data:
|
||||
return make_response("Missing mandatory active field", 400)
|
||||
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"] in valid_boolean_trues
|
||||
|
||||
groups = data.get("groups", None)
|
||||
permissions = data.get("permissions", None)
|
||||
|
||||
try:
|
||||
userManager.add_user(name, password, active, permissions, groups)
|
||||
except users.UserAlreadyExists:
|
||||
abort(409)
|
||||
return get_users()
|
||||
|
||||
|
||||
@api.route("/access/users/<username>", methods=["GET"])
|
||||
@require_firstrun
|
||||
def get_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)):
|
||||
user = userManager.find_user(username)
|
||||
if user is not None:
|
||||
return jsonify(user)
|
||||
else:
|
||||
abort(404)
|
||||
else:
|
||||
abort(403)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>", methods=["PUT"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def update_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
user = userManager.find_user(username)
|
||||
if user is not None:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
|
||||
# change groups
|
||||
if "groups" in data:
|
||||
groups = data["groups"]
|
||||
userManager.change_user_groups(username, groups)
|
||||
|
||||
# change permissions
|
||||
if "permissions" in data:
|
||||
permissions = data["permissions"]
|
||||
userManager.change_user_permissions(username, permissions)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
# change activation
|
||||
if "active" in data:
|
||||
userManager.change_user_activation(username, data["active"] in valid_boolean_trues)
|
||||
|
||||
return get_users()
|
||||
else:
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def remove_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
try:
|
||||
userManager.remove_user(username)
|
||||
return get_users()
|
||||
except users.UnknownUser:
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/password", methods=["PUT"])
|
||||
@require_firstrun
|
||||
def change_password_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "password" in data or not data["password"]:
|
||||
return make_response("password is missing from request", 400)
|
||||
|
||||
try:
|
||||
userManager.change_user_password(username, data["password"])
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/settings", methods=["GET"])
|
||||
@require_firstrun
|
||||
def get_settings_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN)):
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
try:
|
||||
return jsonify(userManager.get_all_user_settings(username))
|
||||
except users.UnknownUser:
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
|
||||
@api.route("/access/users/<username>/settings", methods=["PATCH"])
|
||||
@require_firstrun
|
||||
def change_settings_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN)):
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
try:
|
||||
userManager.change_user_settings(username, data)
|
||||
return jsonify(SUCCESS)
|
||||
except users.UnknownUser:
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
|
||||
@api.route("/access/users/<username>/apikey", methods=["DELETE"])
|
||||
@require_firstrun
|
||||
def delete_apikey_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)):
|
||||
try:
|
||||
userManager.delete_api_key(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/apikey", methods=["POST"])
|
||||
@require_firstrun
|
||||
def generate_apikey_for_user(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)):
|
||||
try:
|
||||
apikey = userManager.generate_api_key(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify({"apikey": apikey})
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
def _to_external_permissions(*permissions):
|
||||
return map(lambda p: p.get_name(), permissions)
|
||||
|
||||
def _to_external_groups(*groups):
|
||||
return map(lambda g: g.get_name(), groups)
|
||||
@@ -10,10 +10,11 @@ from flask import request, jsonify, make_response
|
||||
from octoprint.settings import settings
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@api.route("/connection", methods=["GET"])
|
||||
@Permissions.STATUS.require(403)
|
||||
def connectionState():
|
||||
state, port, baudrate, printer_profile = printer.get_current_connection()
|
||||
current = {
|
||||
@@ -27,7 +28,8 @@ def connectionState():
|
||||
|
||||
|
||||
@api.route("/connection", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
"connect": [],
|
||||
|
||||
+220
-205
@@ -10,9 +10,11 @@ from flask import request, jsonify, make_response, url_for
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT, current_user
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.api import api
|
||||
from octoprint.events import Events
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
import octoprint.filemanager
|
||||
import octoprint.filemanager.util
|
||||
import octoprint.filemanager.storage
|
||||
@@ -87,6 +89,7 @@ def _create_etag(path, filter, recursive, lm=None):
|
||||
|
||||
|
||||
@api.route("/files", methods=["GET"])
|
||||
@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),
|
||||
@@ -107,6 +110,7 @@ def readGcodeFiles():
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@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),
|
||||
@@ -255,7 +259,8 @@ def _isBusy(target, path):
|
||||
return any(target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files())
|
||||
|
||||
@api.route("/files/<string:target>", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.FILES_UPLOAD.require(403)
|
||||
def uploadGcodeFile(target):
|
||||
input_name = "file"
|
||||
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
|
||||
@@ -279,8 +284,8 @@ 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
|
||||
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
|
||||
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:
|
||||
# validate that all preconditions for SD upload are met before attempting it
|
||||
@@ -453,6 +458,7 @@ def uploadGcodeFile(target):
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["GET"])
|
||||
@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)
|
||||
@@ -469,7 +475,7 @@ def readGcodeFile(target, filename):
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
def gcodeFileCommand(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
@@ -490,245 +496,254 @@ def gcodeFileCommand(filename, target):
|
||||
user = current_user.get_name()
|
||||
|
||||
if command == "select":
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
with Permissions.FILES_SELECT.require(403):
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
# selects/loads a file
|
||||
if not octoprint.filemanager.valid_file_type(filename, type="machinecode"):
|
||||
return make_response("Cannot select {filename} for printing, not a machinecode file".format(**locals()), 415)
|
||||
# selects/loads a file
|
||||
if not octoprint.filemanager.valid_file_type(filename, type="machinecode"):
|
||||
return make_response("Cannot select {filename} for printing, not a machinecode file".format(**locals()), 415)
|
||||
|
||||
printAfterLoading = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
printAfterLoading = True
|
||||
printAfterLoading = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
with Permissions.PRINT.require(403):
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
printAfterLoading = True
|
||||
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = filename
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.path_on_disk(target, filename)
|
||||
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = filename
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.path_on_disk(target, filename)
|
||||
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
|
||||
|
||||
elif command == "slice":
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
with Permissions.SLICE.require(403):
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
try:
|
||||
if "slicer" in data:
|
||||
slicer = data["slicer"]
|
||||
del data["slicer"]
|
||||
slicer_instance = slicingManager.get_slicer(slicer)
|
||||
try:
|
||||
if "slicer" in data:
|
||||
slicer = data["slicer"]
|
||||
del data["slicer"]
|
||||
slicer_instance = slicingManager.get_slicer(slicer)
|
||||
|
||||
elif "cura" in slicingManager.registered_slicers:
|
||||
slicer = "cura"
|
||||
slicer_instance = slicingManager.get_slicer("cura")
|
||||
elif "cura" in slicingManager.registered_slicers:
|
||||
slicer = "cura"
|
||||
slicer_instance = slicingManager.get_slicer("cura")
|
||||
|
||||
else:
|
||||
return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415)
|
||||
except octoprint.slicing.UnknownSlicer as e:
|
||||
return make_response("Slicer {slicer} is not available".format(slicer=e.slicer), 400)
|
||||
|
||||
if not any([octoprint.filemanager.valid_file_type(filename, type=source_file_type) for source_file_type in slicer_instance.get_slicer_properties().get("source_file_types", ["model"])]):
|
||||
return make_response("Cannot slice {filename}, not a model file".format(**locals()), 415)
|
||||
|
||||
if slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()):
|
||||
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
|
||||
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
|
||||
|
||||
if "destination" in data and data["destination"]:
|
||||
destination = data["destination"]
|
||||
del data["destination"]
|
||||
elif "gcode" in data and data["gcode"]:
|
||||
destination = data["gcode"]
|
||||
del data["gcode"]
|
||||
else:
|
||||
import os
|
||||
name, _ = os.path.splitext(filename)
|
||||
destination = name + "." + slicer_instance.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])[0]
|
||||
|
||||
full_path = destination
|
||||
if "path" in data and data["path"]:
|
||||
full_path = fileManager.join_path(target, data["path"], destination)
|
||||
else:
|
||||
path, _ = fileManager.split_path(target, filename)
|
||||
if path:
|
||||
full_path = fileManager.join_path(target, path, destination)
|
||||
|
||||
canon_path, canon_name = fileManager.canonicalize(target, full_path)
|
||||
sanitized_name = fileManager.sanitize_name(target, canon_name)
|
||||
|
||||
if canon_path:
|
||||
full_path = fileManager.join_path(target, canon_path, sanitized_name)
|
||||
else:
|
||||
full_path = sanitized_name
|
||||
|
||||
# prohibit overwriting the file that is currently being printed
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
make_response("Trying to slice into file that is currently being printed: %s" % full_path, 409)
|
||||
|
||||
if "profile" in data.keys() and data["profile"]:
|
||||
profile = data["profile"]
|
||||
del data["profile"]
|
||||
else:
|
||||
profile = None
|
||||
|
||||
if "printerProfile" in data.keys() and data["printerProfile"]:
|
||||
printerProfile = data["printerProfile"]
|
||||
del data["printerProfile"]
|
||||
else:
|
||||
printerProfile = None
|
||||
|
||||
if "position" in data.keys() and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]:
|
||||
position = data["position"]
|
||||
del data["position"]
|
||||
else:
|
||||
position = None
|
||||
|
||||
select_after_slicing = False
|
||||
if "select" in data.keys() and data["select"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly select for printing", 409)
|
||||
select_after_slicing = True
|
||||
|
||||
print_after_slicing = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
|
||||
overrides = dict()
|
||||
for key in override_keys:
|
||||
overrides[key[len("profile."):]] = data[key]
|
||||
|
||||
def slicing_done(target, path, select_after_slicing, print_after_slicing):
|
||||
if select_after_slicing or print_after_slicing:
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = path
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.path_on_disk(target, path)
|
||||
printer.select_file(filenameToSelect, sd, print_after_slicing, user)
|
||||
return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415)
|
||||
except octoprint.slicing.UnknownSlicer as e:
|
||||
return make_response("Slicer {slicer} is not available".format(slicer=e.slicer), 400)
|
||||
|
||||
try:
|
||||
fileManager.slice(slicer, target, filename, target, full_path,
|
||||
profile=profile,
|
||||
printer_profile_id=printerProfile,
|
||||
position=position,
|
||||
overrides=overrides,
|
||||
display=canon_name,
|
||||
callback=slicing_done,
|
||||
callback_args=(target, full_path, select_after_slicing, print_after_slicing))
|
||||
except octoprint.slicing.UnknownProfile:
|
||||
return make_response("Profile {profile} doesn't exist".format(**locals()), 400)
|
||||
if not any([octoprint.filemanager.valid_file_type(filename, type=source_file_type) for source_file_type in slicer_instance.get_slicer_properties().get("source_file_types", ["model"])]):
|
||||
return make_response("Cannot slice {filename}, not a model file".format(**locals()), 415)
|
||||
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=target, filename=full_path, _external=True)
|
||||
result = {
|
||||
"name": sanitized_name,
|
||||
"path": full_path,
|
||||
"display": canon_name,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + full_path
|
||||
if slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()):
|
||||
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
|
||||
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
|
||||
|
||||
if "destination" in data and data["destination"]:
|
||||
destination = data["destination"]
|
||||
del data["destination"]
|
||||
elif "gcode" in data and data["gcode"]:
|
||||
destination = data["gcode"]
|
||||
del data["gcode"]
|
||||
else:
|
||||
import os
|
||||
name, _ = os.path.splitext(filename)
|
||||
destination = name + "." + slicer_instance.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])[0]
|
||||
|
||||
full_path = destination
|
||||
if "path" in data and data["path"]:
|
||||
full_path = fileManager.join_path(target, data["path"], destination)
|
||||
else:
|
||||
path, _ = fileManager.split_path(target, filename)
|
||||
if path:
|
||||
full_path = fileManager.join_path(target, path, destination)
|
||||
|
||||
canon_path, canon_name = fileManager.canonicalize(target, full_path)
|
||||
sanitized_name = fileManager.sanitize_name(target, canon_name)
|
||||
|
||||
if canon_path:
|
||||
full_path = fileManager.join_path(target, canon_path, sanitized_name)
|
||||
else:
|
||||
full_path = sanitized_name
|
||||
|
||||
# prohibit overwriting the file that is currently being printed
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
make_response("Trying to slice into file that is currently being printed: %s" % full_path, 409)
|
||||
|
||||
if "profile" in data.keys() and data["profile"]:
|
||||
profile = data["profile"]
|
||||
del data["profile"]
|
||||
else:
|
||||
profile = None
|
||||
|
||||
if "printerProfile" in data.keys() and data["printerProfile"]:
|
||||
printerProfile = data["printerProfile"]
|
||||
del data["printerProfile"]
|
||||
else:
|
||||
printerProfile = None
|
||||
|
||||
if "position" in data.keys() and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]:
|
||||
position = data["position"]
|
||||
del data["position"]
|
||||
else:
|
||||
position = None
|
||||
|
||||
select_after_slicing = False
|
||||
if "select" in data.keys() and data["select"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly select for printing", 409)
|
||||
select_after_slicing = True
|
||||
|
||||
print_after_slicing = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
|
||||
overrides = dict()
|
||||
for key in override_keys:
|
||||
overrides[key[len("profile."):]] = data[key]
|
||||
|
||||
def slicing_done(target, path, select_after_slicing, print_after_slicing):
|
||||
if select_after_slicing or print_after_slicing:
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = path
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.path_on_disk(target, path)
|
||||
printer.select_file(filenameToSelect, sd, print_after_slicing, user)
|
||||
|
||||
try:
|
||||
fileManager.slice(slicer, target, filename, target, full_path,
|
||||
profile=profile,
|
||||
printer_profile_id=printerProfile,
|
||||
position=position,
|
||||
overrides=overrides,
|
||||
display=canon_name,
|
||||
callback=slicing_done,
|
||||
callback_args=(target, full_path, select_after_slicing, print_after_slicing))
|
||||
except octoprint.slicing.UnknownProfile:
|
||||
return make_response("Profile {profile} doesn't exist".format(**locals()), 400)
|
||||
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=target, filename=full_path, _external=True)
|
||||
result = {
|
||||
"name": destination,
|
||||
"path": full_path,
|
||||
"display": canon_name,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + full_path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r = make_response(jsonify(result), 202)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
r = make_response(jsonify(result), 202)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
elif command == "analyse":
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
with Permissions.FILES_UPLOAD.require(403):
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
printer_profile = None
|
||||
if "printerProfile" in data and data["printerProfile"]:
|
||||
printer_profile = data["printerProfile"]
|
||||
printer_profile = None
|
||||
if "printerProfile" in data and data["printerProfile"]:
|
||||
printer_profile = data["printerProfile"]
|
||||
|
||||
if not fileManager.analyse(target, filename, printer_profile_id=printer_profile):
|
||||
return make_response("No analysis possible for {} on {}".format(filename, target), 400)
|
||||
if not fileManager.analyse(target, filename, printer_profile_id=printer_profile):
|
||||
return make_response("No analysis possible for {} on {}".format(filename, target), 400)
|
||||
|
||||
elif command == "copy" or command == "move":
|
||||
# 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)
|
||||
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)
|
||||
|
||||
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
|
||||
return make_response("File or folder not found on {}: {}".format(target, filename), 404)
|
||||
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
|
||||
return make_response("File or folder not found on {}: {}".format(target, filename), 404)
|
||||
|
||||
path, name = fileManager.split_path(target, filename)
|
||||
path, name = fileManager.split_path(target, filename)
|
||||
|
||||
destination = data["destination"]
|
||||
dst_path, dst_name = fileManager.split_path(target, destination)
|
||||
sanitized_destination = fileManager.join_path(target, dst_path, fileManager.sanitize_name(target, dst_name))
|
||||
destination = data["destination"]
|
||||
dst_path, dst_name = fileManager.split_path(target, destination)
|
||||
sanitized_destination = fileManager.join_path(target, dst_path, fileManager.sanitize_name(target, dst_name))
|
||||
|
||||
if _verifyFolderExists(target, destination) and sanitized_destination != filename:
|
||||
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
|
||||
# to move filename to this folder under the same name
|
||||
destination = fileManager.join_path(target, destination, name)
|
||||
if _verifyFolderExists(target, destination) and sanitized_destination != filename:
|
||||
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
|
||||
# to move filename to this folder under the same name
|
||||
destination = fileManager.join_path(target, destination, name)
|
||||
|
||||
is_file = fileManager.file_exists(target, filename)
|
||||
is_folder = fileManager.folder_exists(target, filename)
|
||||
|
||||
if not (is_file or is_folder):
|
||||
return make_response("{} on {} is neither file or folder, can't {}".format(filename, target, command), 400)
|
||||
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
|
||||
if is_file:
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
is_file = fileManager.file_exists(target, filename)
|
||||
is_folder = fileManager.folder_exists(target, filename)
|
||||
|
||||
elif command == "move":
|
||||
if _isBusy(target, filename):
|
||||
return make_response("Trying to move a file or folder that is currently in use: {}".format(filename), 409)
|
||||
if not (is_file or is_folder):
|
||||
return make_response("{} on {} is neither file or folder, can't {}".format(filename, target, command), 400)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (_verifyFileExists(target, destination) or _verifyFolderExists(target, destination)) \
|
||||
and sanitized_destination != filename:
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselect_file()
|
||||
if is_file:
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
|
||||
if is_file:
|
||||
fileManager.move_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
elif command == "move":
|
||||
if _isBusy(target, filename):
|
||||
return make_response("Trying to move a file or folder that is currently in use: {}".format(filename), 409)
|
||||
|
||||
location = url_for(".readGcodeFile", target=target, filename=destination, _external=True)
|
||||
result = {
|
||||
"name": name,
|
||||
"path": destination,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (_verifyFileExists(target, destination) or _verifyFolderExists(target, destination)) \
|
||||
and sanitized_destination != filename:
|
||||
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselect_file()
|
||||
|
||||
if is_file:
|
||||
fileManager.move_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
|
||||
location = url_for(".readGcodeFile", target=target, filename=destination, _external=True)
|
||||
result = {
|
||||
"name": name,
|
||||
"path": destination,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_file:
|
||||
result["refs"]["download"] = url_for("index", _external=True) + "downloads/files/" + target + "/" + destination
|
||||
if is_file:
|
||||
result["refs"]["download"] = url_for("index", _external=True) + "downloads/files/" + target + "/" + destination
|
||||
|
||||
r = make_response(jsonify(result), 201)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
r = make_response(jsonify(result), 201)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.FILES_DELETE.require(403)
|
||||
def deleteGcodeFile(filename, target):
|
||||
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
|
||||
return make_response("File/Folder not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
@@ -8,13 +8,13 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask import request, make_response, jsonify
|
||||
|
||||
from octoprint.server import printer, NO_CONTENT, current_user
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@api.route("/job", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.PRINT.require(403)
|
||||
def controlJob():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -36,27 +36,31 @@ def controlJob():
|
||||
|
||||
user = current_user.get_name()
|
||||
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.start_print(tags=tags, user=user)
|
||||
elif command == "restart":
|
||||
if not printer.is_paused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.start_print(tags=tags, user=user)
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
|
||||
action = data.get("action", "toggle")
|
||||
if action == "toggle":
|
||||
printer.toggle_pause_print(tags=tags)
|
||||
elif action == "pause":
|
||||
printer.pause_print(tags=tags)
|
||||
elif action == "resume":
|
||||
printer.resume_print(tags=tags)
|
||||
else:
|
||||
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
|
||||
elif command == "cancel":
|
||||
with Permissions.PRINT.require(403):
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.start_print(tags=tags, user=user)
|
||||
elif command == "restart":
|
||||
if not printer.is_paused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.start_print(tags=tags, user=user)
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
|
||||
action = data.get("action", "toggle")
|
||||
if action == "toggle":
|
||||
printer.toggle_pause_print(tags=tags)
|
||||
elif action == "pause":
|
||||
printer.pause_print(tags=tags)
|
||||
elif action == "resume":
|
||||
printer.resume_print(tags=tags)
|
||||
else:
|
||||
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
|
||||
|
||||
# Safety first, everyone can cancel a print, but log who canceled the print
|
||||
# to prevent fraudulent use
|
||||
if command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
|
||||
printer.cancel_print(tags=tags)
|
||||
@@ -64,6 +68,7 @@ def controlJob():
|
||||
|
||||
|
||||
@api.route("/job", methods=["GET"])
|
||||
@Permissions.STATUS.require(403)
|
||||
def jobState():
|
||||
currentData = printer.get_current_data()
|
||||
return jsonify({
|
||||
|
||||
@@ -20,17 +20,17 @@ from flask import request, jsonify, make_response
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import require_firstrun
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
from flask_babel import Locale
|
||||
|
||||
@api.route("/languages", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def getInstalledLanguagePacks():
|
||||
translation_folder = settings().getBaseFolder("translations")
|
||||
if not os.path.exists(translation_folder):
|
||||
@@ -87,8 +87,8 @@ def getInstalledLanguagePacks():
|
||||
return jsonify(language_packs=result)
|
||||
|
||||
@api.route("/languages", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def uploadLanguagePack():
|
||||
input_name = "file"
|
||||
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
|
||||
@@ -115,8 +115,8 @@ def uploadLanguagePack():
|
||||
return getInstalledLanguagePacks()
|
||||
|
||||
@api.route("/languages/<string:locale>/<string:pack>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def deleteInstalledLanguagePack(locale, pack):
|
||||
|
||||
if pack == "_core":
|
||||
|
||||
@@ -12,14 +12,17 @@ import re
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
|
||||
|
||||
from octoprint.printer import UnknownScript
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
#~~ Printer
|
||||
|
||||
|
||||
@api.route("/printer", methods=["GET"])
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -57,7 +60,8 @@ def printerState():
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerToolCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -146,6 +150,8 @@ def printerToolCommand():
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerToolState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -157,7 +163,8 @@ def printerToolState():
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerBedCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -203,6 +210,8 @@ def printerBedCommand():
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerBedState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -221,7 +230,8 @@ def printerBedState():
|
||||
|
||||
|
||||
@api.route("/printer/printhead", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerPrintheadCommand():
|
||||
valid_commands = {
|
||||
"jog": [],
|
||||
@@ -284,7 +294,8 @@ def printerPrintheadCommand():
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerSdCommand():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
@@ -314,6 +325,8 @@ def printerSdCommand():
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
@@ -325,7 +338,8 @@ def printerSdState():
|
||||
|
||||
|
||||
@api.route("/printer/command", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
@@ -385,6 +399,8 @@ def printerCommand():
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printer/command/custom", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.CONTROL.require(403)
|
||||
def getCustomControls():
|
||||
# TODO: document me
|
||||
customControls = settings().get(["controls"])
|
||||
|
||||
@@ -14,16 +14,16 @@ from werkzeug.exceptions import BadRequest
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
from octoprint.server import printerProfileManager
|
||||
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError, SaveError
|
||||
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
def _lastmodified():
|
||||
return printerProfileManager.last_modified
|
||||
|
||||
|
||||
def _etag(lm=None):
|
||||
if lm is None:
|
||||
lm = _lastmodified()
|
||||
@@ -40,12 +40,15 @@ def _etag(lm=None):
|
||||
@with_revalidation_checking(etag_factory=_etag,
|
||||
lastmodified_factory=_lastmodified,
|
||||
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
|
||||
@require_firstrun
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def printerProfilesList():
|
||||
all_profiles = printerProfileManager.get_all()
|
||||
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
|
||||
|
||||
@api.route("/printerprofiles", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesAdd():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
@@ -99,6 +102,8 @@ def printerProfilesAdd():
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@Permissions.CONNECTION.require(403)
|
||||
def printerProfilesGet(identifier):
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
@@ -107,7 +112,8 @@ def printerProfilesGet(identifier):
|
||||
return jsonify(_convert_profile(profile))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesDelete(identifier):
|
||||
current_profile = printerProfileManager.get_current()
|
||||
if current_profile and current_profile["id"] == identifier:
|
||||
@@ -121,7 +127,8 @@ def printerProfilesDelete(identifier):
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesUpdate(identifier):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
@@ -16,7 +16,8 @@ from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import admin_permission, printer
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
|
||||
from octoprint.server.util.flask import require_firstrun, with_revalidation_checking
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
@@ -40,7 +41,7 @@ def _etag(lm=None):
|
||||
sorted_plugin_settings[key] = plugin_settings.get(key, dict())
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous:
|
||||
roles = sorted(current_user.roles)
|
||||
roles = sorted(current_user.permissions)
|
||||
else:
|
||||
roles = []
|
||||
|
||||
@@ -83,7 +84,8 @@ def getSettings():
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"]) if admin_permission.can() else None,
|
||||
"keyEnforced": s.getBoolean(["api", "keyEnforced"]),
|
||||
"key": s.get(["api", "key"]) if Permissions.ADMIN.can() else None,
|
||||
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
|
||||
},
|
||||
"appearance": {
|
||||
@@ -275,8 +277,8 @@ def _get_plugin_settings():
|
||||
|
||||
|
||||
@api.route("/settings", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def setSettings():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
@@ -298,16 +300,16 @@ def setSettings():
|
||||
|
||||
|
||||
@api.route("/settings/apikey", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def generateApiKey():
|
||||
apikey = settings().generateApiKey()
|
||||
return jsonify(apikey=apikey)
|
||||
|
||||
|
||||
@api.route("/settings/apikey", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def deleteApiKey():
|
||||
settings().deleteApiKey()
|
||||
return NO_CONTENT
|
||||
@@ -323,6 +325,7 @@ def _saveSettings(data):
|
||||
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "keyEnforced" in data["api"]: s.setBoolean(["api", "keyEnforced"], data["api"]["keyEnforced"])
|
||||
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
|
||||
if "appearance" in data.keys():
|
||||
|
||||
@@ -9,12 +9,13 @@ from flask import request, jsonify, make_response, url_for
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
|
||||
from octoprint.server.util.flask import require_firstrun, 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
|
||||
|
||||
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile, CouldNotDeleteProfile
|
||||
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, UnknownProfile, CouldNotDeleteProfile
|
||||
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
@@ -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"])
|
||||
@require_firstrun
|
||||
@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"])
|
||||
@require_firstrun
|
||||
@Permissions.SLICE.require(403)
|
||||
def slicingGetSlicerProfile(slicer, name):
|
||||
try:
|
||||
profile = slicingManager.load_profile(slicer, name, require_configured=False)
|
||||
@@ -125,7 +131,8 @@ def slicingGetSlicerProfile(slicer, name):
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@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)
|
||||
@@ -160,7 +167,8 @@ def slicingAddSlicerProfile(slicer, name):
|
||||
return r
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@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)
|
||||
@@ -203,7 +211,8 @@ def slicingPatchSlicerProfile(slicer, name):
|
||||
return jsonify(_getSlicingProfileData(slicer, name, saved_profile))
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def slicingDelSlicerProfile(slicer, name):
|
||||
try:
|
||||
slicingManager.delete_profile(slicer, name)
|
||||
|
||||
@@ -14,15 +14,15 @@ from flask_babel import gettext
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_remote_address
|
||||
from octoprint.server.util.flask import require_firstrun, get_remote_address
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.logging import prefix_multilines
|
||||
|
||||
|
||||
@api.route("/system", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def performSystemAction():
|
||||
logging.getLogger(__name__).warn("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/<action>".format(get_remote_address(request)))
|
||||
|
||||
@@ -37,16 +37,16 @@ def performSystemAction():
|
||||
|
||||
|
||||
@api.route("/system/commands", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def retrieveSystemCommands():
|
||||
return jsonify(core=_to_client_specs(_get_core_command_specs()),
|
||||
custom=_to_client_specs(_get_custom_command_specs()))
|
||||
|
||||
|
||||
@api.route("/system/commands/<string:source>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def retrieveSystemCommandsForSource(source):
|
||||
if source == "core":
|
||||
specs = _get_core_command_specs()
|
||||
@@ -59,8 +59,8 @@ def retrieveSystemCommandsForSource(source):
|
||||
|
||||
|
||||
@api.route("/system/commands/<string:source>/<string:command>", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@require_firstrun
|
||||
@Permissions.SYSTEM.require(403)
|
||||
def executeSystemCommand(source, command):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -10,17 +10,17 @@ import threading
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
import octoprint.timelapse
|
||||
import octoprint.util as util
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import admin_permission, printer
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.util.flask import redirect_to_tornado, require_firstrun, get_json_command_from_request, with_revalidation_checking
|
||||
from octoprint.server.api import api
|
||||
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
@@ -76,6 +76,8 @@ def _etag(unrendered, lm=None):
|
||||
@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)
|
||||
@require_firstrun
|
||||
@Permissions.TIMELAPSE_LIST.require(403)
|
||||
def getTimelapseData():
|
||||
timelapse = octoprint.timelapse.current
|
||||
config = _config_for_timelapse(timelapse)
|
||||
@@ -120,12 +122,15 @@ def getTimelapseData():
|
||||
|
||||
|
||||
@api.route("/timelapse/<filename>", methods=["GET"])
|
||||
@require_firstrun
|
||||
@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
|
||||
@require_firstrun
|
||||
@Permissions.TIMELAPSE_DELETE.require(403)
|
||||
def deleteTimelapse(filename):
|
||||
if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4", "m4v", "mkv"]):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
@@ -141,14 +146,16 @@ def deleteTimelapse(filename):
|
||||
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.TIMELAPSE_DELETE.require(403)
|
||||
def deleteUnrenderedTimelapse(name):
|
||||
octoprint.timelapse.delete_unrendered_timelapse(name)
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.TIMELAPSE_ADMIN.require(403)
|
||||
def processUnrenderedTimelapseCommand(name):
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
@@ -168,7 +175,8 @@ def processUnrenderedTimelapseCommand(name):
|
||||
|
||||
|
||||
@api.route("/timelapse", methods=["POST"])
|
||||
@restricted_access
|
||||
@require_firstrun
|
||||
@Permissions.TIMELAPSE_ADMIN.require(403)
|
||||
def setTimelapseConfig():
|
||||
data = request.get_json(silent=True)
|
||||
if data is None:
|
||||
|
||||
@@ -1,233 +1,61 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__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 flask import request, jsonify, abort, make_response
|
||||
from werkzeug.exceptions import BadRequest
|
||||
from flask_login import current_user
|
||||
|
||||
import octoprint.users as users
|
||||
|
||||
from octoprint.server import SUCCESS, admin_permission, userManager
|
||||
from octoprint.server.api import api, valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
|
||||
#~~ user settings
|
||||
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"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getUsers():
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
return jsonify({"users": userManager.getAllUsers()})
|
||||
def deprecated_get_users():
|
||||
return redirect(url_for("api.get_users"), code=307)
|
||||
|
||||
|
||||
@api.route("/users", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def addUser():
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "name" in data:
|
||||
return make_response("Missing mandatory name field", 400)
|
||||
if not "password" in data:
|
||||
return make_response("Missing mandatory password field", 400)
|
||||
if not "active" in data:
|
||||
return make_response("Missing mandatory active field", 400)
|
||||
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"] in valid_boolean_trues
|
||||
|
||||
roles = ["user"]
|
||||
if "admin" in data and data["admin"] in valid_boolean_trues:
|
||||
roles.append("admin")
|
||||
|
||||
try:
|
||||
userManager.addUser(name, password, active, roles)
|
||||
except users.UserAlreadyExists:
|
||||
abort(409)
|
||||
return getUsers()
|
||||
return redirect(url_for("api.add_user"), code=307)
|
||||
|
||||
|
||||
@api.route("/users/<username>", methods=["GET"])
|
||||
@restricted_access
|
||||
def getUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
return jsonify(user.asDict())
|
||||
else:
|
||||
abort(404)
|
||||
else:
|
||||
abort(403)
|
||||
return redirect(url_for("api.get_user", username=username), code=307)
|
||||
|
||||
|
||||
@api.route("/users/<username>", methods=["PUT"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def updateUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
# change roles
|
||||
roles = ["user"]
|
||||
if "admin" in data and data["admin"] in valid_boolean_trues:
|
||||
roles.append("admin")
|
||||
userManager.changeUserRoles(username, roles)
|
||||
|
||||
# change activation
|
||||
if "active" in data:
|
||||
userManager.changeUserActivation(username, data["active"] in valid_boolean_trues)
|
||||
return getUsers()
|
||||
else:
|
||||
abort(404)
|
||||
return redirect(url_for("api.update_user", username=username), code=307)
|
||||
|
||||
|
||||
@api.route("/users/<username>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(http_exception=403)
|
||||
def removeUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
try:
|
||||
userManager.removeUser(username)
|
||||
return getUsers()
|
||||
except users.UnknownUser:
|
||||
abort(404)
|
||||
return redirect(url_for("api.remove_user", username=username), code=307)
|
||||
|
||||
|
||||
@api.route("/users/<username>/password", methods=["PUT"])
|
||||
@restricted_access
|
||||
def changePasswordForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "password" in data or not data["password"]:
|
||||
return make_response("password is missing from request", 400)
|
||||
|
||||
try:
|
||||
userManager.changeUserPassword(username, data["password"])
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
return redirect(url_for("api.change_password_for_user", username=username), code=307)
|
||||
|
||||
|
||||
@api.route("/users/<username>/settings", methods=["GET"])
|
||||
@restricted_access
|
||||
def getSettingsForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
return redirect(url_for("api.get_settings_for_user", username=username), code=307)
|
||||
|
||||
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.is_admin):
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
try:
|
||||
return jsonify(userManager.getAllUserSettings(username))
|
||||
except users.UnknownUser:
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
|
||||
@api.route("/users/<username>/settings", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def changeSettingsForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
return redirect(url_for("api.change_settings_for_user", username=username), code=307)
|
||||
|
||||
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.is_admin):
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
try:
|
||||
userManager.changeUserSettings(username, data)
|
||||
return jsonify(SUCCESS)
|
||||
except users.UnknownUser:
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
|
||||
@api.route("/users/<username>/apikey", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteApikeyForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
try:
|
||||
userManager.deleteApikey(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
return redirect(url_for("api.delete_apikey_for_user", username=username), code=307)
|
||||
|
||||
|
||||
@api.route("/users/<username>/apikey", methods=["POST"])
|
||||
@restricted_access
|
||||
def generateApikeyForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
try:
|
||||
apikey = userManager.generateApiKey(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify({"apikey": apikey})
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
return redirect(url_for("api.generate_apikey_for_user", username=username), code=307)
|
||||
@@ -10,7 +10,7 @@ import base64
|
||||
from octoprint.settings import settings
|
||||
import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.users import ApiUser
|
||||
from octoprint.access.users import ApiUser
|
||||
|
||||
from octoprint.util import deprecated
|
||||
from octoprint.plugin import plugin_manager
|
||||
@@ -28,7 +28,7 @@ from . import watchdog
|
||||
|
||||
def enforceApiKeyRequestHandler():
|
||||
"""
|
||||
``before_request`` handler for blueprints which makes sure an API key is provided
|
||||
``before_request`` handler for blueprints which makes sure an API key is provided if configured as such
|
||||
"""
|
||||
|
||||
import octoprint.server
|
||||
@@ -43,7 +43,7 @@ def enforceApiKeyRequestHandler():
|
||||
|
||||
apikey = get_api_key(_flask.request)
|
||||
|
||||
if apikey is None:
|
||||
if apikey is None and settings().getBoolean(["api", "keyEnforced"]):
|
||||
return _flask.make_response("No API key provided", 403)
|
||||
|
||||
if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]):
|
||||
@@ -99,7 +99,7 @@ def loginUser(user, remember=False):
|
||||
Returns: (bool) True if the login succeeded, False otherwise
|
||||
|
||||
"""
|
||||
if user is not None and user.is_active() and flask_login.login_user(user, remember=remember):
|
||||
if user is not None and user.is_active and flask_login.login_user(user, remember=remember):
|
||||
flask_principal.identity_changed.send(_flask.current_app._get_current_object(),
|
||||
identity=flask_principal.Identity(user.get_id()))
|
||||
return True
|
||||
@@ -181,12 +181,17 @@ def optionsAllowOrigin(request):
|
||||
|
||||
def get_user_for_apikey(apikey):
|
||||
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
|
||||
if apikey == octoprint.server.UI_API_KEY:
|
||||
import flask_login
|
||||
if octoprint.server.userManager.enabled:
|
||||
return octoprint.server.userManager.find_user(session=flask_login.current_user.session)
|
||||
else:
|
||||
return flask_login.current_user
|
||||
elif apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
|
||||
# master key or an app session key was used
|
||||
return ApiUser()
|
||||
|
||||
return ApiUser([octoprint.server.groupManager.admin_group])
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.findUser(apikey=apikey)
|
||||
user = octoprint.server.userManager.find_user(apikey=apikey)
|
||||
if user is not None:
|
||||
# user key was used
|
||||
return user
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
from flask import make_response
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -15,7 +16,6 @@ import flask_assets
|
||||
import webassets.updater
|
||||
import webassets.utils
|
||||
import functools
|
||||
import contextlib
|
||||
import time
|
||||
import uuid
|
||||
import threading
|
||||
@@ -25,13 +25,15 @@ import os
|
||||
import collections
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import deprecated
|
||||
import octoprint.server
|
||||
import octoprint.users
|
||||
import octoprint.access.users
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.util import DefaultOrderedDict
|
||||
from octoprint.util.json import JsonEncoding
|
||||
|
||||
from werkzeug.local import LocalProxy
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
|
||||
from past.builtins import basestring
|
||||
@@ -509,18 +511,28 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
|
||||
#~~ passive login helper
|
||||
|
||||
def passive_login():
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.login_user(flask_login.current_user)
|
||||
else:
|
||||
user = flask_login.current_user
|
||||
user = flask_login.current_user
|
||||
|
||||
if user is not None and not user.is_anonymous and user.is_active:
|
||||
if isinstance(user, LocalProxy):
|
||||
# noinspection PyProtectedMember
|
||||
user = user._get_current_object()
|
||||
|
||||
def login(u):
|
||||
# login known user
|
||||
if not u.is_anonymous:
|
||||
u = octoprint.server.userManager.login_user(u)
|
||||
flask_login.login_user(u)
|
||||
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
|
||||
identity=flask_principal.Identity(user.get_id()))
|
||||
if hasattr(user, "session"):
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
return flask.jsonify(user.asDict())
|
||||
identity=flask_principal.Identity(u.get_id()))
|
||||
if hasattr(u, "session"):
|
||||
flask.session["usersession.id"] = u.session
|
||||
flask.g.user = u
|
||||
return u
|
||||
|
||||
if user is not None and user.is_active:
|
||||
# login known user
|
||||
user = login(user)
|
||||
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and settings().get(["accessControl", "autologinAs"]) is not None \
|
||||
and settings().get(["accessControl", "localNetworks"]) is not None:
|
||||
@@ -533,20 +545,15 @@ def passive_login():
|
||||
try:
|
||||
remoteAddr = get_remote_address(flask.request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None and user.is_active:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
flask_login.login_user(user)
|
||||
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
|
||||
identity=flask_principal.Identity(user.get_id()))
|
||||
return flask.jsonify(user.asDict())
|
||||
autologin_user = octoprint.server.userManager.find_user(autologinAs)
|
||||
if autologin_user is not None and user.is_active:
|
||||
autologin_user = octoprint.server.userManager.login_user(autologin_user)
|
||||
user = login(autologin_user)
|
||||
except:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
|
||||
return "", 204
|
||||
return flask.jsonify(user)
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
@@ -1045,36 +1052,29 @@ def add_no_max_age_response_headers(response):
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
def permission_validator(request, permission):
|
||||
"""
|
||||
Validates that the given request is made by an authorized user, identified either by API key or existing Flask
|
||||
session.
|
||||
|
||||
Must be executed in an existing Flask request context!
|
||||
|
||||
:param request: The Flask request object
|
||||
:param request: The required permission
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated or not user.has_permission(permission):
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
@deprecated("admin_validator is deprecated, please use new permission_validator", since="")
|
||||
def admin_validator(request):
|
||||
"""
|
||||
Validates that the given request is made by an admin user, identified either by API key or existing Flask
|
||||
session.
|
||||
|
||||
Must be executed in an existing Flask request context!
|
||||
|
||||
:param request: The Flask request object
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated or not user.is_admin:
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
return permission_validator(request, Permissions.ADMIN)
|
||||
|
||||
@deprecated("user_validator is deprecated, please use new permission_validator", since="")
|
||||
def user_validator(request):
|
||||
"""
|
||||
Validates that the given request is made by an authenticated user, identified either by API key or existing Flask
|
||||
session.
|
||||
|
||||
Must be executed in an existing Flask request context!
|
||||
|
||||
:param request: The Flask request object
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated:
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
return True
|
||||
|
||||
def _get_flask_user_from_request(request):
|
||||
"""
|
||||
@@ -1126,6 +1126,23 @@ def restricted_access(func):
|
||||
login_required decorator are met (possibly through a session already created
|
||||
by octoprint.server.util.apiKeyRequestHandler earlier in the request processing).
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||
"""
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
return require_firstrun(flask_login.login_required(func))(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
|
||||
|
||||
def require_firstrun(func):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control.
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
@@ -1134,10 +1151,11 @@ def restricted_access(func):
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
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 flask_login.login_required(func)(*args, **kwargs)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
|
||||
@@ -1151,7 +1169,7 @@ def firstrun_only_access(func):
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint has been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.has_been_customized()):
|
||||
return func(*args, **kwargs)
|
||||
else:
|
||||
return flask.make_response("OctoPrint is already setup, this resource is not longer available.", 403)
|
||||
@@ -1334,6 +1352,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
'js/app/bindings/toggle.js',
|
||||
'js/app/bindings/togglecontent.js',
|
||||
'js/app/bindings/valuewithinit.js',
|
||||
'js/app/viewmodels/access.js',
|
||||
'js/app/viewmodels/appearance.js',
|
||||
'js/app/viewmodels/connection.js',
|
||||
'js/app/viewmodels/control.js',
|
||||
@@ -1348,6 +1367,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
'js/app/viewmodels/temperature.js',
|
||||
'js/app/viewmodels/terminal.js',
|
||||
'js/app/viewmodels/timelapse.js',
|
||||
'js/app/viewmodels/uistate.js',
|
||||
'js/app/viewmodels/users.js',
|
||||
'js/app/viewmodels/usersettings.js',
|
||||
'js/app/viewmodels/wizard.js',
|
||||
|
||||
@@ -20,6 +20,8 @@ import octoprint.plugin
|
||||
|
||||
from octoprint.events import Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.access.users import LoginStatusListener
|
||||
from octoprint.util.json import JsonEncoding
|
||||
|
||||
import octoprint.printer
|
||||
@@ -64,8 +66,15 @@ class JsonEncodingSessionWrapper(wrapt.ObjectProxy):
|
||||
stats)
|
||||
|
||||
|
||||
class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
class PrinterStateConnection(octoprint.vendor.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, octoprint.vendor.sockjs.tornado.session.Session):
|
||||
session = JsonEncodingSessionWrapper(session)
|
||||
|
||||
@@ -84,19 +93,22 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
self._fileManager = fileManager
|
||||
self._analysisQueue = analysisQueue
|
||||
self._userManager = userManager
|
||||
self._groupManager = groupManager
|
||||
self._eventManager = eventManager
|
||||
self._pluginManager = pluginManager
|
||||
|
||||
self._remoteAddress = None
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
|
||||
self._throttleFactor = 1
|
||||
self._lastCurrent = 0
|
||||
self._baseRateLimit = 0.5
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
@staticmethod
|
||||
def _get_remote_address(info):
|
||||
forwarded_for = info.headers.get("X-Forwarded-For")
|
||||
if forwarded_for is not None:
|
||||
return forwarded_for.split(",")[0]
|
||||
return info.ip
|
||||
|
||||
def __str__(self):
|
||||
@@ -106,9 +118,12 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
return "Unconnected {!r}".format(self)
|
||||
|
||||
def on_open(self, info):
|
||||
self._remoteAddress = self._getRemoteAddress(info)
|
||||
self._remoteAddress = self._get_remote_address(info)
|
||||
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
||||
|
||||
self._userManager.register_login_status_listener(self)
|
||||
self._groupManager.register_listener(self)
|
||||
|
||||
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
|
||||
template_plugins = map(plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.TemplatePlugin))
|
||||
asset_plugins = map(plugin_signature, self._pluginManager.get_implementations(octoprint.plugin.AssetPlugin))
|
||||
@@ -121,48 +136,26 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
config_hash = settings().config_hash
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", dict(
|
||||
apikey=octoprint.server.UI_API_KEY,
|
||||
version=octoprint.server.VERSION,
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
config_hash=config_hash,
|
||||
debug=octoprint.server.debug,
|
||||
safe_mode=octoprint.server.safe_mode
|
||||
))
|
||||
|
||||
self._printer.register_callback(self)
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
octoprint.timelapse.register_callback(self)
|
||||
self._pluginManager.register_message_receiver(self.on_plugin_message)
|
||||
self._emit("connected", payload=dict(apikey=octoprint.server.UI_API_KEY,
|
||||
version=octoprint.server.VERSION,
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
config_hash=config_hash,
|
||||
debug=octoprint.server.debug,
|
||||
safe_mode=octoprint.server.safe_mode,
|
||||
permissions=[permission.as_dict() for permission in Permissions.all()]))
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
octoprint.timelapse.notify_callbacks(octoprint.timelapse.current)
|
||||
|
||||
# This is a horrible hack for now to allow displaying a notification that a render job is still
|
||||
# active in the backend on a fresh connect of a client. This needs to be substituted with a proper
|
||||
# job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints
|
||||
# start and so on.
|
||||
#
|
||||
# For now this is the easiest way though to at least inform the user that a timelapse is still ongoing.
|
||||
#
|
||||
# TODO remove when central job management becomes available and takes care of this for us
|
||||
if octoprint.timelapse.current_render_job is not None:
|
||||
self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job})
|
||||
self._register()
|
||||
|
||||
def on_close(self):
|
||||
self._printer.unregister_callback(self)
|
||||
self._fileManager.unregister_slicingprogress_callback(self)
|
||||
octoprint.timelapse.unregister_callback(self)
|
||||
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
self._groupManager.unregister_listener(self)
|
||||
self._userManager.unregister_login_status_listener(self)
|
||||
|
||||
self._unregister()
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
||||
self._remoteAddress = None
|
||||
@@ -175,7 +168,27 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
self._logger.warn("Invalid JSON received from client {}, ignoring: {!r}".format(self._remoteAddress, message))
|
||||
return
|
||||
|
||||
if "throttle" in message:
|
||||
if "auth" in message:
|
||||
try:
|
||||
parts = message["auth"].split(":")
|
||||
if not len(parts) == 2:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
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)
|
||||
|
||||
if user is not None:
|
||||
self._user = user
|
||||
self._reregister()
|
||||
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(), self._remoteAddress))
|
||||
else:
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
self._reregister()
|
||||
self._logger.warn("Unknown user/session combo: {}:{}".format(user_id, user_session))
|
||||
|
||||
elif "throttle" in message:
|
||||
try:
|
||||
throttle = int(message["throttle"])
|
||||
if throttle < 1:
|
||||
@@ -187,6 +200,9 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
self._logger.debug("Set throttle factor for client {} to {}".format(self._remoteAddress, self._throttleFactor))
|
||||
|
||||
def on_printer_send_current_data(self, data):
|
||||
if not self._user.has_permission(Permissions.STATUS):
|
||||
return
|
||||
|
||||
# make sure we rate limit the updates according to our throttle factor
|
||||
now = time.time()
|
||||
if now < self._lastCurrent + self._baseRateLimit * self._throttleFactor:
|
||||
@@ -220,26 +236,29 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
"messages": messages,
|
||||
"busyFiles": busy_files,
|
||||
})
|
||||
self._emit("current", data)
|
||||
self._emit("current", payload=data)
|
||||
|
||||
def on_printer_send_initial_data(self, data):
|
||||
data_to_send = dict(data)
|
||||
data_to_send["serverTime"] = time.time()
|
||||
self._emit("history", data_to_send)
|
||||
self._emit("history", payload=data_to_send)
|
||||
|
||||
def sendEvent(self, type, payload=None):
|
||||
self._emit("event", {"type": type, "payload": payload})
|
||||
self._emit("event", payload=dict(type=type, payload=payload))
|
||||
|
||||
def sendTimelapseConfig(self, timelapseConfig):
|
||||
self._emit("timelapse", timelapseConfig)
|
||||
self._emit("timelapse", payload=timelapseConfig)
|
||||
|
||||
def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
self._emit("slicingProgress",
|
||||
dict(slicer=slicer, source_location=source_location, source_path=source_path, dest_location=dest_location, dest_path=dest_path, progress=progress)
|
||||
)
|
||||
self._emit("slicingProgress", payload=dict(slicer=slicer,
|
||||
source_location=source_location,
|
||||
source_path=source_path,
|
||||
dest_location=dest_location,
|
||||
dest_path=dest_path,
|
||||
progress=progress))
|
||||
|
||||
def on_plugin_message(self, plugin, data):
|
||||
self._emit("plugin", dict(plugin=plugin, data=data))
|
||||
def on_plugin_message(self, plugin, data, permissions=None):
|
||||
self._emit("plugin", payload=dict(plugin=plugin, data=data), permissions=permissions)
|
||||
|
||||
def on_printer_add_log(self, data):
|
||||
with self._logBacklogMutex:
|
||||
@@ -253,10 +272,96 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
with self._temperatureBacklogMutex:
|
||||
self._temperatureBacklog.append(data)
|
||||
|
||||
def on_user_logged_out(self, user):
|
||||
if user.get_id() == self._user.get_id() and hasattr(user, "session") and user.session == self._user.session:
|
||||
self._logger.info("User {} logged out, logging out on socket".format(user.get_id()))
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
self._reregister()
|
||||
self._sendReauthRequired("logout")
|
||||
|
||||
def on_user_modified(self, user):
|
||||
if user.get_id() == self._user.get_id():
|
||||
self._reregister()
|
||||
self._sendReauthRequired("modified")
|
||||
|
||||
def on_user_removed(self, userid):
|
||||
if self._user.get_id() == userid:
|
||||
self._logger.info("User {} deleted, logging out on socket".format(userid))
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
self._reregister()
|
||||
self._sendReauthRequired("removed")
|
||||
|
||||
def on_group_permissions_changed(self, group, added=None, removed=None):
|
||||
if self._user.is_anonymous and group == self._groupManager.guest_group:
|
||||
self._reregister()
|
||||
self._sendReauthRequired("modified")
|
||||
|
||||
def _onEvent(self, event, payload):
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
def _register(self):
|
||||
"""Register this socket with the system if STATUS permission is available."""
|
||||
|
||||
if not self._user.has_permission(Permissions.STATUS):
|
||||
return
|
||||
|
||||
# printer
|
||||
self._printer.register_callback(self)
|
||||
self._printer.send_initial_callback(self)
|
||||
|
||||
# files
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
|
||||
# events
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
# plugins
|
||||
self._pluginManager.register_message_receiver(self.on_plugin_message)
|
||||
|
||||
# timelapse
|
||||
octoprint.timelapse.register_callback(self)
|
||||
octoprint.timelapse.notify_callback(self, timelapse=octoprint.timelapse.current)
|
||||
if octoprint.timelapse.current_render_job is not None:
|
||||
# This is a horrible hack for now to allow displaying a notification that a render job is still
|
||||
# active in the backend on a fresh connect of a client. This needs to be substituted with a proper
|
||||
# job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints
|
||||
# start and so on.
|
||||
#
|
||||
# For now this is the easiest way though to at least inform the user that a timelapse is still ongoing.
|
||||
#
|
||||
# TODO remove when central job management becomes available and takes care of this for us
|
||||
self._emit("event", payload=dict(type=Events.MOVIE_RENDERING,
|
||||
payload=octoprint.timelapse.current_render_job))
|
||||
|
||||
def _unregister(self):
|
||||
"""Unregister this socket from the system"""
|
||||
|
||||
self._printer.unregister_callback(self)
|
||||
self._fileManager.unregister_slicingprogress_callback(self)
|
||||
octoprint.timelapse.unregister_callback(self)
|
||||
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def _reregister(self):
|
||||
"""Unregister and register again"""
|
||||
self._unregister()
|
||||
self._register()
|
||||
|
||||
def _sendReauthRequired(self, reason):
|
||||
self._emit("reauthRequired", payload=dict(reason=reason))
|
||||
|
||||
def _emit(self, type, payload=None, permissions=None):
|
||||
if payload is None:
|
||||
payload = dict()
|
||||
|
||||
if permissions is None:
|
||||
permissions = self._emit_permissions.get(type, self._emit_permissions["*"])
|
||||
|
||||
if not self._user or not all(map(lambda p: self._user.has_permission(p), permissions)):
|
||||
return
|
||||
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
@@ -264,3 +369,4 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o
|
||||
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
|
||||
else:
|
||||
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
|
||||
|
||||
@@ -1127,7 +1127,7 @@ class GlobalHeaderTransform(tornado.web.OutputTransform):
|
||||
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
|
||||
|
||||
|
||||
def access_validation_factory(app, login_manager, validator):
|
||||
def access_validation_factory(app, login_manager, validator, permission):
|
||||
"""
|
||||
Creates an access validation wrapper using the supplied validator.
|
||||
|
||||
@@ -1147,7 +1147,7 @@ def access_validation_factory(app, login_manager, validator):
|
||||
with app.request_context(wsgi_environ):
|
||||
app.session_interface.open_session(app, flask.request)
|
||||
login_manager.reload_user()
|
||||
validator(flask.request)
|
||||
validator(flask.request, permission)
|
||||
return f
|
||||
|
||||
def path_validation_factory(path_filter, status_code=404):
|
||||
|
||||
@@ -16,9 +16,10 @@ from flask import request, g, url_for, make_response, render_template, send_from
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||
from octoprint.server import app, userManager, groupManager, pluginManager, gettext, \
|
||||
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \
|
||||
NOT_MODIFIED
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.settings import settings
|
||||
from octoprint.filemanager import get_all_extensions
|
||||
from octoprint.util import to_unicode
|
||||
@@ -348,13 +349,12 @@ def index():
|
||||
filtered_templates = _filter_templates(_templates[locale], default_template_filter)
|
||||
|
||||
wizard = wizard_active(filtered_templates)
|
||||
accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized()
|
||||
accesscontrol_active = enable_accesscontrol and userManager.has_been_customized()
|
||||
|
||||
render_kwargs = _get_render_kwargs(filtered_templates,
|
||||
_plugin_names,
|
||||
_plugin_vars,
|
||||
now)
|
||||
|
||||
render_kwargs.update(dict(
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
|
||||
@@ -422,6 +422,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
|
||||
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)
|
||||
permissions = [permission.as_dict() for permission in Permissions.all()]
|
||||
extensions = map(lambda ext: ".{}".format(ext), get_all_extensions())
|
||||
|
||||
#~~ prepare full set of template vars for rendering
|
||||
@@ -434,6 +435,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
templates=templates,
|
||||
pluginNames=plugin_names,
|
||||
locales=locales,
|
||||
permissions=permissions,
|
||||
supportedExtensions=extensions
|
||||
)
|
||||
render_kwargs.update(plugin_vars)
|
||||
@@ -527,27 +529,27 @@ def _process_templates():
|
||||
# navbar
|
||||
|
||||
templates["navbar"]["entries"] = dict(
|
||||
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin"),
|
||||
systemmenu=dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False),
|
||||
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.SETTINGS)"),
|
||||
systemmenu=dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", classes=["dropdown"], styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.SYSTEM)", custom_bindings=False),
|
||||
login=dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False),
|
||||
)
|
||||
|
||||
# sidebar
|
||||
|
||||
templates["sidebar"]["entries"]= dict(
|
||||
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isUser", template_header="sidebar/connection_header.jinja2")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2"))
|
||||
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_LIST)"))
|
||||
)
|
||||
|
||||
# tabs
|
||||
|
||||
templates["tab"]["entries"] = dict(
|
||||
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")),
|
||||
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")),
|
||||
gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode")),
|
||||
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")),
|
||||
timelapse=(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
|
||||
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_LIST)"))
|
||||
)
|
||||
|
||||
# settings dialog
|
||||
|
||||
@@ -311,8 +311,11 @@ default_settings = {
|
||||
"accessControl": {
|
||||
"enabled": True,
|
||||
"salt": None,
|
||||
"userManager": "octoprint.users.FilebasedUserManager",
|
||||
"userManager": "octoprint.access.users.FilebasedUserManager",
|
||||
"groupManager": "octoprint.access.groups.FilebasedGroupManager",
|
||||
"permissionManager": "octoprint.access.permissions.PermissionManager",
|
||||
"userfile": None,
|
||||
"groupfile": None,
|
||||
"autologinLocal": False,
|
||||
"localNetworks": ["127.0.0.0/8"],
|
||||
"autologinAs": None,
|
||||
@@ -330,6 +333,7 @@ default_settings = {
|
||||
},
|
||||
"api": {
|
||||
"enabled": True,
|
||||
"keyEnforced": False,
|
||||
"key": None,
|
||||
"allowCrossOrigin": False,
|
||||
"apps": {}
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,218 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define("OctoPrintAccessClient", ["OctoPrintClient"], factory);
|
||||
} else {
|
||||
global.OctoPrintAccessClient = factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var baseAccessUrl = "api/access";
|
||||
|
||||
//~~ permissions client api
|
||||
|
||||
var OctoPrintAccessPermissionsClient = function(access) {
|
||||
this.access = access;
|
||||
this.base = this.access.base;
|
||||
|
||||
var baseUrl = baseAccessUrl + "/permissions";
|
||||
this.url = function() {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
return baseUrl;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
OctoPrintAccessPermissionsClient.prototype.list = function (opts) {
|
||||
return this.base.get(this.url(), opts);
|
||||
};
|
||||
|
||||
//~~ groups client api
|
||||
|
||||
var OctoPrintAccessGroupsClient = function(access) {
|
||||
this.access = access;
|
||||
this.base = this.access.base;
|
||||
|
||||
var baseUrl = baseAccessUrl + "/groups";
|
||||
this.url = function() {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
return baseUrl;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
OctoPrintAccessGroupsClient.prototype.list = function (opts) {
|
||||
return this.base.get(this.url(), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessGroupsClient.prototype.add = function (group, opts) {
|
||||
if (!group.key) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("group key must be set");
|
||||
}
|
||||
if (!group.name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("group name must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
key: group.key,
|
||||
name: group.name,
|
||||
description: group.description,
|
||||
permissions: group.permissions,
|
||||
default: group.default
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url(), data, opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessGroupsClient.prototype.get = function (key, opts) {
|
||||
if (!key) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("group key must be set");
|
||||
}
|
||||
|
||||
return this.base.get(this.url(key), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessGroupsClient.prototype.update = function (group, opts) {
|
||||
if (!group.key) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("group key must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
description: group.description,
|
||||
permissions: group.permissions,
|
||||
default: group.default
|
||||
};
|
||||
return this.base.putJson(this.url(group.key), data, opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessGroupsClient.prototype.delete = function (key, opts) {
|
||||
if (!key) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("group key must be set");
|
||||
}
|
||||
|
||||
return this.base.delete(this.url(key), opts);
|
||||
};
|
||||
|
||||
//~~ users client api
|
||||
|
||||
var OctoPrintAccessUsersClient = function(access) {
|
||||
this.access = access;
|
||||
this.base = this.access.base;
|
||||
|
||||
var baseUrl = baseAccessUrl + "/users";
|
||||
this.url = function() {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
return baseUrl;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.list = function (opts) {
|
||||
return this.base.get(this.url(), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.add = function (user, opts) {
|
||||
if (!user.name || !user.password) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("Both user's name and password need to be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
name: user.name,
|
||||
password: user.password,
|
||||
groups: user.hasOwnProperty("groups") ? user.groups : [],
|
||||
permissions: user.hasOwnProperty("permissions") ? user.permissions : [],
|
||||
active: user.hasOwnProperty("active") ? !!user.active : true,
|
||||
admin: user.hasOwnProperty("admin") ? !!user.admin : false
|
||||
};
|
||||
|
||||
return this.base.postJson(this.url(), data, opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.get = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.get(this.url(name), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.update = function (name, active, admin, permissions, groups, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
active: !!active,
|
||||
groups: groups,
|
||||
permissions: permissions,
|
||||
admin: !!admin
|
||||
};
|
||||
return this.base.putJson(this.url(name), data, opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.delete = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.delete(this.url(name), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.changePassword = function (name, password, opts) {
|
||||
if (!name || !password) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name and password must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
password: password
|
||||
};
|
||||
return this.base.putJson(this.url(name, "password"), data, opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.generateApiKey = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.postJson(this.url(name, "apikey"), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.resetApiKey = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.delete(this.url(name, "apikey"), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.getSettings = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.get(this.url(name, "settings"), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.saveSettings = function (name, settings, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
settings = settings || {};
|
||||
return this.base.patchJson(this.url(name, "settings"), settings, opts);
|
||||
};
|
||||
|
||||
var OctoPrintAccessClient = function(base) {
|
||||
this.base = base;
|
||||
|
||||
this.permissions = new OctoPrintAccessPermissionsClient(this);
|
||||
this.groups = new OctoPrintAccessGroupsClient(this);
|
||||
this.users = new OctoPrintAccessUsersClient(this);
|
||||
};
|
||||
OctoPrintClient.registerComponent("access", OctoPrintAccessClient);
|
||||
return OctoPrintAccessClient;
|
||||
});
|
||||
@@ -111,9 +111,11 @@
|
||||
additional = additional || {};
|
||||
|
||||
var headers = $.extend({}, additional);
|
||||
headers["X-Api-Key"] = this.options.apikey;
|
||||
|
||||
if (this.options.locale !== undefined) {
|
||||
if (this.options.apikey) {
|
||||
headers["X-Api-Key"] = this.options.apikey;
|
||||
}
|
||||
if (this.options.locale) {
|
||||
headers["X-Locale"] = this.options.locale;
|
||||
}
|
||||
|
||||
@@ -335,5 +337,23 @@
|
||||
|
||||
OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException("InvalidArgumentError");
|
||||
|
||||
OctoPrintClient.deprecated = function (deprecatedFct, newFct, fn) {
|
||||
return function() {
|
||||
console.warn(deprecatedFct + " is deprecated, please use the new " + newFct + " function instead");
|
||||
return fn.apply(this, arguments);
|
||||
};
|
||||
};
|
||||
|
||||
OctoPrintClient.deprecatedMethod = function(object, oldNamespace, oldFct, newNamespace, newFct, fn) {
|
||||
object[oldFct] = OctoPrintClient.deprecated(oldNamespace + "." + oldFct, newNamespace + "." + newFct, fn);
|
||||
};
|
||||
|
||||
OctoPrintClient.deprecatedVariable = function(object, oldNamespace, oldVar, newNamespace, newVar, getter, setter) {
|
||||
Object.defineProperty(object, oldVar, {
|
||||
get: function() { return OctoPrintClient.deprecated(oldNamespace + "." + oldVar, newNamespace + "." + newVar, getter)(); },
|
||||
set: function(val) { OctoPrintClient.deprecated(oldNamespace + "." + oldVar, newNamespace + "." + newVar, setter)(val); }
|
||||
});
|
||||
};
|
||||
|
||||
return OctoPrintClient;
|
||||
});
|
||||
@@ -85,6 +85,10 @@
|
||||
this.sendMessage("throttle", this.rateThrottleFactor);
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.sendAuth = function(userId, session) {
|
||||
this.sendMessage("auth", userId + ":" + session);
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.sendMessage = function(type, payload) {
|
||||
var data = {};
|
||||
data[type] = payload;
|
||||
|
||||
@@ -1,114 +1,57 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
define(["OctoPrintClient", "OctoPrintAccessClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var baseUrl = "api/users";
|
||||
|
||||
var url = function() {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
return baseUrl;
|
||||
}
|
||||
var deprecatedUserClient = function (deprecatedFct, newFct, fn) {
|
||||
return OctoPrintClient.deprecated("OctoPrint.users." + deprecatedFct, "OctoPrint.access.users." + newFct, fn);
|
||||
};
|
||||
|
||||
var OctoPrintUserClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.list = function (opts) {
|
||||
return this.base.get(url(), opts);
|
||||
};
|
||||
OctoPrintUserClient.prototype.list = deprecatedUserClient("list", "list", function (opts) {
|
||||
return this.base.access.users.list(opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.add = function (user, opts) {
|
||||
if (!user.name || !user.password) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("Both user's name and password need to be set");
|
||||
}
|
||||
OctoPrintUserClient.prototype.add = deprecatedUserClient("add", "add", function (user, opts) {
|
||||
return this.base.access.users.add(user, opts);
|
||||
});
|
||||
|
||||
var data = {
|
||||
name: user.name,
|
||||
password: user.password,
|
||||
active: user.hasOwnProperty("active") ? !!user.active : true,
|
||||
admin: user.hasOwnProperty("admin") ? !!user.admin : false
|
||||
};
|
||||
OctoPrintUserClient.prototype.get = deprecatedUserClient("get", "get", function (name, opts) {
|
||||
return this.base.access.users.get(name, opts);
|
||||
});
|
||||
|
||||
return this.base.postJson(url(), data, opts);
|
||||
};
|
||||
OctoPrintUserClient.prototype.update = deprecatedUserClient("update", "update", function (name, active, admin, permissions, groups, opts) {
|
||||
return this.base.access.users.update(name, active, admin, permissions, groups, opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.get = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
OctoPrintUserClient.prototype.delete = deprecatedUserClient("delete", "delete", function (name, opts) {
|
||||
return this.base.access.users.delete(name, opts);
|
||||
});
|
||||
|
||||
return this.base.get(url(name), opts);
|
||||
};
|
||||
OctoPrintUserClient.prototype.changePassword = deprecatedUserClient("changePassword", "changePassword", function (name, password, opts) {
|
||||
return this.base.access.users.changePassword(name, password, opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.update = function (name, active, admin, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
OctoPrintUserClient.prototype.generateApiKey = deprecatedUserClient("generateApiKey", "generateApiKey", function (name, opts) {
|
||||
return this.base.access.users.generateApiKey(name, opts);
|
||||
});
|
||||
|
||||
var data = {
|
||||
active: !!active,
|
||||
admin: !!admin
|
||||
};
|
||||
return this.base.putJson(url(name), data, opts);
|
||||
};
|
||||
OctoPrintUserClient.prototype.resetApiKey = deprecatedUserClient("resetApiKey", "resetApiKey", function (name, opts) {
|
||||
return this.base.access.users.resetApiKey(name, opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.delete = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
OctoPrintUserClient.prototype.getSettings = deprecatedUserClient("getSettings", "getSettings", function (name, opts) {
|
||||
return this.base.access.users.getSettings(name, opts);
|
||||
});
|
||||
|
||||
return this.base.delete(url(name), opts);
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.changePassword = function (name, password, opts) {
|
||||
if (!name || !password) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name and password must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
password: password
|
||||
};
|
||||
return this.base.putJson(url(name, "password"), data, opts);
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.generateApiKey = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.postJson(url(name, "apikey"), opts);
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.resetApiKey = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.delete(url(name, "apikey"), opts);
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.getSettings = function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return this.base.get(url(name, "settings"), opts);
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.saveSettings = function (name, settings, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
settings = settings || {};
|
||||
return this.base.patchJson(url(name, "settings"), settings, opts);
|
||||
};
|
||||
OctoPrintUserClient.prototype.saveSettings = deprecatedUserClient("saveSettings", "saveSettings", function (name, settings, opts) {
|
||||
return this.base.access.users.saveSettings(name, settings, opts);
|
||||
});
|
||||
|
||||
OctoPrintClient.registerComponent("users", OctoPrintUserClient);
|
||||
return OctoPrintUserClient;
|
||||
|
||||
@@ -133,6 +133,9 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
|
||||
var data = event.data;
|
||||
|
||||
// update permissions
|
||||
PERMISSIONS = data["permissions"];
|
||||
|
||||
// update version information
|
||||
var oldVersion = VERSION;
|
||||
VERSION = data["version"];
|
||||
@@ -319,6 +322,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
})
|
||||
};
|
||||
|
||||
self._onReauthMessage = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReauthRequired", [event.data.reason]);
|
||||
})
|
||||
};
|
||||
|
||||
self._onIncreaseRate = function(measurement, minimum) {
|
||||
log.debug("We are fast (" + measurement + " < " + minimum + "), increasing refresh rate");
|
||||
OctoPrint.socket.increaseRate();
|
||||
@@ -349,5 +358,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
.onMessage("slicingProgress", self._onSlicingProgress)
|
||||
.onMessage("event", self._onEvent)
|
||||
.onMessage("timelapse", self._onTimelapse)
|
||||
.onMessage("plugin", self._onPluginMessage);
|
||||
.onMessage("plugin", self._onPluginMessage)
|
||||
.onMessage("reauthRequired", self._onReauthMessage);
|
||||
}
|
||||
@@ -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();
|
||||
@@ -559,10 +568,18 @@ $(function() {
|
||||
throw new Error("settingsViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
if (!_.has(viewModelMap, "accessViewModel") || !viewModelMap["accessViewModel"].permissions) {
|
||||
throw new Error("accessViewmodel is missing or incomplete, can't run UI");
|
||||
}
|
||||
|
||||
if (!_.has(viewModelMap, "loginStateViewModel")) {
|
||||
throw new Error("loginStateViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
if (!_.has(viewModelMap, "uiStateViewModel")) {
|
||||
throw new Error("uiStateViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
var bindViewModels = function() {
|
||||
log.info("Going to bind " + allViewModelData.length + " view models...");
|
||||
_.each(allViewModelData, function(viewModelData) {
|
||||
@@ -658,10 +675,6 @@ $(function() {
|
||||
callViewModels(allViewModels, "onAllBound", [allViewModels]);
|
||||
log.info("... binding done");
|
||||
|
||||
// startup complete
|
||||
callViewModels(allViewModels, "onStartupComplete");
|
||||
setOnViewModels(allViewModels, "_startupComplete", true);
|
||||
|
||||
// make sure we can track the browser tab visibility
|
||||
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
|
||||
log.debug("Browser tab is now " + (status ? "visible" : "hidden"));
|
||||
@@ -669,14 +682,17 @@ $(function() {
|
||||
});
|
||||
|
||||
$(window).on("hashchange", function() {
|
||||
changeTab();
|
||||
OctoPrint.coreui.updateTab();
|
||||
});
|
||||
|
||||
if (window.location.hash !== "") {
|
||||
changeTab();
|
||||
}
|
||||
|
||||
log.info("Application startup complete");
|
||||
|
||||
viewModelMap["uiStateViewModel"].loading(false);
|
||||
|
||||
// startup complete
|
||||
callViewModels(allViewModels, "onStartupComplete");
|
||||
setOnViewModels(allViewModels, "_startupComplete", true);
|
||||
OctoPrint.coreui.updateTab();
|
||||
};
|
||||
|
||||
var fetchSettings = function() {
|
||||
@@ -733,6 +749,9 @@ $(function() {
|
||||
*/
|
||||
|
||||
var onServerConnect = function() {
|
||||
// Initialize our permissions
|
||||
viewModelMap["accessViewModel"].permissions.initialize();
|
||||
|
||||
// Always perform a passive login on server (re)connect. No need for
|
||||
// onServerConnect/onServerReconnect on the LoginStateViewModel with this in place.
|
||||
return viewModelMap["loginStateViewModel"].requestData()
|
||||
|
||||
@@ -0,0 +1,705 @@
|
||||
$(function() {
|
||||
function AccessViewModel(parameters) {
|
||||
var access = this;
|
||||
|
||||
access.loginState = parameters[0];
|
||||
|
||||
//~~ Users ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.users = (function() {
|
||||
var self = {};
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"users",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_USERSPERPAGE
|
||||
);
|
||||
|
||||
self.emptyUser = {name: "", active: false};
|
||||
|
||||
self.currentUser = ko.observable(self.emptyUser).extend({ notify: 'always' });
|
||||
|
||||
self.editor = {
|
||||
name: ko.observable(undefined),
|
||||
groups: ko.observableArray([]),
|
||||
permissions: ko.observableArray([]),
|
||||
password: ko.observable(undefined),
|
||||
repeatedPassword: ko.observable(undefined),
|
||||
passwordMismatch: ko.pureComputed(function() {
|
||||
return self.editor.password() !== self.editor.repeatedPassword();
|
||||
}),
|
||||
apikey: ko.observable(undefined),
|
||||
active: ko.observable(undefined),
|
||||
permissionSelected: function(permission) {
|
||||
var index = self.editor.permissions().indexOf(permission);
|
||||
return index >= 0;
|
||||
},
|
||||
togglePermission: function(permission) {
|
||||
var permissions = self.editor.permissions();
|
||||
var index = permissions.indexOf(permission);
|
||||
if (index < 0) {
|
||||
permissions.push(permission);
|
||||
} else {
|
||||
permissions.splice(index, 1);
|
||||
}
|
||||
self.editor.permissions(permissions);
|
||||
},
|
||||
groupSelected: function(group) {
|
||||
var index = self.editor.groups().indexOf(group);
|
||||
return index >= 0;
|
||||
},
|
||||
toggleGroup: function(group) {
|
||||
var groups = self.editor.groups();
|
||||
var index = groups.indexOf(group);
|
||||
if (index < 0) {
|
||||
groups.push(group);
|
||||
} else {
|
||||
groups.splice(index, 1);
|
||||
}
|
||||
self.editor.groups(groups);
|
||||
},
|
||||
joinedGroupPermissions: function(group) {
|
||||
return access.permissionList(group);
|
||||
},
|
||||
header: ko.observable(undefined),
|
||||
new: ko.observable(true),
|
||||
confirm: undefined,
|
||||
valid: ko.pureComputed(function() {
|
||||
return self.editor.name() && self.editor.name().trim()
|
||||
&& (!self.editor.new() || (self.editor.password() && self.editor.password().trim() && !self.editor.passwordMismatch()));
|
||||
})
|
||||
};
|
||||
|
||||
self.userEditorDialog = undefined;
|
||||
self.changePasswordDialog = undefined;
|
||||
|
||||
self.currentUser.subscribe(function(newValue) {
|
||||
if (newValue === undefined) {
|
||||
self.editor.name(undefined);
|
||||
self.editor.groups(access.groups.defaults.slice(0));
|
||||
self.editor.permissions([]);
|
||||
self.editor.active(true);
|
||||
self.editor.apikey(undefined);
|
||||
self.editor.header(gettext("Add user"));
|
||||
self.editor.new(true);
|
||||
self.editor.confirm = self.confirmAddUser
|
||||
} else {
|
||||
self.editor.name(newValue.name);
|
||||
self.editor.groups(newValue.groups.slice(0));
|
||||
self.editor.permissions(newValue.permissions.slice(0));
|
||||
self.editor.active(newValue.active);
|
||||
self.editor.apikey(newValue.apikey);
|
||||
self.editor.header(_.sprintf(gettext("Edit user \"%(name)s\""), {name: newValue.name}));
|
||||
self.editor.new(false);
|
||||
self.editor.confirm = self.confirmEditUser
|
||||
}
|
||||
self.editor.password(undefined);
|
||||
self.editor.repeatedPassword(undefined);
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (!access.loginState.hasPermissionKo(access.permissions.ADMIN)) return;
|
||||
|
||||
OctoPrint.access.users.list()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.listHelper.updateItems(response.users);
|
||||
};
|
||||
|
||||
self.showAddUserDialog = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(undefined);
|
||||
|
||||
$('ul.nav-pills a[data-toggle="tab"]:first', self.userEditorDialog).tab("show");
|
||||
self.userEditorDialog.modal({
|
||||
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
|
||||
}).css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmAddUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = {
|
||||
name: self.editor.name(),
|
||||
password: self.editor.password(),
|
||||
groups: self.editor.groups(),
|
||||
permissions: self.editor.permissions(),
|
||||
active: self.editor.active()
|
||||
};
|
||||
|
||||
self.addUser(user)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showEditUserDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var process = function(user) {
|
||||
self.currentUser(user);
|
||||
|
||||
$('ul.nav-pills a[data-toggle="tab"]:first', self.userEditorDialog).tab("show");
|
||||
self.userEditorDialog.modal({
|
||||
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
|
||||
}).css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrint.users.get(user.name)
|
||||
.done(function(data) {
|
||||
process(data);
|
||||
})
|
||||
.fail(function() {
|
||||
log.warn("Could not fetch current user data, proceeding with client side data copy");
|
||||
process(user);
|
||||
})
|
||||
};
|
||||
|
||||
self.confirmEditUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = self.currentUser();
|
||||
user.active = self.editor.active();
|
||||
user.groups = self.editor.groups();
|
||||
user.permissions = self.editor.permissions();
|
||||
|
||||
self.updateUser(user)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showChangePasswordDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
self.changePasswordDialog.modal("show");
|
||||
};
|
||||
|
||||
self.confirmChangePassword = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.updatePassword(self.currentUser().name, self.editor.password())
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.changePasswordDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmGenerateApikey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.generateApikey(self.currentUser().name)
|
||||
.done(function(response) {
|
||||
self._updateApikey(response.apikey);
|
||||
});
|
||||
};
|
||||
|
||||
self.copyApikey = function() {
|
||||
copyToClipboard(self.editor.apikey());
|
||||
};
|
||||
|
||||
self._updateApikey = function(apikey) {
|
||||
self.editor.apikey(apikey);
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.confirmDeleteApikey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.deleteApikey(self.currentUser().name)
|
||||
.done(function() {
|
||||
self._updateApikey(undefined);
|
||||
});
|
||||
};
|
||||
|
||||
//~~ Framework
|
||||
|
||||
self.onStartup = function() {
|
||||
self.userEditorDialog = $("#settings-usersEditorDialog");
|
||||
self.changePasswordDialog = $("#settings-usersDialogChangePassword");
|
||||
};
|
||||
|
||||
//~~ API calls
|
||||
|
||||
self.addUser = function(user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
if (!access.loginState.hasPermissionKo(access.permissions.ADMIN)) return $.Deferred().reject("You are not authorized to perform this action").promise();
|
||||
|
||||
return OctoPrint.access.users.add(user)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.removeUser = function(user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
if (!access.loginState.hasPermissionKo(access.permissions.ADMIN)) return $.Deferred().reject("You are not authorized to perform this action").promise();
|
||||
|
||||
if (user.name === access.loginState.username()) {
|
||||
// we do not allow to delete ourselves
|
||||
new PNotify({
|
||||
title: gettext("Not possible"),
|
||||
text: gettext("You may not delete your own account."),
|
||||
type: "error"
|
||||
});
|
||||
return $.Deferred().reject("You may not delete your own account").promise();
|
||||
}
|
||||
|
||||
showConfirmationDialog({
|
||||
title: gettext("Are you sure?"),
|
||||
message: _.sprintf(gettext("You are about to delete the user \"%(name)s\"."), {name: user.name}),
|
||||
proceed: gettext("Delete"),
|
||||
onproceed: function() {
|
||||
OctoPrint.access.users.delete(user.name)
|
||||
.done(self.fromResponse);
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
self.updateUser = function(user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.access.users.update(user.name, user.active, user.admin, user.permissions, user.groups)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.updatePassword = function(username, password) {
|
||||
return OctoPrint.access.users.changePassword(username, password);
|
||||
};
|
||||
|
||||
self.generateApikey = function(username) {
|
||||
return OctoPrint.access.users.generateApiKey(username)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
|
||||
self.deleteApikey = function(username) {
|
||||
return OctoPrint.access.users.resetApiKey(username);
|
||||
};
|
||||
|
||||
return self;
|
||||
})();
|
||||
|
||||
//~~ Groups ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.groups = (function() {
|
||||
var self = {};
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"groups",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_GROUPSPERPAGE
|
||||
);
|
||||
|
||||
self.groupsList = self.listHelper.items; // Alias for easier reference
|
||||
self.lookup = {};
|
||||
self.defaults = [];
|
||||
|
||||
self.emptyGroup = {name: ""};
|
||||
|
||||
self.currentGroup = ko.observable(self.emptyGroup);
|
||||
|
||||
self.editor = {
|
||||
key: ko.observable(undefined),
|
||||
name: ko.observable(undefined),
|
||||
description: ko.observable(undefined),
|
||||
permissions: ko.observableArray([]),
|
||||
default: ko.observable(false),
|
||||
permissionSelected: function(permission) {
|
||||
var index = self.editor.permissions().indexOf(permission);
|
||||
return index >= 0;
|
||||
},
|
||||
togglePermission: function(permission) {
|
||||
var permissions = self.editor.permissions();
|
||||
var index = permissions.indexOf(permission);
|
||||
if (index < 0) {
|
||||
permissions.push(permission);
|
||||
} else {
|
||||
permissions.splice(index, 1);
|
||||
}
|
||||
self.editor.permissions(permissions);
|
||||
},
|
||||
header: ko.observable(undefined),
|
||||
new: ko.observable(true),
|
||||
confirm: undefined,
|
||||
valid: ko.pureComputed(function() {
|
||||
return self.editor.name() && self.editor.name().trim();
|
||||
})
|
||||
};
|
||||
|
||||
self.groupEditorDialog = undefined;
|
||||
|
||||
// used to delete all the groups before registering new ones
|
||||
self.groupsList.subscribe(function(oldValue) {
|
||||
if (oldValue === undefined || oldValue.length === 0)
|
||||
return;
|
||||
|
||||
oldValue.forEach(function (p) {
|
||||
delete self[p.key.toUpperCase()];
|
||||
});
|
||||
}, null, "beforeChange");
|
||||
|
||||
// used to register new groups
|
||||
self.groupsList.subscribe(function(newValue) {
|
||||
if (newValue === undefined)
|
||||
return;
|
||||
|
||||
newValue.forEach(function(g) {
|
||||
var needs = [];
|
||||
g.permissions.forEach(function(p) {
|
||||
for (var key in p.needs) {
|
||||
p.needs[key].forEach(function(value) {
|
||||
needs.push(access.permissions.need(key, value));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// if the permission has no need sets do not register it.
|
||||
if (needs.length > 0) {
|
||||
self.registerGroup(g.key.toUpperCase(), needs);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
self.registerGroup = function(name, group) {
|
||||
Object.defineProperty(self, name, {
|
||||
value: group,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
};
|
||||
|
||||
self.currentGroup.subscribe(function(newValue) {
|
||||
if (newValue === undefined) {
|
||||
// group add
|
||||
self.editor.key(undefined);
|
||||
self.editor.name(undefined);
|
||||
self.editor.description(undefined);
|
||||
self.editor.permissions([]);
|
||||
self.editor.default(false);
|
||||
self.editor.header(gettext("Add group"));
|
||||
self.editor.new(true);
|
||||
self.editor.confirm = self.confirmAddGroup
|
||||
} else {
|
||||
// group update
|
||||
self.editor.key(newValue.key);
|
||||
self.editor.name(newValue.name);
|
||||
self.editor.description(newValue.description);
|
||||
self.editor.permissions(newValue.permissions.slice(0));
|
||||
self.editor.default(newValue.default);
|
||||
self.editor.header(_.sprintf(gettext("Edit group \"%(name)s\""), {name: newValue.name}));
|
||||
self.editor.new(false);
|
||||
self.editor.confirm = self.confirmEditGroup
|
||||
}
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.access.groups.list()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.listHelper.updateItems(response.groups);
|
||||
|
||||
var lookup = {};
|
||||
var defaults = [];
|
||||
_.each(response.groups, function(group) {
|
||||
lookup[group.key] = group;
|
||||
if (group.default) {
|
||||
defaults.push(group.key);
|
||||
}
|
||||
});
|
||||
self.lookup = lookup;
|
||||
self.defaults = defaults;
|
||||
};
|
||||
|
||||
self.showAddGroupDialog = function() {
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("show");
|
||||
};
|
||||
|
||||
self.confirmAddGroup = function() {
|
||||
var group = {
|
||||
key: self.editor.name().toLowerCase().replace(/[^a-z0-9_ ]/g, "").replace(/ /g, "_"),
|
||||
name: self.editor.name(),
|
||||
description: self.editor.description(),
|
||||
permissions: self.editor.permissions(),
|
||||
default: self.editor.default()
|
||||
};
|
||||
|
||||
self.addGroup(group)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showEditGroupDialog = function(group) {
|
||||
if (!group.changeable) return;
|
||||
|
||||
self.currentGroup(group);
|
||||
self.groupEditorDialog.modal("show");
|
||||
};
|
||||
|
||||
self.confirmEditGroup = function() {
|
||||
var group = self.currentGroup();
|
||||
|
||||
var data = { key: group.key, name: group.name };
|
||||
|
||||
if (group.description !== self.editor.description()) {
|
||||
data.description = self.editor.description();
|
||||
}
|
||||
|
||||
var editorPermissions = self.editor.permissions();
|
||||
if (!_.isEqual(group.permissions.sort(), editorPermissions.sort())) {
|
||||
data.permissions = editorPermissions;
|
||||
}
|
||||
|
||||
if (group.default !== self.editor.default()) {
|
||||
data.default = self.editor.default();
|
||||
}
|
||||
|
||||
self.updateGroup(data)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
//~~ Framework
|
||||
|
||||
self.onStartup = function() {
|
||||
self.groupEditorDialog = $("#settings-groupsEditorDialog");
|
||||
};
|
||||
|
||||
//~~ API calls
|
||||
|
||||
self.addGroup = function(group) {
|
||||
if (!group) {
|
||||
throw OctoPrint.InvalidArgumentError("group must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.access.groups.add(group)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.removeGroup = function(group) {
|
||||
if (!group) {
|
||||
throw OctoPrint.InvalidArgumentError("group must be set");
|
||||
}
|
||||
|
||||
if (!group.removable) return;
|
||||
|
||||
showConfirmationDialog({
|
||||
title: gettext("Are you sure?"),
|
||||
message: _.sprintf(gettext("You are about to delete the group \"%(name)s\"."), {name: group.name}),
|
||||
proceed: gettext("Delete"),
|
||||
onproceed: function() {
|
||||
OctoPrint.access.groups.delete(group.key).done(function(response) {
|
||||
self.fromResponse(response);
|
||||
access.users.requestData();
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.updateGroup = function(group) {
|
||||
if (!group) {
|
||||
throw OctoPrint.InvalidArgumentError("group must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.access.groups.update(group)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
return self;
|
||||
})();
|
||||
|
||||
//~~ Permissions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.permissions = (function() {
|
||||
var self = {};
|
||||
|
||||
self.need = function(method, value) { return {method: method, value: value}; };
|
||||
self.roleNeed = function(value) { return self.need("role", value); };
|
||||
|
||||
self.permissionList = ko.observableArray([]);
|
||||
self.lookup = {};
|
||||
|
||||
var registeredPermissions = [];
|
||||
var registerPermission = function(key, permission) {
|
||||
Object.defineProperty(self, key, {
|
||||
value: permission,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
registeredPermissions.push(key);
|
||||
};
|
||||
var clearAllRegisteredPermissions = function() {
|
||||
_.each(registeredPermissions, function(key) {
|
||||
delete self[key];
|
||||
});
|
||||
registeredPermissions = [];
|
||||
};
|
||||
|
||||
self.initialize = function() {
|
||||
clearAllRegisteredPermissions();
|
||||
|
||||
var permissionList = [];
|
||||
var lookup = {};
|
||||
_.each(PERMISSIONS, function(permission) {
|
||||
var needs = [];
|
||||
_.each(permission.needs, function(value, key) {
|
||||
needs.push(self.need(key, value));
|
||||
});
|
||||
|
||||
if (needs.length > 0) {
|
||||
registerPermission(permission.key, needs);
|
||||
}
|
||||
|
||||
if (!permission.combined) {
|
||||
permissionList.push(permission);
|
||||
}
|
||||
lookup[permission.key] = permission;
|
||||
});
|
||||
|
||||
permissionList.sort(access.permissionComparator);
|
||||
self.permissionList(permissionList);
|
||||
self.lookup = lookup;
|
||||
};
|
||||
|
||||
return self;
|
||||
})();
|
||||
|
||||
//~~ helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.groupComparator = function(a, b) {
|
||||
var nameA = a.name ? a.name.toUpperCase() : "";
|
||||
var nameB = b.name ? b.name.toUpperCase() : "";
|
||||
|
||||
if (nameA < nameB) {
|
||||
return -1;
|
||||
} else if (nameA > nameB) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
access.permissionComparator = function(a, b) {
|
||||
var nameA = a.name ? a.name.toUpperCase() : "";
|
||||
var nameB = b.name ? b.name.toUpperCase() : "";
|
||||
|
||||
var pluginA = a.plugin || "";
|
||||
var pluginB = b.plugin || "";
|
||||
|
||||
var compA = pluginA + ":" + nameA;
|
||||
var compB = pluginB + ":" + nameB;
|
||||
|
||||
if (compA < compB) {
|
||||
return -1;
|
||||
} else if (compA > compB) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// Maps the group names into a comma separated list
|
||||
access.groupList = function(data) {
|
||||
if (data.groups === undefined)
|
||||
return "";
|
||||
|
||||
var mappedGroups = _.filter(_.map(data.groups, function(g) { return access.groups.lookup[g] }), function(g) { return g !== undefined });
|
||||
mappedGroups.sort(access.groupComparator);
|
||||
return _.map(mappedGroups, function(g) {
|
||||
return g.name;
|
||||
}).join(", ");
|
||||
};
|
||||
|
||||
// Maps the permission names into a comma separated list
|
||||
access.permissionList = function(data) {
|
||||
if (!data || data.permissions === undefined)
|
||||
return "";
|
||||
|
||||
var mappedPermissions = _.filter(_.map(data.permissions, function(p) { return access.permissions.lookup[p] }), function(p) { return p !== undefined });
|
||||
mappedPermissions.sort(access.permissionComparator);
|
||||
return _.map(mappedPermissions, function(p) {
|
||||
return p.name;
|
||||
}).join(", ");
|
||||
};
|
||||
|
||||
//~~ API Calls
|
||||
access.onStartup = function() {
|
||||
access.groups.onStartup();
|
||||
access.users.onStartup();
|
||||
};
|
||||
|
||||
access.onServerConnect = function() {
|
||||
access.permissions.initialize();
|
||||
};
|
||||
|
||||
access.onServerReconnect = function() {
|
||||
access.permissions.initialize();
|
||||
};
|
||||
|
||||
access.onUserPermissionsChanged = access.onUserLoggedIn = access.onUserLoggedOut = function(user) {
|
||||
if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
|
||||
access.groups.requestData();
|
||||
access.users.requestData();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AccessViewModel,
|
||||
["loginStateViewModel"],
|
||||
[]
|
||||
]);
|
||||
});
|
||||
@@ -5,6 +5,7 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
self.access = parameters[3];
|
||||
|
||||
self.printerProfiles.profiles.items.subscribe(function() {
|
||||
var allProfiles = self.printerProfiles.profiles.items();
|
||||
@@ -49,6 +50,10 @@ $(function() {
|
||||
self.refreshVisible = ko.observable(true);
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.connection.getSettings()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
@@ -82,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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -102,7 +111,7 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
if (self.loginState.isUser() && 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();
|
||||
@@ -159,22 +168,20 @@ $(function() {
|
||||
connectionTab.on("hide", function() {
|
||||
self.refreshVisible(false);
|
||||
});
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
self.openOrCloseOnStateChange(true);
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.openOrCloseOnStateChange();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.openOrCloseOnStateChange();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ConnectionViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel", "accessViewModel"],
|
||||
elements: ["#connection_wrapper"]
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self._createToolEntry = function () {
|
||||
return {
|
||||
@@ -43,7 +44,7 @@ $(function() {
|
||||
self.keycontrolActive = ko.observable(false);
|
||||
self.keycontrolHelpActive = ko.observable(false);
|
||||
self.keycontrolPossible = ko.pureComputed(function () {
|
||||
return self.settings.feature_keyboardControl() && self.isOperational() && !self.isPrinting() && self.loginState.isUser() && !$.browser.mobile;
|
||||
return self.loginState.hasPermission(self.access.permissions.CONTROL) && self.settings.feature_keyboardControl() && self.isOperational() && !self.isPrinting() && !$.browser.mobile;
|
||||
});
|
||||
self.showKeycontrols = ko.pureComputed(function () {
|
||||
return self.keycontrolActive() && self.keycontrolPossible();
|
||||
@@ -123,6 +124,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.CONTROL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.control.getCustomControls()
|
||||
.done(function(response) {
|
||||
self._fromResponse(response);
|
||||
@@ -238,7 +243,7 @@ $(function() {
|
||||
if (data.hasOwnProperty("enabled")) {
|
||||
return data.enabled(data);
|
||||
} else {
|
||||
return self.isOperational() && self.loginState.isUser();
|
||||
return self.loginState.hasPermission(self.access.permissions.CONTROL) && self.isOperational();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -353,7 +358,7 @@ $(function() {
|
||||
return span + " " + offset;
|
||||
};
|
||||
|
||||
self.onStartup = function () {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
@@ -560,7 +565,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ControlViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#control"]
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#control", "#control_link"]
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ $(function() {
|
||||
self.printerState = parameters[2];
|
||||
self.slicing = parameters[3];
|
||||
self.printerProfiles=parameters[4];
|
||||
self.access = parameters[5];
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
@@ -76,8 +77,7 @@ $(function() {
|
||||
self.addFolderDialog = undefined;
|
||||
self.addFolderName = ko.observable(undefined);
|
||||
self.enableAddFolder = ko.pureComputed(function() {
|
||||
return self.loginState.isUser() && 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,11 +159,11 @@ $(function() {
|
||||
});
|
||||
|
||||
self.isLoadActionPossible = ko.pureComputed(function() {
|
||||
return self.loginState.isUser() && !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() {
|
||||
return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible();
|
||||
return self.loginState.hasPermission(self.access.permissions.PRINT) && self.isOperational() && self.isLoadActionPossible();
|
||||
});
|
||||
|
||||
self.printerState.filepath.subscribe(function(newValue) {
|
||||
@@ -211,6 +211,10 @@ $(function() {
|
||||
self._focus = undefined;
|
||||
self._switchToPath = undefined;
|
||||
self.requestData = function(params) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.FILES_LIST)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var focus, switchToPath, force;
|
||||
|
||||
if (_.isObject(params)) {
|
||||
@@ -246,6 +250,10 @@ $(function() {
|
||||
.done(function(response) {
|
||||
self.fromResponse(response, {focus: self._focus, switchToPath: self._switchToPath});
|
||||
})
|
||||
.fail(function() {
|
||||
self.allItems(undefined);
|
||||
self.listHelper.updateItems([]);
|
||||
})
|
||||
.always(function() {
|
||||
self._otherRequestInProgress = undefined;
|
||||
self._focus = undefined;
|
||||
@@ -361,6 +369,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showAddFolderDialog = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD)) return;
|
||||
|
||||
if (self.addFolderDialog) {
|
||||
self.addFolderName("");
|
||||
self.addFolderDialog.modal("show");
|
||||
@@ -368,6 +378,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,
|
||||
@@ -400,6 +412,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeFolder = function(folder, event) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.FILES_DELETE)) return;
|
||||
|
||||
if (!folder) {
|
||||
return;
|
||||
}
|
||||
@@ -423,6 +437,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.loadFile = function(data, printAfterLoad) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.FILES_SELECT)) return;
|
||||
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
@@ -440,6 +456,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeFile = function(file, event) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.FILES_DELETE)) return;
|
||||
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
@@ -452,6 +470,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.sliceFile = function(file) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SLICE)) return;
|
||||
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
@@ -460,14 +480,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();
|
||||
};
|
||||
|
||||
@@ -575,19 +598,25 @@ $(function() {
|
||||
} else {
|
||||
busy = _.contains(self.printerState.busyFiles(), data.origin + ":" + data.path);
|
||||
}
|
||||
return self.loginState.isUser() && !busy;
|
||||
return self.loginState.hasPermission(self.access.permissions.FILES_DELETE) && !busy;
|
||||
};
|
||||
|
||||
self.enableSelect = function(data, printAfterSelect) {
|
||||
return self.enablePrint(data) && !self.listHelper.isSelected(data);
|
||||
self.enableSelect = function(data) {
|
||||
return self.isLoadAndPrintActionPossible() && !self.listHelper.isSelected(data);
|
||||
};
|
||||
|
||||
self.enablePrint = function(data) {
|
||||
return self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading());
|
||||
return self.loginState.hasPermission(self.access.permissions.PRINT) && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading());
|
||||
};
|
||||
|
||||
self.enableSelectAndPrint = function(data, printAfterSelect) {
|
||||
var isLoadAndPrintActionPossible = self.isLoadAndPrintActionPossible();
|
||||
return isLoadAndPrintActionPossible && !self.listHelper.isSelected(data);
|
||||
};
|
||||
|
||||
|
||||
self.enableSlicing = function(data) {
|
||||
return self.loginState.isUser() && self.slicing.enableSlicingDialog() && self.slicing.enableSlicingDialogForFile(data.name);
|
||||
return self.loginState.hasPermission(self.access.permissions.SLICE) && self.slicing.enableSlicingDialog() && self.slicing.enableSlicingDialogForFile(data.name);
|
||||
};
|
||||
|
||||
self.enableAdditionalData = function(data) {
|
||||
@@ -783,18 +812,23 @@ $(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");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.uploadButton.fileupload("disable");
|
||||
if (self.uploadSdButton) {
|
||||
self.uploadSdButton.fileupload("disable");
|
||||
}
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.updateButtons();
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
@@ -852,18 +886,16 @@ $(function() {
|
||||
self.dropOverlay.on('drop', self._forceEndDragNDrop);
|
||||
|
||||
function evaluateDropzones() {
|
||||
var enableLocal = self.loginState.isUser();
|
||||
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);
|
||||
self._setDropzone("sdcard", enableSd);
|
||||
}
|
||||
self.loginState.isUser.subscribe(evaluateDropzones);
|
||||
self.loginState.currentUser.subscribe(evaluateDropzones);
|
||||
self.printerState.isSdReady.subscribe(evaluateDropzones);
|
||||
self.isPrinting.subscribe(evaluateDropzones);
|
||||
evaluateDropzones();
|
||||
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventUpdatedFiles = function(payload) {
|
||||
@@ -1186,7 +1218,7 @@ $(function() {
|
||||
construct: FilesViewModel,
|
||||
name: "filesViewModel",
|
||||
additionalNames: ["gcodeFilesViewModel"],
|
||||
dependencies: ["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel", "printerProfilesViewModel"],
|
||||
dependencies: ["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel", "printerProfilesViewModel", "accessViewModel"],
|
||||
elements: ["#files_wrapper", "#add_folder_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.ui_progress_percentage = ko.observable();
|
||||
self.ui_progress_type = ko.observable();
|
||||
@@ -744,7 +745,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: GcodeViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#gcode"]
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#gcode", "#gcode_link"]
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,14 @@
|
||||
$(function() {
|
||||
function LoginStateViewModel() {
|
||||
function LoginStateViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginUser = ko.observable("");
|
||||
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);
|
||||
self.isUser = ko.observable(false);
|
||||
|
||||
@@ -41,33 +42,48 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
return OctoPrint.users.get(self.currentUser().name)
|
||||
return OctoPrint.access.users.get(self.currentUser().name)
|
||||
.done(self.updateCurrentUserData);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
return OctoPrint.browser.passiveLogin()
|
||||
.done(self.fromResponse);
|
||||
.done(self.fromResponse)
|
||||
.fail(function() {
|
||||
// something went very wrong, still, proceed
|
||||
self.fromResponse();
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
var process = function() {
|
||||
var currentLoggedIn = self.loggedIn();
|
||||
var currentNeeds = self.userneeds();
|
||||
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")
|
||||
log.info("User " + response.name + " logged in");
|
||||
} else if (!_.isEqual(currentNeeds, self.userneeds())) {
|
||||
callViewModels(self.allViewModels, "onUserPermissionsChanged");
|
||||
log.info("User needs for " + response.name + " changed");
|
||||
}
|
||||
if (response.session) {
|
||||
OctoPrint.socket.sendAuth(response.name, response.session);
|
||||
}
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.resetCurrentUserData();
|
||||
if (currentLoggedIn) {
|
||||
self.updateCurrentUserData(response);
|
||||
if (currentLoggedIn || currentLoggedIn === undefined) {
|
||||
callViewModels(self.allViewModels, "onUserLoggedOut");
|
||||
log.info("User logged out");
|
||||
} else if (!_.isEqual(currentNeeds, self.userneeds())) {
|
||||
callViewModels(self.allViewModels, "onUserPermissionsChanged");
|
||||
log.info("User needs for guest changed");
|
||||
}
|
||||
}
|
||||
OctoPrint.coreui.updateTab();
|
||||
};
|
||||
|
||||
if (self.startupDeferred !== undefined) {
|
||||
@@ -80,29 +96,44 @@ $(function() {
|
||||
};
|
||||
|
||||
self.updateCurrentUserData = function(data) {
|
||||
self.username(data.name);
|
||||
self.isUser(data.user);
|
||||
self.isAdmin(data.admin);
|
||||
if (data) {
|
||||
self.userneeds(data.needs);
|
||||
} else {
|
||||
self.userneeds({});
|
||||
}
|
||||
|
||||
self.currentUser(data);
|
||||
if (data.name) {
|
||||
self.username(data.name);
|
||||
self.currentUser(data);
|
||||
|
||||
// TODO: deprecated, remove in 1.5.0
|
||||
self.isUser(data.user);
|
||||
self.isAdmin(data.admin);
|
||||
} else {
|
||||
self.username(undefined);
|
||||
self.currentUser(undefined);
|
||||
|
||||
// TODO: deprecated, remove in 1.5.0
|
||||
self.isUser(false);
|
||||
self.isAdmin(false);
|
||||
}
|
||||
};
|
||||
|
||||
self.resetCurrentUserData = function() {
|
||||
self.username(undefined);
|
||||
self.isUser(false);
|
||||
self.isAdmin(false);
|
||||
|
||||
self.currentUser(undefined);
|
||||
};
|
||||
|
||||
self.login = function(u, p, r) {
|
||||
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)
|
||||
.done(function(response) {
|
||||
new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"});
|
||||
if (notifications) {
|
||||
new PNotify({
|
||||
title: gettext("Login successful"),
|
||||
text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}),
|
||||
type: "success"
|
||||
});
|
||||
}
|
||||
self.fromResponse(response);
|
||||
|
||||
self.loginUser("");
|
||||
@@ -114,6 +145,10 @@ $(function() {
|
||||
}
|
||||
})
|
||||
.fail(function(response) {
|
||||
if (!notifications) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch(response.status) {
|
||||
case 401: {
|
||||
new PNotify({
|
||||
@@ -135,7 +170,10 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
var _logoutInProgress = false;
|
||||
self.logout = function() {
|
||||
if (_logoutInProgress) return;
|
||||
_logoutInProgress = true;
|
||||
return OctoPrint.browser.logout()
|
||||
.done(function(response) {
|
||||
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
|
||||
@@ -145,6 +183,9 @@ $(function() {
|
||||
if (error && error.status === 401) {
|
||||
self.fromResponse(false);
|
||||
}
|
||||
})
|
||||
.always(function() {
|
||||
_logoutInProgress = false;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -155,6 +196,14 @@ $(function() {
|
||||
self.login();
|
||||
};
|
||||
|
||||
self.onDataUpdaterReauthRequired = function(reason) {
|
||||
if (reason === "logout" || reason === "removed") {
|
||||
self.logout();
|
||||
} else {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.allViewModels = allViewModels;
|
||||
self.startupDeferred.resolve();
|
||||
@@ -198,6 +247,105 @@ $(function() {
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
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;
|
||||
|
||||
if ($.isEmptyObject(userneeds)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return _.any(permission, function(need) {
|
||||
return _.has(userneeds, need.method) && _.all(need.value, function(value) {
|
||||
return _.contains(userneeds[need.method], value);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
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" });
|
||||
};
|
||||
|
||||
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);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -7,6 +7,7 @@ $(function() {
|
||||
self.settings = parameters[2];
|
||||
self.usersettings = parameters[3];
|
||||
self.system = parameters[4];
|
||||
self.access = parameters[5];
|
||||
|
||||
self.appearanceClasses = ko.pureComputed(function() {
|
||||
var classes = self.appearance.color();
|
||||
@@ -20,7 +21,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: NavigationViewModel,
|
||||
dependencies: ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel", "systemViewModel"],
|
||||
dependencies: ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel", "systemViewModel", "accessViewModel"],
|
||||
elements: ["#navbar"]
|
||||
});
|
||||
});
|
||||
@@ -396,9 +396,12 @@ $(function() {
|
||||
self.fromProfileData(cleanProfile());
|
||||
}
|
||||
|
||||
function PrinterProfilesViewModel() {
|
||||
function PrinterProfilesViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.requestInProgress = ko.observable(false);
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
@@ -453,6 +456,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return OctoPrint.printerprofiles.list()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
@@ -594,10 +601,14 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onSettingsShown = self.requestData;
|
||||
self.onStartup = self.requestData;
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterProfilesViewModel
|
||||
construct: PrinterProfilesViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.stateString = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
@@ -18,13 +19,27 @@ $(function() {
|
||||
self.isSdReady = ko.observable(undefined);
|
||||
|
||||
self.enablePrint = ko.pureComputed(function() {
|
||||
return self.isOperational() && self.isReady() && !self.isPrinting() && !self.isCancelling() && !self.isPausing() && self.loginState.isUser() && self.filename() != undefined;
|
||||
return self.isOperational() &&
|
||||
self.isReady() &&
|
||||
!self.isPrinting() &&
|
||||
!self.isCancelling() &&
|
||||
!self.isPausing() &&
|
||||
self.loginState.hasPermission(self.access.permissions.PRINT) &&
|
||||
self.filename() !== undefined;
|
||||
});
|
||||
self.enablePause = ko.pureComputed(function() {
|
||||
return self.isOperational() && (self.isPrinting() || self.isPaused()) && !self.isCancelling() && !self.isPausing() && self.loginState.isUser();
|
||||
return self.isOperational() &&
|
||||
(self.isPrinting() || self.isPaused()) &&
|
||||
!self.isCancelling() &&
|
||||
!self.isPausing() &&
|
||||
self.loginState.hasPermission(self.access.permissions.PRINT);
|
||||
});
|
||||
self.enableCancel = ko.pureComputed(function() {
|
||||
return self.isOperational() && (self.isPrinting() || self.isPaused()) && !self.isCancelling() && !self.isPausing() && self.loginState.isUser();
|
||||
return self.isOperational() &&
|
||||
(self.isPrinting() || self.isPaused()) &&
|
||||
!self.isCancelling() &&
|
||||
!self.isPausing() &&
|
||||
self.loginState.loggedIn();
|
||||
});
|
||||
|
||||
self.filename = ko.observable(undefined);
|
||||
@@ -80,7 +95,7 @@ $(function() {
|
||||
return formatDuration(self.printTime());
|
||||
});
|
||||
self.printTimeLeftString = ko.pureComputed(function() {
|
||||
if (self.printTimeLeft() == undefined) {
|
||||
if (self.printTimeLeft() === undefined) {
|
||||
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
|
||||
return "-";
|
||||
} else {
|
||||
@@ -159,9 +174,9 @@ $(function() {
|
||||
return "-";
|
||||
|
||||
var type = timelapse["type"];
|
||||
if (type == "zchange") {
|
||||
if (type === "zchange") {
|
||||
return gettext("On Z Change");
|
||||
} else if (type == "timed") {
|
||||
} else if (type === "timed") {
|
||||
return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")";
|
||||
} else {
|
||||
return "-";
|
||||
@@ -208,7 +223,7 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
|
||||
if (self.isPaused() != prevPaused) {
|
||||
if (self.isPaused() !== prevPaused) {
|
||||
if (self.isPaused()) {
|
||||
self.titlePrintButton(self.TITLE_PRINT_BUTTON_PAUSED);
|
||||
self.titlePauseButton(self.TITLE_PAUSE_BUTTON_PAUSED);
|
||||
@@ -225,7 +240,7 @@ $(function() {
|
||||
self.filepath(data.file.path);
|
||||
self.filesize(data.file.size);
|
||||
self.filedisplay(data.file.display);
|
||||
self.sd(data.file.origin == "sdcard");
|
||||
self.sd(data.file.origin === "sdcard");
|
||||
} else {
|
||||
self.filename(undefined);
|
||||
self.filepath(undefined);
|
||||
@@ -238,7 +253,7 @@ $(function() {
|
||||
self.lastPrintTime(data.lastPrintTime);
|
||||
|
||||
var result = [];
|
||||
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
|
||||
if (data.filament && typeof(data.filament) === "object" && _.keys(data.filament).length > 0) {
|
||||
var keys = _.keys(data.filament);
|
||||
keys.sort();
|
||||
_.each(keys, function(key) {
|
||||
@@ -324,7 +339,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterStateViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#state_wrapper", "#drop_overlay"]
|
||||
});
|
||||
});
|
||||
@@ -3,10 +3,13 @@ $(function() {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.users = parameters[1];
|
||||
self.access = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
self.about = parameters[3];
|
||||
|
||||
// TODO: remove in upcoming version, this is only for backwards compatibility
|
||||
self.users = parameters[4];
|
||||
|
||||
// use this promise to do certain things once the SettingsViewModel has processed
|
||||
// its first request
|
||||
var firstRequest = $.Deferred();
|
||||
@@ -105,6 +108,7 @@ $(function() {
|
||||
self.locale_languages = _.keys(AVAILABLE_LOCALES);
|
||||
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
self.api_keyEnforced = ko.observable(undefined);
|
||||
self.api_key = ko.observable(undefined);
|
||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||
|
||||
@@ -1023,22 +1027,16 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
// we might have other user rights now, refresh (but only if startup has fully completed)
|
||||
if (!self._startupComplete) return;
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
// we might have other user rights now, refresh (but only if startup has fully completed)
|
||||
if (!self._startupComplete) return;
|
||||
self.requestData();
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SettingsViewModel,
|
||||
dependencies: ["loginStateViewModel", "usersViewModel", "printerProfilesViewModel", "aboutViewModel"],
|
||||
dependencies: ["loginStateViewModel", "accessViewModel", "printerProfilesViewModel", "aboutViewModel", "usersViewModel"],
|
||||
elements: ["#settings_dialog", "#navbar_settings"]
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.printerProfiles = parameters[1];
|
||||
self.printerState = parameters[2];
|
||||
self.access = parameters[3];
|
||||
|
||||
self.file = ko.observable(undefined);
|
||||
self.target = undefined;
|
||||
@@ -193,6 +194,10 @@ $(function() {
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SLICING)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return OctoPrint.slicing.listAllSlicersAndProfiles()
|
||||
.done(function(data) {
|
||||
self.fromResponse(data);
|
||||
@@ -300,7 +305,7 @@ $(function() {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
@@ -315,7 +320,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SlicingViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerProfilesViewModel", "printerStateViewModel"],
|
||||
dependencies: ["loginStateViewModel", "printerProfilesViewModel", "printerStateViewModel", "accessViewModel"],
|
||||
elements: ["#slicing_configuration_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ $(function() {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.lastCommandResponse = undefined;
|
||||
self.systemActions = ko.observableArray([]);
|
||||
@@ -12,7 +13,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestCommandData = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
return $.Deferred().reject().promise();
|
||||
}
|
||||
|
||||
@@ -42,6 +43,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.triggerCommand = function(commandSpec) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
return $.Deferred().reject().promise();
|
||||
}
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var callback = function() {
|
||||
@@ -90,21 +95,17 @@ $(function() {
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
if (user.admin) {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function(user) {
|
||||
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
self.requestData();
|
||||
} else {
|
||||
self.onUserLoggedOut();
|
||||
self.lastCommandResponse = undefined;
|
||||
self.systemActions([]);
|
||||
}
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.lastCommandResponse = undefined;
|
||||
self.systemActions([]);
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
if (self.loginState.isAdmin()) {
|
||||
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
@@ -112,6 +113,6 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SystemViewModel,
|
||||
dependencies: ["loginStateViewModel"]
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self._createToolEntry = function() {
|
||||
var entry = {
|
||||
@@ -67,6 +68,9 @@ $(function() {
|
||||
};
|
||||
self.changeOffsetDialog = undefined;
|
||||
|
||||
// TODO: find some nicer way to update plot AFTER graph becomes visible
|
||||
self.loginStateSubscription = undefined;
|
||||
|
||||
self.tools = ko.observableArray([]);
|
||||
|
||||
self.hasBed = ko.observable(true);
|
||||
@@ -144,6 +148,7 @@ $(function() {
|
||||
}
|
||||
self.updatePlot();
|
||||
};
|
||||
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
@@ -745,8 +750,9 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
if (current !== "#temp") {
|
||||
self.initOrUpdate = function() {
|
||||
if (OctoPrint.coreui.selectedTab !== "#temp" || !$("#temp").is(":visible")) {
|
||||
// do not try to initialize the graph when it's not visible or its sizing will be off
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -757,6 +763,10 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function() {
|
||||
self.initOrUpdate();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length && !OctoPrint.coreui.browser.mobile) {
|
||||
@@ -774,14 +784,19 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
self.initOrUpdate();
|
||||
self._printerProfileUpdated();
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.initOrUpdate();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: TemperatureViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#temp", "#change_offset_dialog"]
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#temp", "#temp_link", "#change_offset_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ $(function() {
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self.tabActive = false;
|
||||
|
||||
@@ -418,7 +419,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: TerminalViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel"],
|
||||
elements: ["#term"]
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
elements: ["#term", "#term_link"]
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ $(function() {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.timelapsePopup = undefined;
|
||||
|
||||
@@ -50,7 +51,7 @@ $(function() {
|
||||
return ("timed" === self.timelapseType());
|
||||
});
|
||||
self.saveButtonEnabled = ko.pureComputed(function() {
|
||||
return self.isDirty() && !self.isPrinting() && self.loginState.isUser();
|
||||
return self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN) && self.isDirty() && self.isOperational() && !self.isPrinting();
|
||||
});
|
||||
self.resetButtonEnabled = ko.pureComputed(function() {
|
||||
return self.saveButtonEnabled() && self.serverConfig() !== undefined;
|
||||
@@ -141,6 +142,9 @@ $(function() {
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_LIST))
|
||||
return;
|
||||
|
||||
OctoPrint.timelapse.get(true)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
@@ -230,6 +234,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
OctoPrint.timelapse.delete(filename)
|
||||
.done(function() {
|
||||
@@ -253,6 +260,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForFileDeletion(), "files")
|
||||
.done(function() {
|
||||
@@ -277,6 +287,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeUnrendered = function(name) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
OctoPrint.timelapse.deleteUnrendered(name)
|
||||
.done(function() {
|
||||
@@ -290,6 +303,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeMarkedUnrendered = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForUnrenderedDeletion(), "unrendered")
|
||||
.done(function() {
|
||||
@@ -361,11 +377,17 @@ $(function() {
|
||||
};
|
||||
|
||||
self.renderUnrendered = function(name) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN))
|
||||
return;
|
||||
|
||||
OctoPrint.timelapse.renderUnrendered(name)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.save = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN))
|
||||
return;
|
||||
|
||||
var payload = {
|
||||
"type": self.timelapseType(),
|
||||
"postRoll": self.timelapsePostRoll(),
|
||||
@@ -516,14 +538,14 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: TimelapseViewModel,
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#timelapse"]
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#timelapse", "#timelapse_link"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
$(function() {
|
||||
function UiStateViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.loading = ko.observable(true);
|
||||
self.needlogin = ko.computed(function() {
|
||||
return !self.loading() && !self.loginState.hasPermissionKo(self.access.permissions.STATUS)();
|
||||
});
|
||||
self.visible = ko.pureComputed(function() {
|
||||
return !self.loading() && !self.needlogin();
|
||||
});
|
||||
|
||||
self.login_username = ko.observable();
|
||||
self.login_password = ko.observable();
|
||||
self.login_remember = ko.observable(false);
|
||||
self.login_error = ko.observable(false);
|
||||
|
||||
self.login = function() {
|
||||
self.login_error(false);
|
||||
self.loginState.login(self.login_username(), self.login_password(), self.login_remember(), false)
|
||||
.done(function() {
|
||||
self.login_username(undefined);
|
||||
self.login_password(undefined);
|
||||
})
|
||||
.fail(function(response) {
|
||||
switch(response.status) {
|
||||
case 401: {
|
||||
self.login_error(gettext("User unknown or wrong password"));
|
||||
break;
|
||||
}
|
||||
case 403: {
|
||||
self.login_error(gettext("Your account is deactivated"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UiStateViewModel,
|
||||
["loginStateViewModel", "accessViewModel"],
|
||||
["#page-container-main", "#page-container-loading", "#page-container-needlogin"]
|
||||
]);
|
||||
});
|
||||
@@ -2,249 +2,77 @@ $(function() {
|
||||
function UsersViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[0];
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"users",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_USERSPERPAGE
|
||||
);
|
||||
|
||||
self.emptyUser = {name: "", admin: false, active: false};
|
||||
|
||||
self.currentUser = ko.observable(self.emptyUser);
|
||||
|
||||
self.editorUsername = ko.observable(undefined);
|
||||
self.editorPassword = ko.observable(undefined);
|
||||
self.editorRepeatedPassword = ko.observable(undefined);
|
||||
self.editorApikey = ko.observable(undefined);
|
||||
self.editorAdmin = ko.observable(undefined);
|
||||
self.editorActive = ko.observable(undefined);
|
||||
|
||||
self.addUserDialog = undefined;
|
||||
self.editUserDialog = undefined;
|
||||
self.changePasswordDialog = undefined;
|
||||
|
||||
self.currentUser.subscribe(function(newValue) {
|
||||
if (newValue === undefined) {
|
||||
self.editorUsername(undefined);
|
||||
self.editorAdmin(undefined);
|
||||
self.editorActive(undefined);
|
||||
self.editorApikey(undefined);
|
||||
} else {
|
||||
self.editorUsername(newValue.name);
|
||||
self.editorAdmin(newValue.admin);
|
||||
self.editorActive(newValue.active);
|
||||
self.editorApikey(newValue.apikey);
|
||||
self.deprecatedUsersMethod = function(oldFct) {
|
||||
var newFct = oldFct;
|
||||
if (arguments.length === 2) {
|
||||
newFct = arguments[1];
|
||||
}
|
||||
self.editorPassword(undefined);
|
||||
self.editorRepeatedPassword(undefined);
|
||||
});
|
||||
|
||||
self.editorPasswordMismatch = ko.pureComputed(function() {
|
||||
return self.editorPassword() !== self.editorRepeatedPassword();
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
OctoPrint.users.list()
|
||||
.done(self.fromResponse);
|
||||
OctoPrintClient.deprecatedMethod(self, "UsersViewModel", oldFct, "AccessViewModel.users", newFct, function() {
|
||||
self.access.users[newFct](this.arguments);
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.listHelper.updateItems(response.users);
|
||||
self.deprecatedUsersVariable = function(oldVar) {
|
||||
var newVar = oldVar;
|
||||
if (arguments.length === 2) {
|
||||
newVar = arguments[1];
|
||||
}
|
||||
|
||||
OctoPrintClient.deprecatedVariable(self, "UsersViewModel", oldVar, "AccessViewModel.users", newVar,
|
||||
function() {
|
||||
return self.access.users[newVar];
|
||||
},
|
||||
function(val) {
|
||||
self.access.users[newVar] = val;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
self.showAddUserDialog = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
// initialize deprecated Variables
|
||||
self.deprecatedUsersVariable("listHelper");
|
||||
|
||||
self.currentUser(undefined);
|
||||
self.editorActive(true);
|
||||
self.addUserDialog.modal("show");
|
||||
};
|
||||
self.deprecatedUsersVariable("emptyUser");
|
||||
|
||||
self.confirmAddUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
self.deprecatedUsersVariable("currentUser");
|
||||
|
||||
var user = {
|
||||
name: self.editorUsername(),
|
||||
password: self.editorPassword(),
|
||||
admin: self.editorAdmin(),
|
||||
active: self.editorActive()
|
||||
};
|
||||
self.deprecatedUsersVariable("editorUsername");
|
||||
self.deprecatedUsersVariable("editorGroups");
|
||||
self.deprecatedUsersVariable("editorPermissions");
|
||||
self.deprecatedUsersVariable("editorPassword");
|
||||
self.deprecatedUsersVariable("editorRepeatedPassword");
|
||||
self.deprecatedUsersVariable("editorApikey");
|
||||
self.deprecatedUsersVariable("editorActive");
|
||||
|
||||
self.addUser(user)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.addUserDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
self.deprecatedUsersVariable("editorPasswordMismatch");
|
||||
|
||||
self.showEditUserDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var process = function(user) {
|
||||
self.currentUser(user);
|
||||
self.editUserDialog.modal("show");
|
||||
};
|
||||
|
||||
// make sure we have the current user data, see #2534
|
||||
OctoPrint.users.get(user.name)
|
||||
.done(function(data) {
|
||||
process(data);
|
||||
})
|
||||
.fail(function() {
|
||||
log.warn("Could not fetch current user data, proceeding with client side data copy");
|
||||
process(user);
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmEditUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = self.currentUser();
|
||||
user.active = self.editorActive();
|
||||
user.admin = self.editorAdmin();
|
||||
|
||||
self.updateUser(user)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.editUserDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showChangePasswordDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
self.changePasswordDialog.modal("show");
|
||||
};
|
||||
|
||||
self.confirmChangePassword = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.updatePassword(self.currentUser().name, self.editorPassword())
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.changePasswordDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmGenerateApikey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.generateApikey(self.currentUser().name)
|
||||
.done(function(response) {
|
||||
self._updateApikey(response.apikey);
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmDeleteApikey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.deleteApikey(self.currentUser().name)
|
||||
.done(function() {
|
||||
self._updateApikey(undefined);
|
||||
});
|
||||
};
|
||||
|
||||
self.copyApikey = function() {
|
||||
copyToClipboard(self.editorApikey());
|
||||
};
|
||||
|
||||
self._updateApikey = function(apikey) {
|
||||
self.editorApikey(apikey);
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
//~~ Framework
|
||||
|
||||
self.onStartup = function() {
|
||||
self.addUserDialog = $("#settings-usersDialogAddUser");
|
||||
self.editUserDialog = $("#settings-usersDialogEditUser");
|
||||
self.changePasswordDialog = $("#settings-usersDialogChangePassword");
|
||||
};
|
||||
self.deprecatedUsersMethod("requestData");
|
||||
self.deprecatedUsersMethod("fromResponse");
|
||||
self.deprecatedUsersMethod("showAddUserDialog");
|
||||
self.deprecatedUsersMethod("confirmAddUser");
|
||||
self.deprecatedUsersMethod("showEditUserDialog");
|
||||
self.deprecatedUsersMethod("confirmEditUser");
|
||||
self.deprecatedUsersMethod("showChangePasswordDialog");
|
||||
self.deprecatedUsersMethod("confirmChangePassword");
|
||||
self.deprecatedUsersMethod("confirmGenerateApikey");
|
||||
self.deprecatedUsersMethod("copyApikey");
|
||||
self.deprecatedUsersMethod("confirmDeleteApikey");
|
||||
self.deprecatedUsersMethod("_updateApikey");
|
||||
|
||||
//~~ API calls
|
||||
|
||||
self.addUser = function(user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
if (!self.loginState.isAdmin()) return $.Deferred().reject("You are not authorized to perform this action").promise();
|
||||
|
||||
return OctoPrint.users.add(user)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.removeUser = function(user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
if (!self.loginState.isAdmin()) return $.Deferred().reject("You are not authorized to perform this action").promise();
|
||||
|
||||
if (user.name === self.loginState.username()) {
|
||||
// we do not allow to delete ourselves
|
||||
new PNotify({
|
||||
title: gettext("Not possible"),
|
||||
text: gettext("You may not delete your own account."),
|
||||
type: "error"
|
||||
});
|
||||
return $.Deferred().reject("You may not delete your own account").promise();
|
||||
}
|
||||
|
||||
return OctoPrint.users.delete(user.name)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.updateUser = function(user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.users.update(user.name, user.active, user.admin)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.updatePassword = function(username, password) {
|
||||
return OctoPrint.users.changePassword(username, password);
|
||||
};
|
||||
|
||||
self.generateApikey = function(username) {
|
||||
return OctoPrint.users.generateApiKey(username)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
|
||||
self.deleteApikey = function(username) {
|
||||
return OctoPrint.users.resetApiKey(username);
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
self.requestData();
|
||||
}
|
||||
self.deprecatedUsersMethod("addUser");
|
||||
self.deprecatedUsersMethod("removeUser");
|
||||
self.deprecatedUsersMethod("updateUser");
|
||||
self.deprecatedUsersMethod("updatePassword");
|
||||
self.deprecatedUsersMethod("generateApikey");
|
||||
self.deprecatedUsersMethod("deleteApikey");
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: UsersViewModel,
|
||||
dependencies: ["loginStateViewModel"]
|
||||
dependencies: ["accessViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,9 @@ $(function() {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.users = parameters[1];
|
||||
self.access = parameters[1];
|
||||
|
||||
self.users = self.access.users;
|
||||
|
||||
self.userSettingsDialog = undefined;
|
||||
|
||||
@@ -50,7 +52,7 @@ $(function() {
|
||||
};
|
||||
|
||||
// make sure we have the current user data, see #2534
|
||||
OctoPrint.users.get(user.name)
|
||||
OctoPrint.access.users.get(user.name)
|
||||
.done(function(data) {
|
||||
process(data);
|
||||
})
|
||||
@@ -116,7 +118,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.updateSettings = function(username, settings) {
|
||||
return OctoPrint.users.saveSettings(username, settings);
|
||||
return OctoPrint.access.users.saveSettings(username, settings);
|
||||
};
|
||||
|
||||
self.saveEnabled = function() {
|
||||
@@ -140,7 +142,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: UserSettingsViewModel,
|
||||
dependencies: ["loginStateViewModel", "usersViewModel"],
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#usersettings_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -352,18 +352,58 @@ table {
|
||||
&.settings_users_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
&.settings_users_active, &.settings_users_admin {
|
||||
&.settings_users_active {
|
||||
text-align: center;
|
||||
width: 55px;
|
||||
}
|
||||
|
||||
&.settings_users_actions {
|
||||
table.settings_users_details_table {
|
||||
font-size: 0.8em;
|
||||
margin-bottom: 0;
|
||||
|
||||
.settings_users_details_key {
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
&.settings_groups_default {
|
||||
text-align: center;
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
&.settings_groups_name {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
&.settings_users_actions,
|
||||
&.settings_groups_actions {
|
||||
width: 60px;
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
&.settings_accesscontrol_permissions_list_checkbox {
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
&.settings_accesscontrol_groups_list_checkbox {
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
#settings-usersDialogAddUser, #settings-usersDialogEditUser {
|
||||
position: relative;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
margin-top: 0 !important;
|
||||
}
|
||||
|
||||
// Printer profiles
|
||||
&.settings_printerProfiles_profiles_name {
|
||||
text-overflow: ellipsis;
|
||||
@@ -379,6 +419,7 @@ table {
|
||||
width: 80px;
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1436,3 +1477,68 @@ input[type="number"].input-nospin {
|
||||
margin-top: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
// page wide login form
|
||||
#page-container-needlogin {
|
||||
background-color: #ffffff;
|
||||
z-index: 12300;
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 50px auto;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// loading overlay
|
||||
#page-container-loading {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #ffffff;
|
||||
z-index: 12301;
|
||||
|
||||
.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,155 +1,16 @@
|
||||
<table class="table table-condensed table-hover" id="system_users">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_users_name">{{ _('Name') }}</th>
|
||||
<th class="settings_users_active">{{ _('Active') }}</th>
|
||||
<th class="settings_users_admin">{{ _('Admin') }}</th>
|
||||
<th class="settings_users_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: users.listHelper.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(apikey) }"><i class="fa fa-copy"></i></a></small></span></td>
|
||||
<td class="settings_users_active"><i class="fa" data-bind="css: { 'fa-check-square-o': active, 'fa-square-o': !active }"></i></td>
|
||||
<td class="settings_users_admin"><i class="fa" data-bind="css: { 'fa-check-square-o': admin, 'fa-square-o': !admin }"></i></td>
|
||||
<td class="settings_users_actions">
|
||||
<a href="#" class="fa fa-pencil" title="{{ _('Update User') }}" data-bind="click: function() { $root.users.showEditUserDialog($data); }"></a> | <a href="#" class="fa fa-key" title="{{ _('Change password') }}" data-bind="click: function() { $root.users.showChangePasswordDialog($data); }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Delete user') }}" data-bind="click: function() { $root.users.removeUser($data); }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: users.listHelper.currentPage() === 0}"><a href="#" data-bind="click: users.listHelper.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: users.listHelper.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.users.listHelper.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.users.listHelper.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: users.listHelper.currentPage() === users.listHelper.lastPage()}"><a href="#" data-bind="click: users.listHelper.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button title="Add user" class="btn" data-bind="click: $root.users.showAddUserDialog"><i class="fa fa-plus"></i> {{ _('Add user') }}</button>
|
||||
|
||||
<!-- Modals for user management -->
|
||||
|
||||
<div id="settings-usersDialogAddUser" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Add user') }}</h3>
|
||||
<ul class="nav nav-pills">
|
||||
<li id="settings_accesscontrol_users_link" class="active">
|
||||
<a href="#settings_accesscontrol_users" data-toggle="tab">{{ _('Users') }}</a>
|
||||
</li>
|
||||
<li id="settings_accesscontrol_groups_link">
|
||||
<a href="#settings_accesscontrol_groups" data-toggle="tab">{{ _('Groups') }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content">
|
||||
<div id="settings_accesscontrol_users" class="tab-pane active">
|
||||
{% include 'snippets/settings/accesscontrol/users.jinja2' %}
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogAddUserName">{{ _('Username') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-usersDialogAddUserName" data-bind="value: $root.users.editorUsername" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogAddUserPassword1">{{ _('Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword1" data-bind="value: $root.users.editorPassword" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: $root.users.editorPasswordMismatch()}">
|
||||
<label class="control-label" for="settings-usersDialogAddUserPassword2">{{ _('Repeat Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword2" data-bind="value: $root.users.editorRepeatedPassword, valueUpdate: 'afterkeydown'" required>
|
||||
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogAddUserActive" data-bind="checked: $root.users.editorActive"> {{ _('Active') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogAddUserAdmin" data-bind="checked: $root.users.editorAdmin"> {{ _('Admin') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmAddUser(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings-usersDialogEditUser" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Edit user "%(user)s"', user = '<span data-bind="text: $root.users.editorUsername"></span>') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogEditUserActive" data-bind="checked: $root.users.editorActive"> {{ _('Active') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogEditUserAdmin" data-bind="checked: $root.users.editorAdmin"> {{ _('Admin') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmEditUser(); }">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings-usersDialogChangePassword" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Change password for user "%(user)s"', user='<span data-bind="text: $root.users.editorUsername"></span>') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogChangePasswordPassword1">{{ _('New Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword1" data-bind="value: $root.users.editorPassword" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: $root.users.editorPasswordMismatch()}">
|
||||
<label class="control-label" for="settings-usersDialogChangePasswordPassword2">{{ _('Repeat Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword2" data-bind="value: $root.users.editorRepeatedPassword, valueUpdate: 'afterkeydown'" required>
|
||||
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset data-bind="visible: api_enabled">
|
||||
<legend>Apikey</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Current API Key') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" readonly="readonly" data-bind="value: $root.users.editorApikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
|
||||
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: $root.users.copyApikey, enable: $root.users.editorApikey"><i class="fa fa-copy"></i></a>
|
||||
<a class="btn add-on" title="Generate new API Key" data-bind="click: function() { $root.users.confirmGenerateApikey(); }"><i class="fa fa-refresh"></i></a>
|
||||
<a class="btn add-on btn-danger" title="Delete API Key" data-bind="click: function() { $root.users.confirmDeleteApikey(); }"><i class="fa fa-trash-o"></i></a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
|
||||
<div id="settings_accesscontrol_groups" class="tab-pane">
|
||||
{% include 'snippets/settings/accesscontrol/groups.jinja2' %}
|
||||
</div>
|
||||
</div>
|
||||
@@ -6,6 +6,14 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiEnforcedKey" data-bind="checked: api_keyEnforced"> {{ _('Enforce key') }}
|
||||
</label>
|
||||
<span class="help-block">{{ _('If you check this, requests to any of OctoPrint\'s APIs without an API key will be denied instead of handled like an anonymous/not logged in user. This is OctoPrint\'s old default behaviour.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
|
||||
{% include "snippets/settings/printerprofiles/profiles.jinja2" %}
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }"><i class="fa fa-plus"></i> {{ _('Add Profile...') }}</button>
|
||||
|
||||
{% include "snippets/settings/printerprofiles/profileEditor.jinja2" %}
|
||||
@@ -14,7 +14,8 @@
|
||||
{% include 'initscript.jinja2' %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="page-container">
|
||||
<div class="page-container" id="page-container-main" style="display: none" data-bind="visible: visible">
|
||||
<!-- ko allowBindings: false -->
|
||||
<div id="navbar" class="navbar navbar-static-top">
|
||||
<div class="navbar-inner" data-bind="css: appearanceClasses">
|
||||
<div class="container">
|
||||
@@ -43,7 +44,7 @@
|
||||
<div class="row">
|
||||
<!-- Sidebar -->
|
||||
{% if templates.sidebar.order %}
|
||||
<div class="accordion {% if templates.tab.order %}span4{% else %}span12{% endif %}">
|
||||
<div id="sidebar" class="accordion {% if templates.tab.order %}span4{% else %}span12{% endif %}">
|
||||
{% for key in templates.sidebar.order %}
|
||||
{% set entry, data = templates.sidebar.entries[key] %}
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
|
||||
@@ -82,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 %}
|
||||
>
|
||||
@@ -146,7 +147,36 @@
|
||||
{% endfor %}
|
||||
<!-- End of generic plugin template files -->
|
||||
|
||||
{% include 'javascripts.jinja2' %}
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
|
||||
<div id="page-container-loading" data-bind="visible: loading">
|
||||
<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>
|
||||
|
||||
<div class="container" id="page-container-needlogin" style="display: none" data-bind="visible: needlogin">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
|
||||
|
||||
<div class="alert alert-error" style="display: none" data-bind="visible: login_error, text: login_error"></div>
|
||||
|
||||
<input type="text" data-bind="value: login_username" class="input-block-level" placeholder="{{ _('Username') }}">
|
||||
<input type="password" data-bind="value: login_password" class="input-block-level" placeholder="{{ _('Password') }}">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="value: login_remember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-large btn-primary" type="submit" data-bind="click: login">{{ _('Log in') }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% include 'javascripts.jinja2' %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -10,6 +10,7 @@
|
||||
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
|
||||
var CONFIG_LOGFILESPERPAGE = 10;
|
||||
var CONFIG_USERSPERPAGE = 10;
|
||||
var CONFIG_GROUPSPERPAGE = 10;
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}
|
||||
@@ -25,7 +26,9 @@
|
||||
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
||||
var SOCKJS_CLOSE_NORMAL = 1000;
|
||||
|
||||
// only needed if API keys are enforced, only provides anonymous access on its own
|
||||
var UI_API_KEY = "{{ uiApiKey|e }}";
|
||||
|
||||
var VERSION = "{{ version.number|e }}";
|
||||
var DISPLAY_VERSION = "{{ version.display|e }}";
|
||||
var BRANCH = "{{ version.branch|e }}";
|
||||
@@ -33,6 +36,8 @@
|
||||
var AVAILABLE_LOCALES = {{ locales|tojson }};
|
||||
var SUPPORTED_EXTENSIONS = {{ supportedExtensions|tojson }};
|
||||
|
||||
var PERMISSIONS = {{ permissions|tojson }};
|
||||
|
||||
var OCTOPRINT_VIEWMODELS = [];
|
||||
var ADDITIONAL_VIEWMODELS = [];
|
||||
var OCTOPRINT_ADDITIONAL_BINDINGS = [];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<div id="drop_overlay" data-bind="visible: loginState.isUser()">
|
||||
<div id="drop_overlay" data-bind="visible: loginState.hasPermissionKo(access.permissions.UPLOAD)">
|
||||
<div id="drop_overlay_background"></div>
|
||||
<div id="drop_overlay_wrapper">
|
||||
{% if enableSdSupport %}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Serial Port') }}</label>
|
||||
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
|
||||
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Baudrate') }}</label>
|
||||
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
|
||||
<label for="connection_printers" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Printer Profile') }}</label>
|
||||
<select id="connection_printers" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></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: isErrorOrClosed()"></select>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"> {{ _('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: isErrorOrClosed() && loginState.isUser()"> {{ _('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: connect, text: buttonText(), enable: loginState.isUser()">{{ _('Connect') }}</button>
|
||||
<button class="btn btn-block" id="printer_connect" data-bind="click: connect, text: buttonText">{{ _('Connect') }}</button>
|
||||
@@ -19,10 +19,10 @@
|
||||
<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="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="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="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="click: function() { if ($root.enablePrint($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enablePrint($data)}" title="{{ _('Load and Print') }}"><i class="fa fa-print"></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,9 +32,9 @@
|
||||
<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="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="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="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>
|
||||
<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,36 +43,36 @@
|
||||
<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="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.isUser">
|
||||
<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: function() { if ($root.loginState.isUser()) { $root.showAddFolderDialog(); } }, css: {disabled: !$root.loginState.isUser()}">
|
||||
<span class="btn addfolder-button span12" data-bind="click: $root.showAddFolderDialog">
|
||||
<i class="fa fa-folder"></i> {{ _('Create folder...') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="row-fluid upload-buttons">
|
||||
{% if enableSdSupport %}
|
||||
<span class="btn btn-primary fileinput-button span6" data-bind="enable: $root.loginState.isUser(), css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px">
|
||||
<span class="btn btn-primary fileinput-button span6" style="margin-bottom: 10px">
|
||||
<i class="fa fa-upload"></i>
|
||||
<span>{{ _('Upload') }}</span>
|
||||
<input id="gcode_upload" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
|
||||
<input id="gcode_upload" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button">
|
||||
</span>
|
||||
<span class="btn btn-primary fileinput-button span6" data-bind="enable: $root.loginState.isUser() && $root.isSdReady() && !$root.isPrinting(), css: {disabled: !$root.loginState.isUser() || !$root.isSdReady() || $root.isPrinting()}" style="margin-bottom: 10px">
|
||||
<span class="btn btn-primary fileinput-button span6" data-bind="enable: $root.isSdReady() && !$root.isPrinting(), css: {disabled: !$root.isSdReady() || $root.isPrinting()}" style="margin-bottom: 10px">
|
||||
<i class="fa fa-upload"></i>
|
||||
<span>{{ _('Upload to SD') }}</span>
|
||||
<input id="gcode_upload_sd" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser() && isSdReady() && !isPrinting()">
|
||||
<input id="gcode_upload_sd" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: isSdReady()">
|
||||
</span>
|
||||
{% else %}
|
||||
<span class="btn btn-primary fileinput-button span12" data-bind="enable: $root.loginState.isUser(), css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px">
|
||||
<i class="fa fa-upload"></i>
|
||||
<span class="btn btn-primary fileinput-button span12" style="margin-bottom: 10px">
|
||||
<i class="icon-upload-alt icon-white"></i>
|
||||
<span>{{ _('Upload') }}</span>
|
||||
<input id="gcode_upload" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
|
||||
<input id="gcode_upload" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button">
|
||||
</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row-fluid print-control" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div class="row-fluid print-control" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.PRINT)">
|
||||
<button class="btn btn-primary span4" data-bind="click: print, enable: enablePrint, css: {'btn-danger': isPaused()}, attr: {title: titlePrintButton}" id="job_print"><i class="fa" data-bind="css: {'fa-print': !isPaused(), 'fa-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? '{{ _('Restart') }}' : '{{ _('Print') }}')">{{ _('Print') }}</span></button>
|
||||
<button class="btn span4" id="job_pause" data-bind="click: function() { isPaused() ? onlyResume() : onlyPause(); }, enable: enablePause, css: {active: isPaused()}, attr: {title: titlePauseButton}"><i class="fa" data-bind="css: {'fa-pause': !isPaused(), 'fa-play': isPaused()}"></i> <span data-bind="visible: !isPaused()">{{ _('Pause') }}</span><span data-bind="visible: isPaused()">{{ _('Resume') }}</span></button>
|
||||
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: enableCancel" title="{{ _('Cancels the print job') }}"><i class="fa fa-stop"></i> {{ _('Cancel') }}</button>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<table class="table table-condensed table-hover settings_accesscontrol_groups_list">
|
||||
<tbody data-bind="foreach: groupsList()">
|
||||
<tr>
|
||||
<td class="settings_accesscontrol_groups_list_checkbox"><input type="checkbox" data-bind="checkedValue: key, checked: $parents[1].editor.groups, enable: toggleable"></td>
|
||||
<td class="settings_accesscontrol_groups_list_name" style="cursor: pointer" data-bind="click: function() { if ($data.toggleable) { $parents[1].editor.toggleGroup($data.key) } }, attr: {title: description}">
|
||||
<span class="name" data-bind="text: name, style: { fontWeight: ($parents[1].editor.groupSelected($data.name)) ? 'bold' : 'normal' }"></span> <small class="label label-info" data-bind="visible: !$data.toggleable" title="{{ _('Fixed groups can\'t be added or removed to users.') }}">{{ _('Fixed') }}</small><br>
|
||||
<small class="description" data-bind="text: description"></small><br>
|
||||
<small class="permissions muted" data-bind="text: $parents[1].editor.joinedGroupPermissions($data)"></small>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,78 @@
|
||||
<table class="table table-condensed table-hover" id="system_groups">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_groups_default"></th>
|
||||
<th class="settings_groups_name">{{ _('Name') }}</th>
|
||||
<th class="settings_groups_permissions">{{ _('Permissions') }}</th>
|
||||
<th class="settings_groups_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: $root.access.groups.listHelper.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_groups_default"><span class="fa fa-star" data-bind="invisible: !$data.default" title="{{ _('Default group') }}"></span></td>
|
||||
<td class="settings_groups_name">
|
||||
<span data-bind="text: name"></span><br>
|
||||
<small class="muted" data-bind="text: description"></small>
|
||||
</td>
|
||||
<td class="settings_groups_permissions"><small><span data-bind="text: $root.access.permissionList($data)"></span></small></td>
|
||||
<td class="settings_groups_actions">
|
||||
<a href="#" class="fa fa-pencil" title="{{ _('Update group') }}" data-bind="enable: changeable, css: {disabled: !changeable}, click: function() { $root.access.groups.showEditGroupDialog($data); }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Delete group') }}" data-bind="enable: removable, css: {disabled: !removable}, click: function() { $root.access.groups.removeGroup($data); }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: $root.access.groups.listHelper.currentPage() === 0}"><a href="#" data-bind="click: access.groups.listHelper.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: $root.access.groups.listHelper.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.access.groups.listHelper.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.access.groups.listHelper.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: $root.access.groups.listHelper.currentPage() === access.groups.listHelper.lastPage()}"><a href="#" data-bind="click: access.groups.listHelper.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button title="{{ _('Add group') }}" class="btn pull-right" data-bind="click: $root.access.groups.showAddGroupDialog"><i class="fa fa-plus"></i> {{ _('Add group...') }}</button>
|
||||
|
||||
<!-- Modals for group management -->
|
||||
|
||||
<div id="settings-groupsEditorDialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3 data-bind="text: $root.access.groups.editor.header"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-groupsDialogAddGroupName">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-groupsDialogAddGroupName" data-bind="disable: !$root.access.groups.editor.new(), textInput: $root.access.groups.editor.name" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-groupsDialogAddGroupDescription">{{ _('Description') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-groupsDialogAddGroupDescription" data-bind="value: $root.access.groups.editor.description">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-groupsDialogEditDefault" data-bind="checked: $root.access.groups.editor.default"> {{ _('Default') }}
|
||||
</label>
|
||||
<span class="help-block">{{ _('Marking a group as default will make it be pre selected when creating new users.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- ko with: $root.access.groups -->
|
||||
<!-- ko with: $root.access.permissions -->
|
||||
{% include 'snippets/settings/accesscontrol/permission_list.jinja2' %}
|
||||
<!-- /ko -->
|
||||
<!-- /ko -->
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="enable: $root.access.groups.editor.valid, click: function() { $root.access.groups.editor.confirm(); }">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<table class="table table-condensed table-hover settings_accesscontrol_permissions_list">
|
||||
<tbody data-bind="foreach: permissionList()">
|
||||
<tr>
|
||||
<td class="settings_accesscontrol_permissions_list_checkbox"><input type="checkbox" data-bind="checkedValue: key, checked: $parents[1].editor.permissions"></td>
|
||||
<td class="settings_accesscontrol_permissions_list_name" style="cursor: pointer" data-bind="click: function() { $parents[1].editor.togglePermission($data.key) }, attr: {title: description}">
|
||||
<span class="name" data-bind="text: name, style: { fontWeight: ($parents[1].editor.permissionSelected($data.key)) ? 'bold' : 'normal' }"></span> <span class="label label-info" data-bind="visible: typeof(plugin) !== 'undefined'">{{ _('Plugin') }}</span> <span class="label label-important" data-bind="visible: dangerous">{{ _('Warning') }}</span><br>
|
||||
<small class="description muted" data-bind="text: description"></small>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,174 @@
|
||||
<table class="table table-condensed table-hover" id="system_users">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_users_name">{{ _('Name') }}</th>
|
||||
<th class="settings_users_groups">{{ _('Details') }}</th>
|
||||
<th class="settings_users_active">{{ _('Active') }}</th>
|
||||
<th class="settings_users_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: $root.access.users.listHelper.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_users_name"><span data-bind="text: name"></span></td>
|
||||
<td class="settings_users_details">
|
||||
<table class="table settings_users_details_table">
|
||||
<tr>
|
||||
<th class="settings_users_details_key">{{ _('Groups') }}</th>
|
||||
<td class="settings_users_details_value" data-bind="text: $root.access.groupList($data)"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th class="settings_users_details_key">{{ _('Permissions') }}</th>
|
||||
<td class="settings_users_details_value" data-bind="text: $root.access.permissionList($data)"></td>
|
||||
</tr>
|
||||
<tr data-bind="visible: $root.api_enabled() && apikey">
|
||||
<th class="settings_users_details_key">{{ _('API Key') }}</th>
|
||||
<td class="settings_users_details_value"><span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(apikey) }"><i class="fa fa-copy"></i></a></td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
<td class="settings_users_active"><i class="fa" data-bind="css: { 'fa-check-square-o': active, 'fa-square-o': !active }"></i></td>
|
||||
<td class="settings_users_actions">
|
||||
<a href="#" class="fa fa-pencil" title="{{ _('Update User') }}" data-bind="click: function() { $root.access.users.showEditUserDialog($data); }"></a> | <a href="#" class="fa fa-key" title="{{ _('Change password') }}" data-bind="click: function() { $root.access.users.showChangePasswordDialog($data); }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Delete user') }}" data-bind="click: function() { $root.access.users.removeUser($data); }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: $root.access.users.listHelper.currentPage() === 0}"><a href="#" data-bind="click: access.users.listHelper.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: access.users.listHelper.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.access.users.listHelper.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.access.users.listHelper.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: $root.access.users.listHelper.currentPage() === access.users.listHelper.lastPage()}"><a href="#" data-bind="click: access.users.listHelper.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button title="{{ _('Add user') }}" class="btn pull-right" data-bind="click: $root.access.users.showAddUserDialog"><i class="fa fa-plus"></i> {{ _('Add user...') }}</button>
|
||||
|
||||
<!-- Modals for user management -->
|
||||
|
||||
<script type="text/html" id="users-group-template">
|
||||
<!-- ko foreach: $root.access.groups.groupsList() -->
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checkedValue: name, checked: $root.access.users.editor.groups"><span data-bind="text: name"></span><br>
|
||||
<span class="description" data-bind="text: description"></span>
|
||||
</label>
|
||||
<!-- /ko -->
|
||||
</script>
|
||||
|
||||
<div id="settings-usersEditorDialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3 data-bind="text: $root.access.users.editor.header"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="full-sized-box">
|
||||
<ul class="nav nav-pills">
|
||||
<li id="settings_accesscontrol_users_add_general_link" class="active">
|
||||
<a href="#settings_accesscontrol_users_add_general" data-toggle="tab">{{ _('General') }}</a>
|
||||
</li>
|
||||
<li id="settings_accesscontrol_users_add_groups_link">
|
||||
<a href="#settings_accesscontrol_users_add_groups" data-toggle="tab">{{ _('Groups') }}</a>
|
||||
</li>
|
||||
<li id="settings_accesscontrol_users_add_permissions_link">
|
||||
<a href="#settings_accesscontrol_users_add_permissions" data-toggle="tab">{{ _('Additional permissions') }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content">
|
||||
<div id="settings_accesscontrol_users_add_general" class="tab-pane active">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogAddUserName">{{ _('Username') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-usersDialogAddUserName" data-bind="disable: !$root.access.users.editor.new(), value: $root.access.users.editor.name" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="visible: $root.access.users.editor.new()">
|
||||
<label class="control-label" for="settings-usersDialogAddUserPassword1">{{ _('Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword1" data-bind="value: $root.access.users.editor.password" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: $root.access.users.editor.passwordMismatch()}, visible: $root.access.users.editor.new()">
|
||||
<label class="control-label" for="settings-usersDialogAddUserPassword2">{{ _('Repeat Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword2" data-bind="value: $root.access.users.editor.repeatedPassword, valueUpdate: 'afterkeydown'" required>
|
||||
<span class="help-inline" data-bind="visible: $root.access.users.editor.passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogAddUserActive" data-bind="checked: $root.access.users.editor.active"> {{ _('Active') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div id="settings_accesscontrol_users_add_groups" class="tab-pane">
|
||||
<!-- ko with: $root.access.users -->
|
||||
<!-- ko with: $root.access.groups -->
|
||||
{% include 'snippets/settings/accesscontrol/group_list.jinja2' %}
|
||||
<!-- /ko -->
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
<div id="settings_accesscontrol_users_add_permissions" class="tab-pane">
|
||||
<!-- ko with: $root.access.users -->
|
||||
<!-- ko with: $root.access.permissions -->
|
||||
{% include 'snippets/settings/accesscontrol/permission_list.jinja2' %}
|
||||
<!-- /ko -->
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.access.users.editor.confirm(); }, enable: $root.access.users.editor.valid">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings-usersDialogChangePassword" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Change password for user "%(user)s"', user='<span data-bind="text: $root.access.users.editor.name"></span>') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogChangePasswordPassword1">{{ _('New Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword1" data-bind="value: $root.access.users.editor.password" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: $root.access.users.editor.passwordMismatch()}">
|
||||
<label class="control-label" for="settings-usersDialogChangePasswordPassword2">{{ _('Repeat Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword2" data-bind="value: $root.access.users.editor.repeatedPassword, valueUpdate: 'afterkeydown'" required>
|
||||
<span class="help-inline" data-bind="visible: $root.access.users.editor.passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset data-bind="visible: api_enabled">
|
||||
<legend>Apikey</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Current API Key') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level ">
|
||||
<input type="text" readonly="readonly" data-bind="value: $root.access.users.editor.apikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
|
||||
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: $root.access.users.copyApikey, enable: $root.access.users.editor.apikey"><i class="fa fa-copy"></i></a>
|
||||
<a class="btn add-on" title="Generate new API Key" data-bind="click: function() { $root.access.users.confirmGenerateApikey(); }"><i class="fa fa-refresh"></i></a>
|
||||
<a class="btn add-on btn-danger" title="Delete API Key" data-bind="click: function() { $root.access.users.confirmDeleteApikey(); }"><i class="fa fa-trash-o"></i></a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.access.users.confirmChangePassword(); }, enable: !$root.access.users.editor.passwordMismatch()">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,5 +1,5 @@
|
||||
{% if webcamStream %}
|
||||
<div id="webcam_container" tabindex="0" data-bind="event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }">
|
||||
<div id="webcam_container" tabindex="0" data-bind="visible: loginState.hasPermissionKo(access.permissions.WEBCAM), event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }">
|
||||
<div class="nowebcam" data-bind="visible: !webcamLoaded()">
|
||||
<div class="text webcam_loading" data-bind="visible: !webcamLoaded() && !webcamError()">
|
||||
<p><strong>{{ _('Webcam stream loading...') }}</strong></p>
|
||||
@@ -34,38 +34,38 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="visible: keycontrolPossible">
|
||||
<div data-bind="visible: keycontrolPossible && loginState.hasPermissionKo(access.permissions.WEBCAM) && loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<small class="muted">{{ _("Hint: If you move your mouse over the picture, you enter keyboard control mode.") }}</small>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="jog-panel" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<!-- XY jogging control panel -->
|
||||
<div id="control-jog-xy" class="jog-panel">
|
||||
<h1>X/Y</h1>
|
||||
<div>
|
||||
<button id="control-yinc" class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('y',1) }"><i class="fa fa-arrow-up"></i></button>
|
||||
<button id="control-yinc" class="btn box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendJogCommand('y',1) }"><i class="fa fa-arrow-up"></i></button>
|
||||
</div>
|
||||
<div>
|
||||
<button id="control-xdec" class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('x',-1) }"><i class="fa fa-arrow-left"></i></button>
|
||||
<button id="control-xyhome" class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendHomeCommand(['x', 'y']) }"><i class="fa fa-home"></i></button>
|
||||
<button id="control-xinc" class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('x',1) }"><i class="fa fa-arrow-right"></i></button>
|
||||
<button id="control-xdec" class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendJogCommand('x',-1) }"><i class="fa fa-arrow-left"></i></button>
|
||||
<button id="control-xyhome" class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() , click: function() { $root.sendHomeCommand(['x', 'y']) }"><i class="fa fa-home"></i></button>
|
||||
<button id="control-xinc" class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendJogCommand('x',1) }"><i class="fa fa-arrow-right"></i></button>
|
||||
</div>
|
||||
<div>
|
||||
<button id="control-ydec" class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('y',-1) }"><i class="fa fa-arrow-down"></i></button>
|
||||
<button id="control-ydec" class="btn box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendJogCommand('y',-1) }"><i class="fa fa-arrow-down"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Z jogging control panel -->
|
||||
<div id="control-jog-z" class="jog-panel">
|
||||
<h1>Z</h1>
|
||||
<div>
|
||||
<button id="control-zinc" class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('z',1) }"><i class="fa fa-arrow-up"></i></button>
|
||||
<button id="control-zinc" class="btn box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendJogCommand('z',1) }"><i class="fa fa-arrow-up"></i></button>
|
||||
</div>
|
||||
<div>
|
||||
<button id="control-zhome" class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendHomeCommand(['z']) }"><i class="fa fa-home"></i></button>
|
||||
<button id="control-zhome" class="btn box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendHomeCommand(['z']) }"><i class="fa fa-home"></i></button>
|
||||
</div>
|
||||
<div>
|
||||
<button id="control-zdec" class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('z',-1) }"><i class="fa fa-arrow-down"></i></button>
|
||||
<button id="control-zdec" class="btn box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendJogCommand('z',-1) }"><i class="fa fa-arrow-down"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
<div class="distance">
|
||||
<div class="btn-group" data-toggle="buttons-radio" id="jog_distance">
|
||||
<!-- ko foreach: distances -->
|
||||
<button type="button" class="btn distance" data-bind="enable: $root.isOperational() && !$root.isPrinting() && $root.loginState.isUser(), text: $data, click: function() { $root.distance($data) }, css: { active: $root.distance() === $data }, attr: { id: 'control-distance' + $root.stripDistanceDecimal($data) }"></button>
|
||||
<button type="button" class="btn distance" data-bind="enable: $root.isOperational() && !$root.isPrinting(), text: $data, click: function() { $root.distance($data) }, css: { active: $root.distance() === $data }, attr: { id: 'control-distance' + $root.stripDistanceDecimal($data) }"></button>
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
</div>
|
||||
@@ -81,46 +81,46 @@
|
||||
<!-- Feed rate -->
|
||||
<div id="control-jog-feedrate" class="jog-panel">
|
||||
<input type="number" style="width: 153px" data-bind="slider: {min: 50, max: 150, step: 1, value: feedRate, tooltip: 'hide'}">
|
||||
<button class="btn btn-block" style="width: 169px" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendFeedRateCommand() }">{{ _('Feed rate:') }}<span data-bind="text: feedRate() + '%'"></span></button>
|
||||
<button class="btn btn-block" style="width: 169px" data-bind="enable: isOperational(), click: function() { $root.sendFeedRateCommand() }">{{ _('Feed rate:') }}<span data-bind="text: feedRate() + '%'"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Extrusion control panel -->
|
||||
<div id="control-jog-extrusion" class="jog-panel" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div id="control-jog-extrusion" class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<h1>Tool (E)</h1>
|
||||
<div>
|
||||
<div class="btn-group control-box">
|
||||
<button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: isOperational() && !isPrinting() && !isPaused() && loginState.isUser()">
|
||||
<button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: isOperational() && !isPrinting() && !isPaused()">
|
||||
{{ _('Select Tool...') }}
|
||||
<span class="caret"></span>
|
||||
</button>
|
||||
<ul class="dropdown-menu" data-bind="foreach: tools">
|
||||
<li><a href="#" data-bind="click: $root.sendSelectToolCommand, text: name(), enable: $root.isOperational() && !$root.isPrinting() && !$root.isPaused() && $root.loginState.isUser()"></a></li>
|
||||
<li><a href="#" data-bind="click: $root.sendSelectToolCommand, text: name(), enable: $root.isOperational() && !$root.isPrinting() && !$root.isPaused()"></a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="input-append control-box">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: extrusionAmount, enable: isOperational() && !isPrinting() && loginState.isUser(), attr: {placeholder: settings.printer_defaultExtrusionLength}">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: extrusionAmount, enable: isOperational() && !isPrinting(), attr: {placeholder: settings.printer_defaultExtrusionLength}">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendExtrudeCommand() }">{{ _('Extrude') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendRetractCommand() }">{{ _('Retract') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendExtrudeCommand() }">{{ _('Extrude') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendRetractCommand() }">{{ _('Retract') }}</button>
|
||||
|
||||
<!-- Flow rate -->
|
||||
<input style="width: 100px" type="number" data-bind="slider: {min: 75, max: 125, step: 1, value: flowRate, tooltip: 'hide'}">
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendFlowRateCommand() }">{{ _('Flow rate:') }}<span data-bind="text: flowRate() + '%'"></span></button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational(), click: function() { $root.sendFlowRateCommand() }">{{ _('Flow rate:') }}<span data-bind="text: flowRate() + '%'"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- General control panel -->
|
||||
<div id="control-jog-general" class="jog-panel" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div id="control-jog-general" class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<h1>{{ _('General') }}</h1>
|
||||
<div>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M18'}) }">{{ _('Motors off') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M106 S255'}) }">{{ _('Fan on') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M106 S0'}) }">{{ _('Fan off') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting(), click: function() { $root.sendCustomCommand({type:'command',command:'M18'}) }">{{ _('Motors off') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational(), click: function() { $root.sendCustomCommand({type:'command',command:'M106 S255'}) }">{{ _('Fan on') }}</button>
|
||||
<button class="btn btn-block control-box" data-bind="enable: isOperational(), click: function() { $root.sendCustomCommand({type:'command',command:'M106 S0'}) }">{{ _('Fan off') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Container for custom controls -->
|
||||
<div id="control-jog-custom" style="clear: both; display: none;" data-bind="visible: loginState.isUser, template: { name: $root.displayMode, foreach: controls }"></div>
|
||||
<div id="control-jog-custom" style="clear: both; display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL), template: { name: $root.displayMode, foreach: controls }"></div>
|
||||
|
||||
<!-- Templates for custom controls -->
|
||||
<script type="text/html" id="customControls_containerTemplate_nameless">
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{% if enableTemperatureGraph %}
|
||||
<div class="row-fluid">
|
||||
<div id="temperature-graph"></div>
|
||||
<div id="temperature-graph" style="width: 100%"></div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="row-fluid">
|
||||
|
||||
<table id="temperature-table" class="table table-bordered table-hover">
|
||||
<table id="temperature-table" class="table table-bordered table-hover" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<tr>
|
||||
<th class="temperature_tool"></th>
|
||||
<th class="temperature_actual" title="{{ _('Current actual temperature as reported by your printer') }}">{{ _('Actual') }}</th>
|
||||
@@ -24,14 +24,14 @@
|
||||
<td class="temperature_target">
|
||||
<form class="form-inline" style="margin:0" data-bind="submit: function(element) { $root.setTarget($data, element) }">
|
||||
<div class="input-prepend input-append">
|
||||
<button type="button" class="btn btn-input-dec" data-bind="click: $root.decrementTarget, enable: $root.isOperational() && $root.loginState.isUser()" title="{{ _('Fine adjust: -1°C') }}"><i class="fa fa-minus"></i></button>
|
||||
<input type="number" min="0" max="999" class="input-mini input-nospin" style="width: 30px" data-bind="attr: {placeholder: cleanTemperature(target())}, value: newTarget, valueUpdate: 'input', enable: $root.isOperational() && $root.loginState.isUser(), event: { focus: function(d, e) {$root.handleFocus(e, 'target', $data) } }">
|
||||
<button type="button" class="btn btn-input-dec" data-bind="click: $root.decrementTarget, enable: $root.isOperational() && $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)()" title="{{ _('Fine adjust: -1°C') }}"><i class="fa fa-minus"></i></button>
|
||||
<input type="number" min="0" max="999" class="input-mini input-nospin" style="width: 30px" data-bind="attr: {placeholder: cleanTemperature(target())}, value: newTarget, valueUpdate: 'input', enable: $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)() && $root.isOperational(), event: { focus: function(d, e) {$root.handleFocus(e, 'target', $data) } }">
|
||||
<span class="add-on">°C</span>
|
||||
<button type="button" class="btn btn-input-inc" data-bind="click: $root.incrementTarget, enable: $root.isOperational() && $root.loginState.isUser()" title="{{ _('Fine adjust: +1°C') }}"><i class="fa fa-plus"></i></button>
|
||||
<button type="button" class="btn btn-input-inc" data-bind="click: $root.incrementTarget, enable: $root.isOperational() && $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)()" title="{{ _('Fine adjust: +1°C') }}"><i class="fa fa-plus"></i></button>
|
||||
</div>
|
||||
<div class="btn-group">
|
||||
<button type="submit" data-bind="enable: $root.isOperational() && $root.loginState.isUser() && $data.newTargetValid()" class="btn btn-primary" title="{{ _('Set') }}"><i class="fa fa-check"></i></button>
|
||||
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.isUser()">
|
||||
<button type="submit" data-bind="enable: $root.loginState.hasPermissionKo($root.access.CONTROL)() && $root.isOperational() && $data.newTargetValid()" class="btn btn-primary" title="{{ _('Set') }}"><i class="fa fa-check"></i></button>
|
||||
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)()">
|
||||
<span class="caret"></span>
|
||||
</button>
|
||||
<ul class="dropdown-menu">
|
||||
@@ -53,8 +53,8 @@
|
||||
<div class="input-append">
|
||||
<span class="input-mini uneditable-input text-right" style="width: 30px" data-bind="text: offset"></span>
|
||||
<span class="add-on">°C</span>
|
||||
<button class="btn" title="{{ _('Change Offset') }}" data-bind="click: $root.changeOffset, enable: $root.isOperational() && $root.loginState.isUser()"><i class="fa fa-pencil"></i></button>
|
||||
<button class="btn" title="{{ _('Delete Offset') }}" data-bind="click: $root.setOffsetToZero, enable: $root.isOperational() && $root.loginState.isUser()"><i class="fa fa-trash"></i></button>
|
||||
<button class="btn" title="{{ _('Change Offset') }}" data-bind="click: $root.changeOffset, enable: $root.isOperational() && $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)()"><i class="fa fa-pencil"></i></button>
|
||||
<button class="btn" title="{{ _('Delete Offset') }}" data-bind="click: $root.setOffsetToZero, enable: $root.isOperational() && $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)()"><i class="fa fa-trash"></i></button>
|
||||
</div>
|
||||
</form>
|
||||
</td>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div class="terminal">
|
||||
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }, event: { scroll: terminalScrollEvent }"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
|
||||
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre>
|
||||
<div id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<div class="input-block-level input-append">
|
||||
<input type="text" id="terminal-command" data-bind="value: command, event: { keyup: function(d,e) { return handleKeyUp(e); }, keydown: function(d,e) { return handleKeyDown(e); } }, enable: isOperational() && loginState.isUser()" autocomplete="off">
|
||||
<a class="btn add-on" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</a>
|
||||
@@ -31,10 +31,10 @@
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#term .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div><small><a href="#" class="muted" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL), toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#term .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<p class="row-fluid">
|
||||
<button class="btn btn-primary btn-block" type="button" data-bind="click: fakeAck, enable: isOperational() && loginState.isUser()">{{ _("Fake Acknowledgement") }}</button>
|
||||
<button class="btn btn-primary btn-block" type="button" data-bind="click: fakeAck, enable: isOperational()">{{ _("Fake Acknowledgement") }}</button>
|
||||
<small class="muted">{{ _("If acknowledgements (\"ok\"s) sent by the firmware get lost due to issues with the serial communication to your printer, OctoPrint's communication with it can become stuck. If that happens, this can help. Please be advised that such occurrences hint at general communication issues with your printer which will probably negatively influence your printing results and which you should therefore try to resolve!") }}</small>
|
||||
</p>
|
||||
<p class="row-fluid">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<div style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_ADMIN)">
|
||||
<div class="alert" data-bind="visible: isPrinting()">
|
||||
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
|
||||
</div>
|
||||
@@ -9,7 +9,7 @@
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
|
||||
<div class="controls">
|
||||
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: !isPrinting() && loginState.isUser()">
|
||||
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: !isPrinting()">
|
||||
<option value="off">{{ _('Off') }}</option>
|
||||
<option value="timed">{{ _('Timed') }}</option>
|
||||
<option value="zchange">{{ _('On Z Change') }}</option>
|
||||
@@ -22,7 +22,7 @@
|
||||
<label class="control-label" for="webcam_timelapse_minDelay">{{ _('Minimum interval') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" min="1" class="input-mini" id="webcam_timelapse_minDelay" data-bind="value: timelapseMinDelay, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
|
||||
<input type="number" min="1" class="input-mini" id="webcam_timelapse_minDelay" data-bind="value: timelapseMinDelay, valueUpdate: 'afterkeydown', enable: !isPrinting()">
|
||||
<span class="add-on">{{ _('sec') }}</span>
|
||||
</div>
|
||||
<span class="help-block">{{ _('OctoPrint will rate limit snapshots to this minimum interval. This it to prevent against performance issues with vase mode/continous z prints.') }}</span>
|
||||
@@ -33,7 +33,7 @@
|
||||
<label class="control-label" for="webcam_timelapse_interval">{{ _('Snapshot interval') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" min="1" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
|
||||
<input type="number" min="1" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: !isPrinting()">
|
||||
<span class="add-on">{{ _('sec') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -43,7 +43,7 @@
|
||||
<label class="control-label" for="webcam_timelapse_fps">{{ _('Timelapse frame rate') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" min="1" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
|
||||
<input type="number" min="1" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: !isPrinting() && timelapseTypeSelected()">
|
||||
<span class="add-on">{{ _('fps') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -53,7 +53,7 @@
|
||||
<label class="control-label" for="webcam_timelapse_postRoll">{{ _('Timelapse post roll') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" min="0" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
|
||||
<input type="number" min="0" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: !isPrinting() && timelapseTypeSelected()">
|
||||
<span class="add-on">{{ _('sec') }}</span>
|
||||
</div>
|
||||
<span class="help-block">{{ _('OctoPrint will use the final picture to add this many seconds to the end of your rendered timelapse.') }}</span>
|
||||
@@ -64,17 +64,17 @@
|
||||
<label class="control-label" for="webcam_timelapse_retractionZHop">{{ _('Retraction Z-Hop') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" min="0.0" class="input-mini" id="webcam_timelapse_retractionZHop" data-bind="value: timelapseRetractionZHop, valueUpdate: 'afterkeydown', enable: !isPrinting() && loginState.isUser()">
|
||||
<input type="number" min="0.0" class="input-mini" id="webcam_timelapse_retractionZHop" data-bind="value: timelapseRetractionZHop, valueUpdate: 'afterkeydown', enable: !isPrinting()">
|
||||
<span class="add-on">{{ _('mm') }}</span>
|
||||
</div>
|
||||
<span class="help-block">{{ _('Enter the retraction z-hop used in the firmware or the gcode file to trigger snapshots for the timelapse only if a real layer change happens. For this to work properly your retraction z-hop has to be different from your layerheight!') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group" data-bind="visible: loginState.isAdmin">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: persist, enable: isOperational() && !isPrinting() && loginState.isUser()"> {{ _('Save as default') }}
|
||||
<input type="checkbox" data-bind="checked: persist, enable: isOperational() && !isPrinting()"> {{ _('Save as default') }}
|
||||
<span class="help-block">{{ _('Check this to make your selected timelapse mode and options persist across restarts.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
@@ -102,7 +102,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pull-left">
|
||||
<div class="pull-left" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
@@ -125,10 +125,10 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: listHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="timelapse_files_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForFileDeletion"></td>
|
||||
<td class="timelapse_files_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForFileDeletion, invisible: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)()"></td>
|
||||
<td class="timelapse_files_name" data-bind="text: name"></td>
|
||||
<td class="timelapse_files_size" data-bind="text: size"></td>
|
||||
<td class="timelapse_files_action"><a href="javascript:void(0)" class="fa fa-trash-o" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a> | <a href="javascript:void(0)" class="fa fa-download" data-bind="attr: {href: url}"></a></td>
|
||||
<td class="timelapse_files_action"><a href="javascript:void(0)" class="fa fa-trash-o" data-bind="click: function() { $parent.removeFile($data.name); }, css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)() }"></a> | <a href="javascript:void(0)" class="fa fa-download" data-bind="css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DOWNLOAD)()}, attr: { href: ($root.loginState.hasPermission($root.access.permissions.TIMELAPSE_DOWNLOAD)) ? $data.url : 'javascript:void(0)' }"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -144,10 +144,11 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: unrenderedListHelper.allSize">
|
||||
|
||||
<div data-bind="unrenderedListHelper.allSize">
|
||||
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="pull-left">
|
||||
<div class="pull-left" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
@@ -171,13 +172,13 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: unrenderedListHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="timelapse_unrendered_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForUnrenderedDeletion"></td>
|
||||
<td class="timelapse_unrendered_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForUnrenderedDeletion, invisible: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)()"></td>
|
||||
<td class="timelapse_unrendered_name" data-bind="text: name"></td>
|
||||
<td class="timelapse_unrendered_count" data-bind="text: count"></td>
|
||||
<td class="timelapse_unrendered_size" data-bind="text: size"></td>
|
||||
<td class="timelapse_unrendered_action">
|
||||
<span data-bind="visible: processing"><i class="fa fa-refresh fa-spin"></i></span>
|
||||
<span data-bind="visible: !processing"><a href="javascript:void(0)" title="{{ _('Delete unrendered timelapse') }}" class="fa fa-trash-o" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeUnrendered($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a> | <a href="javascript:void(0)" title="{{ _('Render timelapse') }}" class="fa fa-video-camera" data-bind="click: function() { if ($root.loginState.isUser() && !$root.isBusy()) { $parent.renderUnrendered($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser() || $root.isBusy()}"></a></span>
|
||||
<span data-bind="visible: !processing"><a href="javascript:void(0)" title="{{ _('Delete unrendered timelapse') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeUnrendered($data.name); }, css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)()}"></a> | <a href="javascript:void(0)" title="{{ _('Render timelapse') }}" class="fa fa-video-camera" data-bind="click: function() { if (!$root.isBusy()) { $parent.renderUnrendered($data.name); } else { return; } }, css: {disabled: $root.isBusy() || !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_ADMIN)()}"></a></span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -264,8 +264,11 @@ def register_callback(callback):
|
||||
|
||||
|
||||
def unregister_callback(callback):
|
||||
if callback in _update_callbacks:
|
||||
try:
|
||||
_update_callbacks.remove(callback)
|
||||
except ValueError:
|
||||
# not registered
|
||||
pass
|
||||
|
||||
|
||||
def notify_callbacks(timelapse):
|
||||
@@ -273,9 +276,19 @@ def notify_callbacks(timelapse):
|
||||
config = None
|
||||
else:
|
||||
config = timelapse.config_data()
|
||||
|
||||
for callback in _update_callbacks:
|
||||
try: callback.sendTimelapseConfig(config)
|
||||
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
|
||||
notify_callback(callback, config)
|
||||
|
||||
|
||||
def notify_callback(callback, config=None, timelapse=None):
|
||||
if config is None and timelapse is not None:
|
||||
config = timelapse.config_data()
|
||||
|
||||
try:
|
||||
callback.sendTimelapseConfig(config)
|
||||
except:
|
||||
logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
|
||||
|
||||
|
||||
def configure_timelapse(config=None, persist=False):
|
||||
|
||||
+17
-634
@@ -1,647 +1,30 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__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"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask_login import UserMixin, AnonymousUserMixin
|
||||
from flask_principal import Identity
|
||||
from werkzeug.local import LocalProxy
|
||||
import hashlib
|
||||
import os
|
||||
import yaml
|
||||
import uuid
|
||||
# Wrapper to the new access.users location
|
||||
|
||||
import wrapt
|
||||
from octoprint.access.users import *
|
||||
|
||||
import logging
|
||||
from builtins import range, bytes
|
||||
AccessUser = User
|
||||
|
||||
from octoprint.settings import settings
|
||||
import warnings
|
||||
warnings.warn("octoprint.users is deprecated, use octoprint.access.users instead", DeprecationWarning, stacklevel=2)
|
||||
|
||||
from octoprint.util import atomic_write, to_str, deprecated
|
||||
|
||||
class UserManager(object):
|
||||
valid_roles = ["user", "admin"]
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._session_users_by_session = dict()
|
||||
self._sessionids_by_userid = dict()
|
||||
self._enabled = True
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
return self._enabled
|
||||
|
||||
@enabled.setter
|
||||
def enabled(self, value):
|
||||
self._enabled = value
|
||||
|
||||
def enable(self):
|
||||
self._enabled = True
|
||||
|
||||
def disable(self):
|
||||
self._enabled = False
|
||||
|
||||
def login_user(self, user):
|
||||
self._cleanup_sessions()
|
||||
|
||||
if user is None:
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
user = user._get_current_object()
|
||||
|
||||
if not isinstance(user, User):
|
||||
return None
|
||||
|
||||
if not isinstance(user, SessionUser):
|
||||
user = SessionUser(user)
|
||||
|
||||
self._session_users_by_session[user.session] = user
|
||||
|
||||
userid = user.get_id()
|
||||
if not userid in self._sessionids_by_userid:
|
||||
self._sessionids_by_userid[userid] = set()
|
||||
|
||||
self._sessionids_by_userid[userid].add(user.session)
|
||||
|
||||
self._logger.debug("Logged in user: %r" % user)
|
||||
|
||||
return user
|
||||
|
||||
def logout_user(self, user):
|
||||
if user is None:
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
user = user._get_current_object()
|
||||
|
||||
if not isinstance(user, SessionUser):
|
||||
return
|
||||
|
||||
userid = user.get_id()
|
||||
sessionid = user.session
|
||||
|
||||
if userid in self._sessionids_by_userid:
|
||||
try:
|
||||
self._sessionids_by_userid[userid].remove(sessionid)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
if sessionid in self._session_users_by_session:
|
||||
del self._session_users_by_session[sessionid]
|
||||
|
||||
self._logger.debug("Logged out user: %r" % user)
|
||||
|
||||
def _cleanup_sessions(self):
|
||||
import time
|
||||
for session, user in self._session_users_by_session.items():
|
||||
if not isinstance(user, SessionUser):
|
||||
continue
|
||||
if user.created + (24 * 60 * 60) < time.time():
|
||||
self.logout_user(user)
|
||||
|
||||
@staticmethod
|
||||
def createPasswordHash(password, salt=None):
|
||||
if not salt:
|
||||
salt = settings().get(["accessControl", "salt"])
|
||||
if salt is None:
|
||||
import string
|
||||
from random import choice
|
||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
salt = "".join(choice(chars) for _ in range(32))
|
||||
settings().set(["accessControl", "salt"], salt)
|
||||
settings().save()
|
||||
|
||||
return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest()
|
||||
|
||||
def checkPassword(self, username, password):
|
||||
user = self.findUser(username)
|
||||
if not user:
|
||||
return False
|
||||
|
||||
hash = UserManager.createPasswordHash(password)
|
||||
if user.check_password(hash):
|
||||
# new hash matches, correct password
|
||||
return True
|
||||
else:
|
||||
# new hash doesn't match, but maybe the old one does, so check that!
|
||||
oldHash = UserManager.createPasswordHash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
|
||||
if user.check_password(oldHash):
|
||||
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
||||
self.changeUserPassword(username, password)
|
||||
return True
|
||||
else:
|
||||
# old hash doesn't match either, wrong password
|
||||
return False
|
||||
|
||||
def addUser(self, username, password, active, roles, overwrite=False):
|
||||
pass
|
||||
|
||||
def changeUserActivation(self, username, active):
|
||||
pass
|
||||
|
||||
def changeUserRoles(self, username, roles):
|
||||
pass
|
||||
|
||||
def addRolesToUser(self, username, roles):
|
||||
pass
|
||||
|
||||
def removeRolesFromUser(self, username, roles):
|
||||
pass
|
||||
|
||||
def changeUserPassword(self, username, password):
|
||||
pass
|
||||
|
||||
def getUserSetting(self, username, key):
|
||||
return None
|
||||
|
||||
def getAllUserSettings(self, username):
|
||||
return dict()
|
||||
|
||||
def changeUserSetting(self, username, key, value):
|
||||
pass
|
||||
|
||||
def changeUserSettings(self, username, new_settings):
|
||||
pass
|
||||
|
||||
def removeUser(self, username):
|
||||
if username in self._sessionids_by_userid:
|
||||
sessions = self._sessionids_by_userid[username]
|
||||
for session in sessions:
|
||||
if session in self._session_users_by_session:
|
||||
del self._session_users_by_session[session]
|
||||
del self._sessionids_by_userid[username]
|
||||
|
||||
def findUser(self, userid=None, session=None):
|
||||
if session is not None and session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
if userid is None or userid == user.get_id():
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
def getAllUsers(self):
|
||||
return []
|
||||
|
||||
def hasBeenCustomized(self):
|
||||
return False
|
||||
|
||||
##~~ FilebasedUserManager, takes available users from users.yaml file
|
||||
|
||||
class FilebasedUserManager(UserManager):
|
||||
def __init__(self):
|
||||
UserManager.__init__(self)
|
||||
|
||||
userfile = settings().get(["accessControl", "userfile"])
|
||||
if userfile is None:
|
||||
userfile = os.path.join(settings().getBaseFolder("base"), "users.yaml")
|
||||
self._userfile = userfile
|
||||
self._users = {}
|
||||
self._dirty = False
|
||||
|
||||
self._customized = None
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
if os.path.exists(self._userfile) and os.path.isfile(self._userfile):
|
||||
self._customized = True
|
||||
with open(self._userfile, "r") as f:
|
||||
data = yaml.safe_load(f)
|
||||
for name in data.keys():
|
||||
attributes = data[name]
|
||||
apikey = None
|
||||
if "apikey" in attributes:
|
||||
apikey = attributes["apikey"]
|
||||
settings = dict()
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
self._users[name] = User(name, attributes["password"], attributes["active"], attributes["roles"], apikey=apikey, settings=settings)
|
||||
for sessionid in self._sessionids_by_userid.get(name, set()):
|
||||
if sessionid in self._session_users_by_session:
|
||||
self._session_users_by_session[sessionid].update_user(self._users[name])
|
||||
else:
|
||||
self._customized = False
|
||||
|
||||
def _save(self, force=False):
|
||||
if not self._dirty and not force:
|
||||
return
|
||||
|
||||
data = {}
|
||||
for name in self._users.keys():
|
||||
user = self._users[name]
|
||||
data[name] = {
|
||||
"password": user._passwordHash,
|
||||
"active": user._active,
|
||||
"roles": user._roles,
|
||||
"apikey": user._apikey,
|
||||
"settings": user._settings
|
||||
}
|
||||
|
||||
with atomic_write(self._userfile, "wb", permissions=0o600, max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
def addUser(self, username, password, active=False, roles=None, apikey=None, overwrite=False):
|
||||
if not roles:
|
||||
roles = ["user"]
|
||||
|
||||
if username in self._users.keys() and not overwrite:
|
||||
raise UserAlreadyExists(username)
|
||||
|
||||
self._users[username] = User(username, UserManager.createPasswordHash(password), active, roles, apikey=apikey)
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def changeUserActivation(self, username, active):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
if self._users[username]._active != active:
|
||||
self._users[username]._active = active
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def changeUserRoles(self, username, roles):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
|
||||
removedRoles = set(user._roles) - set(roles)
|
||||
self.removeRolesFromUser(username, removedRoles)
|
||||
|
||||
addedRoles = set(roles) - set(user._roles)
|
||||
self.addRolesToUser(username, addedRoles)
|
||||
|
||||
def addRolesToUser(self, username, roles):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
for role in roles:
|
||||
if not role in user._roles:
|
||||
user._roles.append(role)
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def removeRolesFromUser(self, username, roles):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
for role in roles:
|
||||
if role in user._roles:
|
||||
user._roles.remove(role)
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def changeUserPassword(self, username, password):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
passwordHash = UserManager.createPasswordHash(password)
|
||||
user = self._users[username]
|
||||
if user._passwordHash != passwordHash:
|
||||
user._passwordHash = passwordHash
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def changeUserSetting(self, username, key, value):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
old_value = user.get_setting(key)
|
||||
if not old_value or old_value != value:
|
||||
user.set_setting(key, value)
|
||||
self._dirty = self._dirty or old_value != value
|
||||
self._save()
|
||||
|
||||
def changeUserSettings(self, username, new_settings):
|
||||
if not username in self._users:
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
for key, value in new_settings.items():
|
||||
old_value = user.get_setting(key)
|
||||
user.set_setting(key, value)
|
||||
self._dirty = self._dirty or old_value != value
|
||||
self._save()
|
||||
|
||||
def getAllUserSettings(self, username):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
return user.get_all_settings()
|
||||
|
||||
def getUserSetting(self, username, key):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
return user.get_setting(key)
|
||||
|
||||
def generateApiKey(self, username):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
user._apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
self._dirty = True
|
||||
self._save()
|
||||
return user._apikey
|
||||
|
||||
def deleteApikey(self, username):
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
user._apikey = None
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def removeUser(self, username):
|
||||
UserManager.removeUser(self, username)
|
||||
|
||||
if not username in self._users.keys():
|
||||
raise UnknownUser(username)
|
||||
|
||||
del self._users[username]
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def findUser(self, userid=None, apikey=None, session=None):
|
||||
user = UserManager.findUser(self, userid=userid, session=session)
|
||||
|
||||
if user is not None:
|
||||
return user
|
||||
|
||||
if userid is not None:
|
||||
if userid not in self._users.keys():
|
||||
return None
|
||||
return self._users[userid]
|
||||
|
||||
elif apikey is not None:
|
||||
for user in self._users.values():
|
||||
if apikey == user._apikey:
|
||||
return user
|
||||
return None
|
||||
|
||||
else:
|
||||
return None
|
||||
|
||||
def getAllUsers(self):
|
||||
return map(lambda x: x.asDict(), self._users.values())
|
||||
|
||||
def hasBeenCustomized(self):
|
||||
return self._customized
|
||||
|
||||
##~~ Exceptions
|
||||
|
||||
class UserAlreadyExists(Exception):
|
||||
def __init__(self, username):
|
||||
Exception.__init__(self, "User %s already exists" % username)
|
||||
|
||||
class UnknownUser(Exception):
|
||||
def __init__(self, username):
|
||||
Exception.__init__(self, "Unknown user: %s" % username)
|
||||
|
||||
class UnknownRole(Exception):
|
||||
def _init_(self, role):
|
||||
Exception.__init__(self, "Unknown role: %s" % role)
|
||||
|
||||
##~~ User object
|
||||
|
||||
class MethodReplacedByBooleanProperty(object):
|
||||
|
||||
def __init__(self, name, message, getter):
|
||||
self._name = name
|
||||
self._message = message
|
||||
self._getter = getter
|
||||
|
||||
@property
|
||||
def _attr(self):
|
||||
return self._getter()
|
||||
|
||||
def __call__(self):
|
||||
from warnings import warn
|
||||
warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2)
|
||||
return self._attr
|
||||
|
||||
def __eq__(self, other):
|
||||
return self._attr == other
|
||||
|
||||
def __ne__(self, other):
|
||||
return self._attr != other
|
||||
|
||||
def __bool__(self):
|
||||
# Python 3
|
||||
return self._attr
|
||||
|
||||
def __nonzero__(self):
|
||||
# Python 2
|
||||
return self._attr
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self._attr)
|
||||
|
||||
def __repr__(self):
|
||||
return "MethodReplacedByProperty({}, {}, {})".format(self._name, self._message, self._getter)
|
||||
|
||||
def __str__(self):
|
||||
return str(self._attr)
|
||||
|
||||
|
||||
# TODO: Remove compatibility layer in OctoPrint 1.5.0
|
||||
class FlaskLoginMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty):
|
||||
|
||||
def __init__(self, name, getter):
|
||||
message = "{name} is now a property in Flask-Login versions >= 0.3.0, which OctoPrint now uses. " + \
|
||||
"Use {name} instead of {name}(). This compatibility layer will be removed in OctoPrint 1.5.0."
|
||||
MethodReplacedByBooleanProperty.__init__(self, name, message, getter)
|
||||
|
||||
|
||||
# TODO: Remove compatibility layer in OctoPrint 1.5.0
|
||||
class OctoPrintUserMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty):
|
||||
|
||||
def __init__(self, name, getter):
|
||||
message = "{name} is now a property for consistency reasons with Flask-Login versions >= 0.3.0, which " + \
|
||||
"OctoPrint now uses. Use {name} instead of {name}(). This compatibility layer will be removed " + \
|
||||
"in OctoPrint 1.5.0."
|
||||
MethodReplacedByBooleanProperty.__init__(self, name, message, getter)
|
||||
|
||||
|
||||
class User(UserMixin):
|
||||
class User(AccessUser):
|
||||
@deprecated("octoprint.users.User is deprecated, please use octoprint.access.users.User instead")
|
||||
def __init__(self, username, passwordHash, active, roles, apikey=None, settings=None):
|
||||
self._username = username
|
||||
self._passwordHash = passwordHash
|
||||
self._active = active
|
||||
self._roles = roles
|
||||
self._apikey = apikey
|
||||
from octoprint.server import groupManager
|
||||
|
||||
if settings is None:
|
||||
settings = dict()
|
||||
self._settings = settings
|
||||
|
||||
def asDict(self):
|
||||
return {
|
||||
"name": self._username,
|
||||
"active": bool(self.is_active),
|
||||
"admin": bool(self.is_admin),
|
||||
"user": bool(self.is_user),
|
||||
"apikey": self._apikey,
|
||||
"settings": self._settings
|
||||
}
|
||||
|
||||
def check_password(self, passwordHash):
|
||||
return self._passwordHash == passwordHash
|
||||
|
||||
def get_id(self):
|
||||
return self.get_name()
|
||||
|
||||
def get_name(self):
|
||||
return self._username
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: False)
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: True)
|
||||
|
||||
@property
|
||||
def is_active(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active)
|
||||
|
||||
@property
|
||||
def is_user(self):
|
||||
return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: "user" in self._roles)
|
||||
|
||||
@property
|
||||
def is_admin(self):
|
||||
return OctoPrintUserMethodReplacedByBooleanProperty("is_admin", lambda: "admin" in self._roles)
|
||||
|
||||
def get_all_settings(self):
|
||||
return self._settings
|
||||
|
||||
def get_setting(self, key):
|
||||
if not isinstance(key, (tuple, list)):
|
||||
path = [key]
|
||||
if "admin" in roles:
|
||||
groups = [groupManager.admin_group]
|
||||
elif "user" in roles:
|
||||
groups = [groupManager.user_group]
|
||||
else:
|
||||
path = key
|
||||
groups = [groupManager.guest_group]
|
||||
|
||||
return self._get_setting(path)
|
||||
|
||||
@property
|
||||
def roles(self):
|
||||
return list(self._roles)
|
||||
|
||||
def set_setting(self, key, value):
|
||||
if not isinstance(key, (tuple, list)):
|
||||
path = [key]
|
||||
else:
|
||||
path = key
|
||||
return self._set_setting(path, value)
|
||||
|
||||
def _get_setting(self, path):
|
||||
s = self._settings
|
||||
for p in path:
|
||||
if isinstance(s, dict) and p in s:
|
||||
s = s[p]
|
||||
else:
|
||||
return None
|
||||
return s
|
||||
|
||||
def _set_setting(self, path, value):
|
||||
s = self._settings
|
||||
for p in path[:-1]:
|
||||
if not p in s:
|
||||
s[p] = dict()
|
||||
|
||||
if not isinstance(s[p], dict):
|
||||
s[p] = dict()
|
||||
|
||||
s = s[p]
|
||||
|
||||
key = path[-1]
|
||||
s[key] = value
|
||||
return True
|
||||
|
||||
def __repr__(self):
|
||||
return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin))
|
||||
|
||||
|
||||
class AnonymousUser(AnonymousUserMixin):
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: True)
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: False)
|
||||
|
||||
@property
|
||||
def is_active(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: False)
|
||||
|
||||
|
||||
class SessionUser(wrapt.ObjectProxy):
|
||||
def __init__(self, user):
|
||||
wrapt.ObjectProxy.__init__(self, user)
|
||||
|
||||
import string
|
||||
import random
|
||||
import time
|
||||
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
|
||||
self._self_session = "".join(random.choice(chars) for _ in range(10))
|
||||
self._self_created = time.time()
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
return self._self_session
|
||||
|
||||
@property
|
||||
def created(self):
|
||||
return self._self_created
|
||||
|
||||
@deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5")
|
||||
def get_session(self):
|
||||
return self.session
|
||||
|
||||
def update_user(self, user):
|
||||
self.__wrapped__ = user
|
||||
|
||||
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):
|
||||
User.__init__(self, "dummy", "", True, UserManager.valid_roles)
|
||||
|
||||
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):
|
||||
def __init__(self):
|
||||
User.__init__(self, "_api", "", True, UserManager.valid_roles)
|
||||
AccessUser(username=username, passwordHash=passwordHash, active=active, permissions=None, groups=groups,
|
||||
apikey=apikey, settings=settings)
|
||||
@@ -54,6 +54,35 @@ def warning_decorator_factory(warning_type):
|
||||
return decorator
|
||||
return specific_warning
|
||||
|
||||
|
||||
def warning_factory(warning_type):
|
||||
def specific_warning(message, stacklevel=1, since=None, includedoc=None, extenddoc=False):
|
||||
def decorator(o):
|
||||
def wrapper(f):
|
||||
def new(*args, **kwargs):
|
||||
warnings.warn(message, warning_type, stacklevel=stacklevel + 1)
|
||||
return f(*args, **kwargs)
|
||||
return new
|
||||
|
||||
output = o.__class__.__new__(o.__class__, o)
|
||||
|
||||
unwrappable_names = ("__weakref__", "__class__", "__dict__", "__doc__", "__str__", "__unicode__", "__repr__", "__getattribute__", "__setattr__")
|
||||
for method_name in dir(o):
|
||||
if method_name in unwrappable_names: continue
|
||||
|
||||
setattr(output, method_name, wrapper(getattr(o, method_name)))
|
||||
|
||||
if includedoc is not None and since is not None:
|
||||
docstring = "\n.. deprecated:: {since}\n {message}\n\n".format(since=since, message=includedoc)
|
||||
if extenddoc and hasattr(wrapper, "__doc__") and wrapper.__doc__ is not None:
|
||||
docstring = wrapper.__doc__ + "\n" + docstring
|
||||
wrapper.__doc__ = docstring
|
||||
|
||||
return output
|
||||
return decorator
|
||||
return specific_warning
|
||||
|
||||
|
||||
deprecated = warning_decorator_factory(DeprecationWarning)
|
||||
"""
|
||||
A decorator for deprecated methods. Logs a deprecation warning via Python's `:mod:`warnings` module including the
|
||||
@@ -77,6 +106,24 @@ Returns:
|
||||
function: The wrapped function with the deprecation warnings in place.
|
||||
"""
|
||||
|
||||
variable_deprecated = warning_factory(DeprecationWarning)
|
||||
"""
|
||||
A function for deprecated variables. Logs a deprecation warning via Python's `:mod:`warnings` module including the
|
||||
supplied ``message``. The call stack level used (for adding the source location of the offending call to the
|
||||
warning) can be overridden using the optional ``stacklevel`` parameter.
|
||||
|
||||
Arguments:
|
||||
message (string): The message to include in the deprecation warning.
|
||||
stacklevel (int): Stack level for including the caller of the offending method in the logged warning. Defaults to 1,
|
||||
meaning the direct caller of the method. It might make sense to increase this in case of the function call
|
||||
happening dynamically from a fixed position to not shadow the real caller (e.g. in case of overridden
|
||||
``getattr`` methods).
|
||||
since (string): Version since when the function was deprecated, must be present for the docstring to get extended.
|
||||
|
||||
Returns:
|
||||
value: The value of the variable with the deprecation warnings in place.
|
||||
"""
|
||||
|
||||
pending_deprecation = warning_decorator_factory(PendingDeprecationWarning)
|
||||
"""
|
||||
A decorator for methods pending deprecation. Logs a pending deprecation warning via Python's `:mod:`warnings` module
|
||||
@@ -100,6 +147,25 @@ Returns:
|
||||
function: The wrapped function with the deprecation warnings in place.
|
||||
"""
|
||||
|
||||
variable_pending_deprecation = warning_factory(PendingDeprecationWarning)
|
||||
"""
|
||||
A decorator for variables pending deprecation. Logs a pending deprecation warning via Python's `:mod:`warnings` module
|
||||
including the supplied ``message``. The call stack level used (for adding the source location of the offending call to
|
||||
the warning) can be overridden using the optional ``stacklevel`` parameter.
|
||||
|
||||
Arguments:
|
||||
message (string): The message to include in the deprecation warning.
|
||||
stacklevel (int): Stack level for including the caller of the offending method in the logged warning. Defaults to 1,
|
||||
meaning the direct caller of the method. It might make sense to increase this in case of the function call
|
||||
happening dynamically from a fixed position to not shadow the real caller (e.g. in case of overridden
|
||||
``getattr`` methods).
|
||||
since (string): Version since when the function was deprecated, must be present for the docstring to get extended.
|
||||
|
||||
Returns:
|
||||
value: The value of the variable with the deprecation warnings in place.
|
||||
"""
|
||||
|
||||
|
||||
def get_formatted_size(num):
|
||||
"""
|
||||
Formats the given byte count as a human readable rounded size expressed in the most pressing unit among B(ytes),
|
||||
|
||||
@@ -16,6 +16,13 @@ class JsonEncoding(object):
|
||||
def add_encoder(cls, type, encoder):
|
||||
cls.encoders[type] = encoder
|
||||
|
||||
@classmethod
|
||||
def remove_encoder(cls, type):
|
||||
try:
|
||||
del cls.encoders[type]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def encode(cls, obj):
|
||||
for type, encoder in cls.encoders.items():
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.users
|
||||
Unit tests for octoprint.access
|
||||
"""
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -0,0 +1,15 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
|
||||
def plugin_permissions(components):
|
||||
return [
|
||||
dict(name="fancy permission", description="My Fancy new Permission", roles=["fancy"]),
|
||||
dict(name="fancy permission with two roles", description="My Fancy new Permission with two roles", roles=["fancy1", "fancy2"])
|
||||
]
|
||||
|
||||
|
||||
__plugin_name__ = "Permissions Plugin"
|
||||
__plugin_description__ = "Test permissions plugin"
|
||||
__plugin_hooks__ = {
|
||||
'octoprint.access.permissions': plugin_permissions,
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.access.groups
|
||||
"""
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -0,0 +1,41 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.access.groups.GroupManager
|
||||
"""
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
import tempfile
|
||||
import os
|
||||
import contextlib
|
||||
|
||||
import octoprint.access.groups
|
||||
|
||||
from octoprint.access.permissions import OctoPrintPermission
|
||||
|
||||
TEST_PERMISSION_1 = OctoPrintPermission("Test 1", "Test permission 1", "p1")
|
||||
TEST_PERMISSION_2 = OctoPrintPermission("Test 2", "Test permission 2", "p2")
|
||||
|
||||
@contextlib.contextmanager
|
||||
def group_manager_with_temp_file():
|
||||
with tempfile.NamedTemporaryFile() as f:
|
||||
path = f.name
|
||||
try:
|
||||
f.close()
|
||||
group_manager = octoprint.access.groups.FilebasedGroupManager(path=path)
|
||||
yield group_manager
|
||||
finally:
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
|
||||
class GroupManagerTestCase(unittest.TestCase):
|
||||
def test_add_remove_group(self):
|
||||
with group_manager_with_temp_file() as group_manager:
|
||||
group_manager.add_group("fancy", "Fancy Group", "My Fancy New Group", permissions=[TEST_PERMISSION_1],
|
||||
save=False)
|
||||
self.assertIsNotNone(group_manager.find_group("fancy"))
|
||||
|
||||
group_manager.remove_group("fancy")
|
||||
self.assertIsNone(group_manager.find_group("fancy"))
|
||||
@@ -0,0 +1,20 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.access.permissions
|
||||
"""
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
|
||||
class PermissionsTest(unittest.TestCase):
|
||||
def test_find(self):
|
||||
permission = Permissions.find("ADMIN")
|
||||
self.assertIsNotNone(permission)
|
||||
self.assertEqual(permission.get_name(), "Admin")
|
||||
|
||||
def test_find_fail(self):
|
||||
permission = Permissions.find("doesntexist")
|
||||
self.assertIsNone(permission)
|
||||
@@ -0,0 +1,7 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.access.users
|
||||
"""
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -9,7 +9,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
import unittest
|
||||
import ddt
|
||||
|
||||
import octoprint.users
|
||||
import octoprint.access.users
|
||||
|
||||
@ddt.ddt
|
||||
class UserManagerTest(unittest.TestCase):
|
||||
@@ -21,4 +21,4 @@ class UserManagerTest(unittest.TestCase):
|
||||
salt = "abc"
|
||||
|
||||
# should not throw an exception
|
||||
octoprint.users.UserManager.createPasswordHash(password, salt=salt)
|
||||
octoprint.access.users.UserManager.create_password_hash(password, salt=salt)
|
||||
@@ -1,25 +1,25 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.users.SessionUser
|
||||
Unit tests for octoprint.users
|
||||
"""
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
|
||||
import octoprint.users
|
||||
import octoprint.access.users
|
||||
|
||||
class SessionUserTestCase(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.user = octoprint.users.User("username", "passwordHash", True, ("user",), apikey="apikey", settings=dict(key="value"))
|
||||
self.user = octoprint.access.users.User("username", "passwordHash", True,
|
||||
permissions=[],
|
||||
apikey="apikey",
|
||||
settings=dict(key="value"))
|
||||
|
||||
def test_two_sessions(self):
|
||||
session1 = octoprint.users.SessionUser(self.user)
|
||||
session2 = octoprint.users.SessionUser(self.user)
|
||||
session1 = octoprint.access.users.SessionUser(self.user)
|
||||
session2 = octoprint.access.users.SessionUser(self.user)
|
||||
|
||||
# session should be different, wrapped object should be identical
|
||||
self.assertNotEqual(session1.session, session2.session)
|
||||
@@ -27,8 +27,8 @@ class SessionUserTestCase(unittest.TestCase):
|
||||
self.assertEqual(session1.get_name(), session2.get_name())
|
||||
|
||||
def test_settings_change_propagates(self):
|
||||
session1 = octoprint.users.SessionUser(self.user)
|
||||
session2 = octoprint.users.SessionUser(self.user)
|
||||
session1 = octoprint.access.users.SessionUser(self.user)
|
||||
session2 = octoprint.access.users.SessionUser(self.user)
|
||||
|
||||
# change should propagate from User to SessionUser
|
||||
self.user.set_setting("otherkey", "othervalue")
|
||||
@@ -39,18 +39,18 @@ class SessionUserTestCase(unittest.TestCase):
|
||||
self.assertDictEqual(dict(key="value", otherkey="yetanothervalue"), session1.get_all_settings())
|
||||
|
||||
def test_repr(self):
|
||||
user = octoprint.users.SessionUser(self.user)
|
||||
user = octoprint.access.users.SessionUser(self.user)
|
||||
expected = "SessionUser({!r},session={},created={})".format(self.user, user.session, user.created)
|
||||
self.assertEqual(expected, repr(user))
|
||||
|
||||
def test_isinstance(self):
|
||||
session = octoprint.users.SessionUser(self.user)
|
||||
session = octoprint.access.users.SessionUser(self.user)
|
||||
|
||||
# needs to be detected as User instance
|
||||
self.assertTrue(isinstance(session, octoprint.users.User))
|
||||
self.assertTrue(isinstance(session, octoprint.access.users.User))
|
||||
|
||||
# also needs to be detected as SessionUser instance
|
||||
self.assertTrue(isinstance(session, octoprint.users.SessionUser))
|
||||
self.assertTrue(isinstance(session, octoprint.access.users.SessionUser))
|
||||
|
||||
# but wrapped user should NOT be detected as SessionUser instance of course
|
||||
self.assertFalse(isinstance(self.user, octoprint.users.SessionUser))
|
||||
self.assertFalse(isinstance(self.user, octoprint.access.users.SessionUser))
|
||||
@@ -223,8 +223,8 @@ class PluginTestCase(unittest.TestCase):
|
||||
plugin = "some plugin"
|
||||
data = "some data"
|
||||
self.plugin_manager.send_plugin_message(plugin, data)
|
||||
client1.on_plugin_message.assert_called_once_with(plugin, data)
|
||||
client2.on_plugin_message.assert_called_once_with(plugin, data)
|
||||
client1.on_plugin_message.assert_called_once_with(plugin, data, permissions=None)
|
||||
client2.on_plugin_message.assert_called_once_with(plugin, data, permissions=None)
|
||||
|
||||
def test_validate_plugin(self):
|
||||
self.assertTrue("deprecated_plugin" in self.plugin_manager.enabled_plugins)
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.users.User
|
||||
"""
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
|
||||
import octoprint.users
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
default_settings = dict(key="value", sub=dict(subkey="subvalue"))
|
||||
|
||||
@ddt.ddt
|
||||
class UserTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.user = octoprint.users.User("user", "passwordHash", True, ("user",), apikey="apikey_user", settings=default_settings)
|
||||
self.admin = octoprint.users.User("admin", "passwordHash", True, ("user","admin"), apikey="apikey_admin", settings=default_settings)
|
||||
self.inactive = octoprint.users.User("inactive", "passwordHash", False, ("user",), apikey="apikey_inactive", settings=default_settings)
|
||||
|
||||
@ddt.data(
|
||||
("user", dict(name="user",
|
||||
active=True,
|
||||
admin=False,
|
||||
user=True,
|
||||
apikey="apikey_user",
|
||||
settings=default_settings)),
|
||||
("admin", dict(name="admin",
|
||||
active=True,
|
||||
admin=True,
|
||||
user=True,
|
||||
apikey="apikey_admin",
|
||||
settings=default_settings)),
|
||||
("inactive", dict(name="inactive",
|
||||
active=False,
|
||||
admin=False,
|
||||
user=True,
|
||||
apikey="apikey_inactive",
|
||||
settings=default_settings))
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_as_dict(self, uservar, expected):
|
||||
user = getattr(self, uservar)
|
||||
self.assertDictEqual(expected, user.asDict())
|
||||
|
||||
@ddt.data(
|
||||
("key", "value"),
|
||||
(["sub", "subkey"], "subvalue"),
|
||||
("doesntexist", None)
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_get_setting(self, key, expected):
|
||||
value = self.user.get_setting(key)
|
||||
self.assertEqual(expected, value)
|
||||
|
||||
@ddt.data(
|
||||
("otherkey", "othervalue", dict(otherkey="othervalue"), True),
|
||||
(["sub", "othersubkey"], "othersubvalue", dict(sub=dict(othersubkey="othersubvalue")), True),
|
||||
("booleankey", True, dict(booleankey=True), True),
|
||||
(["newsub", "newsubkey"], "newsubvalue", dict(newsub=dict(newsubkey="newsubvalue")), True),
|
||||
# ["sub", "subkey"] is already existing and gets overwritten
|
||||
(["sub", "subkey", "subsubkey"], "42", dict(sub=dict(subkey=dict(subsubkey="42"))), True),
|
||||
(["sub"], "overwrite", dict(sub="overwrite"), True)
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_set_setting_string(self, key, value, update, expected_returnvalue):
|
||||
returnvalue = self.user.set_setting(key, value)
|
||||
|
||||
expected = dict_merge(default_settings, update)
|
||||
|
||||
self.assertDictEqual(expected, self.user.get_all_settings())
|
||||
self.assertEqual(expected_returnvalue, returnvalue)
|
||||
|
||||
def test_check_password(self):
|
||||
self.assertTrue(self.user.check_password("passwordHash"))
|
||||
self.assertFalse(self.user.check_password("notThePasswordHash"))
|
||||
|
||||
@ddt.data(
|
||||
("user", "User(id=user,name=user,active=True,user=True,admin=False)"),
|
||||
("admin", "User(id=admin,name=admin,active=True,user=True,admin=True)"),
|
||||
("inactive", "User(id=inactive,name=inactive,active=False,user=True,admin=False)")
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_repr(self, uservar, output):
|
||||
self.assertEqual(output, repr(getattr(self, uservar)))
|
||||
Reference in new issue
Block a user