Compare commits

..
56 Commits
Author SHA1 Message Date
Gina Häußge d99af420ac 🐛 loginui: fix reload not triggering right after first run setup 2020-02-26 12:01:24 +01:00
Gina Häußge 73c2baa39e 🔖 Preparing release of 1.4.0rc6 2020-02-26 10:08:34 +01:00
Gina Häußge 054df68741 📝 Fix year 2020-02-26 09:13:44 +01:00
Gina Häußge f7756698e9 🐛 Don't protect blueprints before first run setup 2020-02-25 17:03:51 +01:00
Gina Häußge 453ef0cb97 ♻ Remove implicit blueprint protection in favour of explicit one 2020-02-25 17:03:29 +01:00
Gina Häußge 5015422086 🐛 py3 list vs iterator 2020-02-25 15:48:01 +01:00
Gina Häußge 2d85d8acf8 ♻ is_(anonymous|active)() => is_(anonymous|active) 2020-02-25 15:41:38 +01:00
Gina Häußge 2af589a823 ♻ Remove remnants of old login ui 2020-02-25 15:37:51 +01:00
Gina Häußge 20c55f4d3d 🐛 Fix missing protection for blueprint plugins
is_blueprint_protected should mean a requirement of a logged in non
anonymous user. Implemented accordingly. Got forgotten during switch to
granular permission system.
2020-02-25 15:37:50 +01:00
Gina Häußge b7fdc82d30 🐛 Fix buggy implementation of (before|after)_request hooks 2020-02-25 15:37:48 +01:00
Gina Häußge 770ebf2cf9 📝 Docs for new access control situation 2020-02-25 15:34:17 +01:00
Gina Häußge a75c641c18 ♻ Implement login dialog through UiPlugin
Otherwise alternative UIs might still be wide open, and caching and such
was also really painful to solve before.

The LoginUI Plugin is pretty much just a distilled ForceLogin plugin.

Also declared it as hidden so it won't show up/be manageable by the
plugin manager.
2020-02-25 15:33:42 +01:00
Gina Häußge 38c09153ac ♻ Fix deprecated method names 2020-02-24 14:16:09 +01:00
Gina Häußge e30e18e431 📝 Docs for reauthRequired push message 2020-02-24 12:49:12 +01:00
Gina Häußge 249d19f55b 🐛 Reauth for stale sessions instead of active logout
Fixes #3459
2020-02-24 12:49:04 +01:00
Gina Häußge 2e043ecf5b 📝 Explicitly document LineProcessorStream behaviour under py3
Make absolutely clear that processLine will be called with a byte & not
a unicode string.

See #3454
2020-02-18 15:57:01 +01:00
Gina Häußge 831edf234d 🐛 Fix a firmware info reporting bug
It was not reported if firmware detection was disabled, even though one
should not have anything to do with the other.

Not a regression, but considering that it negatively impacts the printer
safety plugin that relies on firmware info it'll go into 1.4.0
regardless.
2020-02-17 17:34:19 +01:00
Gina Häußge b42c753d3f 🐛 Fix a Py3 bug with the self._printer wrapper in plugins 2020-02-17 17:32:20 +01:00
Gina Häußge 924cd5cb4c 🔖 rc/maintenance is now 1.4.0rc6.dev 2020-02-11 14:37:43 +01:00
Gina Häußge 73f7c4d8a1 🔖 Preparing release of 1.4.0rc5 2020-02-10 17:02:07 +01:00
Gina Häußge 10079b8d9d 🐛 PGMR: Fix UI representation of incompatible plugins
Second part of fixing #3442
2020-02-04 15:53:56 +01:00
Gina Häußge c31566a626 🐛 Fix incompatible plugins to be marked as compatible
First part of fixing #3442
2020-02-04 15:52:53 +01:00
Gina Häußge 0cfc7a2976 Merge remote-tracking branch 'origin/staging/maintenance' into staging/maintenance 2020-02-04 13:17:11 +01:00
Gina Häußge de5a10163e 🐛 Reintroduce message backlog on socket
Was present in forcelogin and made sure that plugins triggering a
message on the socket immediately after connect would get through right
after auth.

Without this a lot of plugins out there run into issues, so this is a
backwards compatibility fix for a regression in 1.4.x.

See also #3400
2020-02-04 13:15:44 +01:00
Gina Häußge 0a22c4e66c ♻ Fix a duplicated line of code 2020-01-31 14:28:27 +01:00
Gina Häußge a88d95af77 🐛 Fix autologin
We need to actually try to identify the user just like we used to do
with the forcelogin plugin. Just checking permissions will only work
if we already have a session.

Closes #3434
2020-01-29 11:37:07 +01:00
Gina Häußge 010221ab5b 🐛 Fix handling of unset remote addresses 2020-01-29 11:35:56 +01:00
Gina Häußge 6471a04a86 staging/maintenance is now 1.4.0rc5.dev
And maintenance is now 1.4.1.dev
2020-01-28 15:16:19 +01:00
Gina Häußge 7b2762c590 🐛 Remove accidentally commited debug statement 2020-01-27 18:06:02 +01:00
Gina Häußge de0b97b99c 🐛 Fix first run setup 2020-01-27 17:32:52 +01:00
Gina Häußge 60d2bd1ac1 🔖 Preparing release of 1.4.0rc4 2020-01-27 15:51:27 +01:00
Gina Häußge 4d716647e5 🐛 Fix socket connect timeout handling
Was triggering even though it should have been cleared due to a
self vs this issue.

Also protect against undefined connection deferred.
2020-01-27 15:03:18 +01:00
Gina Häußge 43ab47a260 ✨ pi support: Permission check for API endpoint 2020-01-27 13:46:09 +01:00
Gina Häußge 88ecfbdb65 🐛 Fix another py2 vs 3 issue
Closes #3431
2020-01-27 11:58:17 +01:00
Gina Häußge 8087967683 🐛 Fix behaviour when page cached & server down
E.g. in Firefox reopen tab while server is down - FF will use a cached
copy and for some reason sockjs won't notice that stuff is down. So now
we have a timeout of 5s for initial connection that takes care of that.
2020-01-24 16:54:52 +01:00
Gina Häußge cb43197105 🐛 Fix endpoint in docs 2020-01-24 13:08:10 +01:00
Gina Häußge b1b9329614 ♻ Move /api/access/user to /api/currentuser
Update documentation accordingly.

See also #3418
2020-01-24 13:05:06 +01:00
Gina Häußge 7317814ce0 📝 Document needed permissions & fix some stuff 2020-01-23 13:21:52 +01:00
Gina Häußge 66ef7b66bb 📝 Documentation for the access API 2020-01-22 18:39:32 +01:00
Gina Häußge be3ff5f043 ✨ API endpoint to retrieve info about current user
As suggested by @fieldOfView.

Implements #3418
2020-01-22 14:58:29 +01:00
Gina Häußge c36fa6da90 🐛 Fix readonly group permissions
Those were accidentally stripped.
2020-01-22 14:55:35 +01:00
Gina Häußge aadcf650c7 🐛 Fix UI caching again
Was broken by 3f3cb556a7 in between server
restarts due to the wrong stuff being fetched by the preemptive cache.
2020-01-21 17:26:45 +01:00
Gina Häußge 95c3fa0b04 🐛 Readd requires line that somehow got missing
Addendum to 3f3cb556a7

Closes #3425
2020-01-21 16:03:48 +01:00
Gina Häußge 1d0829a1db 🐛 Introduce ClientAuthed event
May act as entry point for any kind of push messages a plugin might
wish to send to the client after a connect happened. Since depending
on the current permission configuration this might only be possible
once the client has authenticated on the socket, this is required.

Should close #3400
2020-01-21 15:53:52 +01:00
Gina Häußge 8d31d6687e 🐛 Also trigger login dialog eval on permission change
Not just on logout.

Follow-up to #3425
2020-01-21 15:00:20 +01:00
Gina Häußge 3f3cb556a7 🐛 Fix guest access to settings
Needed its own permission, which in turn needed some changes in how the
whole "guest without read permission" situation is handled. I've
reintroduced a custom login view since the main UI would not be able
to fully load up without settings access. Said login view will override
the default UI view if the account in question does not have
Permissions.STATUS and also Permissions.SETTINGS_READ. It pretty much is
the forcelogin plugin from 1.3.x.

Closes #3425
2020-01-21 14:49:46 +01:00
Gina Häußge 4460c8bee0 🐛 env needs to be native strings
So, bytes under py2 and unicode under py3.

Closes #3428
2020-01-20 13:36:02 +01:00
Gina Häußge 89b597a656 🐛 Fix remember me checkbox
Closes #3426
2020-01-17 16:34:13 +01:00
Gina Häußge e1a25a8913 🐛 Fix caching issue for freshly rendered timelapses
Closes #3396
2020-01-16 12:13:38 +01:00
Gina Häußge 482c2f7115 🐛 Fix timelapse progress under Py3
Closes #3409
2020-01-15 16:53:54 +01:00
Gina Häußge 7fa4ebd1ec Merge pull request #3414 from fieldOfView/fix_allows_multiple_needs
Fix checking against multiple Needs on OctoPrintPermission
2020-01-14 12:44:18 +01:00
Gina Häußge 9c3b552aa8 🔥 Remove unused leftover code 2020-01-14 11:24:22 +01:00
Gina Häußge 3229e65a8d ♻ Remove assumptions about UI from permission model
Implements #3419
2020-01-14 11:22:54 +01:00
fieldOfView 7191d39b51 Fix multiple Needs on OctoPrintPermission
fixes #3398
2020-01-03 08:41:59 -08:00
Gina Häußge 58bc5171ee ✏ Adjusted plugin tutorial for py3 2019-12-13 13:43:29 +01:00
Gina Häußge 74f3bc9ae6 🔖 staging/devel is now 1.4.0rc4.dev 2019-12-12 15:01:53 +01:00
84 changed files with 4294 additions and 5982 deletions

No files matched your search

+9 -9
View File
@@ -18,19 +18,19 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.13
# maintenance is currently the branch for preparation of maintenance release 1.4.1
# so are any fix/... and improve/... branches
maintenance 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
maintenance 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
fix/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
improve/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.12rc4
# staging/maintenance is currently the branch for preparation of 1.4.0rc6
# so is regressionfix/...
staging/maintenance 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev
regressionfix/.* 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev
staging/maintenance 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
regressionfix/.* 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
# staging/devel is currently the branch for preparation of 1.4.0rc3
staging/devel 1.4.0rc3 e603b98d0dc552e570034aae52291737695dd0f6 pep440-dev
# staging/devel is currently inactive (but has the 1.4.0rc6 namespace)
staging/devel 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.5.0-dev for now
.* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
+9 -7
View File
@@ -6,7 +6,6 @@ thanks to everyone who contributed!
## Patreon Patrons
* Andre Bubel
* Andrew Moorby
* Arnljot Arntsen
* BigTreeTech
@@ -16,6 +15,7 @@ thanks to everyone who contributed!
* Christian Wolf
* D Brian Kimmel
* DeltaMaker 3D Printers
* Dennis Breining
* Dorian Gray
* Eric Betts
* Ernesto Martinez
@@ -23,17 +23,18 @@ thanks to everyone who contributed!
* GadgetAngel
* George Robles
* Greg Holloway
* Hog Duske
* Hugh Blemings
* jean-claude migneault
* Jeff Renfer
* Jeremiah Avery
* John Robinson (JRo)
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kenneth Jiang
* Kurt Wubbels
* Kyle Menigoz
* LA 3D Printer Repair
* Lee Dohm
@@ -43,21 +44,22 @@ thanks to everyone who contributed!
* Michael Aumock
* Miles Flavel
* Mosaic Manufacturing
* OMER MEHMET SUTAS
* Neil R. Goldberg
* Patrick Glyré
* Patrick McGinnis
* Prof Yuh Wen Chen
* Randy C. Will
* Ranjib Dey
* Richard Michaud
* Rigid3D
* Robert Gusek
* Ronald Griehsler
* Shawn Lewis
* Sacha Telgenhof
* sghnsk
* Simon Hallam
* Stefan Krister
* Sven Mueller
* The3DprintingMagic.com
* Trent Shumay
* Ulrich Kempken
* Vladislav Kuzemchik
and 1678 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
and 1764 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
+529
View File
@@ -0,0 +1,529 @@
.. _sec-api-access:
**************
Access control
**************
.. contents::
.. _sec-api-access-permissions:
Permissions
===========
.. _sec-api-access-permissions-list:
List all permissions
--------------------
.. http:get:: /api/access/permissions
Retrieves all permissions available in the system.
Will return a :http:statuscode:`200` with a :ref:`permission list <sec-api-access-datamodel-permissions-list>`
as body.
:status 200: No error
.. _sec-api-access-groups:
Groups
======
.. _sec-api-access-groups-list:
Get group list
--------------
.. http:get:: /api/access/groups
Retrieves all groups registered in the system.
Will return a :http:statuscode:`200` with a :ref:`group list <sec-api-access-datamodel-groups-list>`
as body.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-groups-add:
Add a new group
---------------
.. http:post:: /api/access/groups
Adds a new group to the system.
Expects a :ref:`group registration request <sec-api-access-datamodel-groups-addgrouprequest>` as request body.
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
Requires the ``SETTINGS`` permission.
:json key: The group's identifier
:json name: The user's name
:json description: A human readable description of the group
:json permissions: The permissions to assign to the group
:json subgroups: Subgroups assigned to the group
:json default: Whether the group should be assigned to new users by default or not
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
:status 409: A group with the provided key does already exist
.. _sec-api-access-groups-retrieve:
Retrieve a group
----------------
.. http:get:: /api/access/groups/(string:key)
Retrieves an individual group record.
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-grouprecord>`
as body.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-groups-modify:
Update a group
--------------
.. http:put:: /api/access/groups/(string:key)
Updates an existing group.
Expects a :ref:`group update request <sec-api-access-datamodel-groups-updategrouprequest>` as request body.
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
Requires the ``SETTINGS`` permission.
:json description: A human readable description of the group
:json permissions: The permissions to assign to the group
:json subgroups: Subgroups assigned to the group
:json default: Whether the group should be assigned to new users by default or not
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
.. _sec-api-access-groups-delete:
Delete a group
--------------
.. http:delete:: /api/access/groups/(string:key)
Deletes a group.
Will return a :ref:`group list response <sec-api-access-datamodel-groups-list>` on success.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-users:
Users
=====
.. _sec-api-access-users-list:
Retrieve a list of users
========================
.. http:get:: /api/access/users
Retrieves a list of all registered users in OctoPrint.
Will return a :http:statuscode:`200` with a :ref:`user list response <sec-api-access-datamodel-users-userlistresponse>`
as body.
Requires the ``SETTINGS`` permission.
:status 200: No error
.. _sec-api-access-users-retrieve:
Retrieve a user
---------------
.. http:get:: /api/access/users/(string:username)
Retrieves information about a user.
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-access-datamodel-users-userrecord>`
as body.
Requires either the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user which to retrieve
:status 200: No error
:status 404: Unknown user
.. _sec-api-access-users-add:
Add a new user
--------------
.. http:post:: /api/access/users
Adds a user to OctoPrint.
Expects a :ref:`user registration request <sec-api-access-datamodel-users-adduserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
Requires the ``SETTINGS`` permission.
:json name: The user's name
:json password: The user's password
:json active: Whether to activate the account (true) or not (false)
:json admin: Whether to give the account admin rights (true) or not (false)
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
:status 409: A user with the provided name does already exist
.. _sec-api-access-users-modify:
Update a user
-------------
.. http:put:: /api/access/users/(string:username)
Updates a user record.
Expects a :ref:`user update request <sec-api-access-datamodel-users-updateuserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
Requires the ``SETTINGS`` permission.
:param username: Name of the user to update
:json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change)
:json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change)
:status 200: No error
:status 404: Unknown user
.. _sec-api-access-users-delete:
Delete a user
-------------
.. http:delete:: /api/access/users/(string:username)
Delete a user record.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-access-users-list>`.
Requires the ``SETTINGS`` permission.
:param username: Name of the user to delete
:status 200: No error
:status 404: Unknown user
.. _sec-api-access-users-password:
Change a user's password
------------------------
.. http:put:: /api/access/users/(string:username)/password
Changes the password of a user.
Expects a JSON object with a single property ``password`` as request body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to change the password for
:json password: The new password to set
:status 200: No error
:status 400: If the request doesn't contain a ``password`` property or the request
is otherwise invalid
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-settings-get:
Get a user's settings
---------------------
.. http:get:: /api/access/users/(string:username)/settings
Retrieves a user's settings.
Will return a :http:statuscode:`200` with a JSON object representing the user's
personal settings (if any) as body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-settings-set:
Update a user's settings
------------------------
.. http:patch:: /api/access/users/(string:username)/settings
Updates a user's settings.
Expects a new settings JSON object to merge with the current settings as
request body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-apikey-generate:
Regenerate a user's api key
---------------------------
.. http:post:: /api/access/users/(string:username)/apikey
Generates a new API key for the user.
Does not expect a body. Will return the generated API key as ``apikey``
property in the JSON object contained in the response body.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-users-apikey-delete:
Delete a user's api key
-----------------------
.. http:delete:: /api/access/users/(string:username)/apikey
Deletes a user's personal API key.
Requires the ``SETTINGS`` permission or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-access-datamodel:
Data model
==========
.. _sec-api-access-datamodel-permissions:
Permissions
-----------
.. _sec-api-access-datamodel-permissions-list:
Permission list response
~~~~~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``permissions``
- 0..n
- List of :ref:`permission records <sec-api-datamodel-access-permissions>`
- The list of permissions
.. _sec-api-access-datamodel-groups:
Groups
------
.. _sec-api-access-datamodel-groups-list:
Group list response
~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``groups``
- 0..n
- List of :ref:`group records <sec-api-datamodel-access-groups>`
- The list of groups
.. _sec-api-access-datamodel-groups-addgrouprequest:
Group registration request
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- string
- The group's identifier
* - ``name``
- 1
- string
- The group's name
* - ``description``
- 0..1
- string
- The group's description. Set to empty if not provided.
* - ``permissions``
- 1..n
- List of string
- A list of identifier's of permissions to assign to the group
* - ``subgroups``
- 0..n
- List of string
- A list of identifier's of groups to assign to the group as subgroups
* - ``default``
- 0..1
- boolean
- Whether to assign the group to new users by default (true) or not (false, default value)
.. _sec-api-access-datamodel-groups-updategrouprequest:
Group update request
~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``description``
- 0..1
- string
- The group's description. Set to empty if not provided.
* - ``permissions``
- 1..n
- List of string
- A list of identifier's of permissions to assign to the group
* - ``subgroups``
- 0..n
- List of string
- A list of identifier's of groups to assign to the group as subgroups
* - ``default``
- 0..1
- boolean
- Whether to assign the group to new users by default (true) or not (false, default value)
.. _sec-api-access-datamodel-users:
Users
-----
.. _sec-api-access-datamodel-users-userlistresponse:
User list response
~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``users``
- 0..n
- List of :ref:`user records <sec-api-datamodel-access-users>`
- The list of users
.. _sec-api-access-datamodel-users-adduserrequest:
User registration request
~~~~~~~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``password``
- 1
- string
- The user's password
* - ``active``
- 1
- bool
- Whether to activate the account (true) or not (false)
* - ``groups``
- 0..n
- List of string
- A list of identifiers of groups to assign to the user
* - ``permissions``
- 0..n
- List of string
- A list of identifiers of permissions to assign to the user
.. _sec-api-access-datamodel-users-updateuserrequest:
User update request
~~~~~~~~~~~~~~~~~~~
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``active``
- 0..1
- bool
- If present will set the user's active flag to the provided value. True for
activating the account, false for deactivating it.
* - ``groups``
- 0..n
- List of string
- A list of identifiers of groups to assign to the user
* - ``permissions``
- 0..n
- List of string
- A list of identifiers of permissions to assign to the user
+3 -1
View File
@@ -16,6 +16,8 @@ Get connection settings
Retrieve the current connection settings, including information regarding the available baudrates and
serial ports and the current connection state.
Requires the ``STATUS`` permission.
**Example**
.. sourcecode:: http
@@ -81,7 +83,7 @@ Issue a connection command
for the lost acknowledgment should always be properly investigated and removed instead of depending on this
"symptom solver".
Requires user rights.
Requires the ``CONNECTION`` permission.
**Example Connect Request**
+170
View File
@@ -480,3 +480,173 @@ References
- URL
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
folders.
.. _sec-api-datamodel-access:
Access control
==============
.. _sec-api-datamodel-access-users:
User record
-----------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``active``
- 1
- bool
- Whether the user's account is active (true) or not (false)
* - ``user``
- 1
- bool
- Whether the user has user rights. Should always be true. Deprecated as of 1.4.0, use the ``users`` group instead.
* - ``admin``
- 1
- bool
- Whether the user has admin rights (true) or not (false). Deprecated as of 1.4.0, use the ``admins`` group instead.
* - ``apikey``
- 0..1
- string
- The user's personal API key
* - ``settings``
- 1
- object
- The user's personal settings, might be an empty object.
* - ``groups``
- 1..n
- List of string
- Groups assigned to the user
* - ``needs``
- 1
- :ref:`Needs object <sec-api-datamodel-access-needs>`
- Effective needs of the user
* - ``permissions``
- 0..n
- List of :ref:`Permissions <sec-api-datamodel-access-permissions>`
- The list of permissions assigned to the user (note: this does not include implicit permissions inherit from groups).
.. _sec-api-datamodel-access-permissions:
Permission record
-----------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- string
- The permission's identifier
* - ``name``
- 1
- string
- The permission's name
* - ``dangerous``
- 1
- boolean
- Whether the permission should be considered dangerous due to a high reponsibility (true) or not (false).
* - ``default_groups``
- 1
- List of string
- List of group identifiers for which this permission is enabled by default
* - ``description``
- 1
- string
- Human readable description of the permission
* - ``needs``
- 1
- :ref:`Needs object <sec-api-access-datamodel-general-needs>`
- Needs assigned to the permission
.. _sec-api-datamodel-access-groups:
Group record
------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- string
- The group's identifier
* - ``name``
- 1
- string
- The group's name
* - ``description``
- 1
- string
- A human readable description of the group
* - ``permissions``
- 0..n
- List of :ref:`Permissions <sec-api-datamodel-access-permissions>`
- The list of permissions assigned to the group (note: this does not include implicit permissions inherited from
subgroups).
* - ``subgroups``
- 0..n
- List of :ref:`Groups <sec-api-datamodel-access-groups>`
- Subgroups assigned to the group
* - ``needs``
- 1
- :ref:`Needs object <sec-api-datamodel-access-needs>`
- Effective needs of the group
* - ``default``
- 1
- boolean
- Whether this is a default group (true) or not (false)
* - ``removable``
- 1
- boolean
- Whether this group can be removed (true) or not (false)
* - ``changeable``
- 1
- boolean
- Whether this group can be modified (true) or not (false)
* - ``toggleable``
- 1
- boolean
- Whether this group can be assigned to users or other groups (true) or not (false)
.. _sec-api-datamodel-access-needs:
Needs
-----
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``role``
- 0..1
- List of string
- List of ``role`` needs
* - ``group``
- 0..1
- List of string
- List of ``group`` needs
+15 -3
View File
@@ -21,6 +21,8 @@ Retrieve all files
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
Requires the ``FILES_LIST`` permission.
**Example 1**:
Fetch only the files and folders from the root folder.
@@ -250,6 +252,8 @@ Retrieve files from specific location
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
Requires the ``FILES_LIST`` permission.
**Example**:
.. sourcecode:: http
@@ -327,7 +331,7 @@ Upload file or create folder
Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded
file and an :ref:`Upload Response <sec-api-fileops-datamodel-uploadresponse>` as the body upon successful completion.
Requires user rights.
Requires the ``FILES_UPLOAD`` permission.
**Example for uploading a file**
@@ -504,6 +508,8 @@ Retrieve a specific file's or folder's information
On success, a :http:statuscode:`200` is returned, with a :ref:`file information item <sec-api-datamodel-files-file>`
as the response body.
Requires the ``FILES_LIST`` permission.
**Example**
.. sourcecode:: http
@@ -568,6 +574,8 @@ Issue a file command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires the ``FILES_SELECT`` permission.
slice
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
after the response has been sent back to the client. Additional parameters are:
@@ -598,6 +606,8 @@ Issue a file command
Upon success, a status code of :http:statuscode:`202` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
body will be returned.
Requires the ``SLICE`` permission.
copy
Copies the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
@@ -609,6 +619,8 @@ Issue a file command
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
body will be returned.
Requires the ``FILES_UPLOAD`` permission.
move
Moves the file or folder to a new ``destination`` on the same ``location``. Additional parameters are:
@@ -622,7 +634,7 @@ Issue a file command
Upon success, a status code of :http:statuscode:`201` and a :ref:`sec-api-datamodel-files-fileabridged` in the response
body will be returned.
Requires user rights.
Requires the ``FILES_UPLOAD`` permission.
**Example Select Request**
@@ -773,7 +785,7 @@ Delete file
Returns a :http:statuscode:`204` after successful deletion.
Requires user rights.
Requires the ``FILES_DELETE`` permission.
**Example Request**
+47 -29
View File
@@ -180,6 +180,20 @@ Logout
:status 204: No error
.. _sec-api-general-currentuser:
Current User
============
.. http:get:: /api/currentuser
Retrieves information about the current user.
Will return a :http:statuscode:`200` with a :ref:`current user object <sec-api-general-datamodel-currentuser>`
as body.
:status 200: No error
.. _sec-api-general-datamodel:
Data model
@@ -190,6 +204,30 @@ Data model
Login response
--------------
The Login response is a :ref:`user record <sec-api-datamodel-access-users>` extended by the following fields:
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``session``
- 1
- string
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
* - ``_is_external_client``
- 1
- boolean
- Whether the client that made the request got detected as external from the local network or not.
.. _sec-api-general-datamodel-currentuser:
Current user
------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
@@ -201,32 +239,12 @@ Login response
* - ``name``
- 1
- string
- the user's name/id
* - ``active``
- 1
- boolean
- Whether the user's account is active or not
* - ``admin``
- 1
- boolean
- Whether the user has admin rights or not
* - ``user``
- 1
- boolean
- Whether the user has user rights or not (always ``true``)
* - ``apikey``
- 1
- string or None
- The user's API key, if set
* - ``settings``
- 1
- dict
- The user's settings, if any
* - ``session``
- 1
- string
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
* - ``_is_external_client``
- 1
- boolean
- Whether the client that made the request got detected as external from the local network or not.
- The id of the current user. Unset if guest.
* - ``permissions``
- 0..n
- List of :ref:`permission records <sec-api-datamodel-access-permissions>`
- The effective list of permissions assigned to the user
* - ``groups``
- 0..n
- List of :ref:`permission records <sec-api-datamodel-access-groups>`
- The list of groups assigned to the user
+1 -1
View File
@@ -20,7 +20,7 @@ REST API
slicing.rst
system.rst
timelapse.rst
users.rst
access.rst
util.rst
wizard.rst
push.rst
+3 -1
View File
@@ -57,7 +57,7 @@ Issue a job command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``PRINT`` permission.
**Example Start Request**
@@ -180,6 +180,8 @@ Retrieve information about the current job
Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body.
Requires the ``STATUS`` permission.
**Example**
.. sourcecode:: http
+1 -1
View File
@@ -6,7 +6,7 @@ Languages
.. note::
All language pack management operations require admin rights.
All language pack management operations require the ``SETTINGS`` permission.
.. contents::
+54 -6
View File
@@ -80,6 +80,8 @@ Retrieve the current printer state
Returns a :http:statuscode:`200` with a :ref:`Full State Response <sec-api-printer-datamodel-fullstate>` in the
body upon success.
Requires the ``STATUS`` permission.
**Example 1**
Include temperature history data, but limit it to two entries.
@@ -241,7 +243,7 @@ Issue a print head command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Jog Request**
@@ -380,7 +382,7 @@ Issue a tool command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Target Temperature Request**
@@ -555,6 +557,8 @@ Retrieve the current tool state
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
Requires the ``STATUS`` permission.
.. note::
If you want both tool and bed temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -645,7 +649,7 @@ Issue a bed command
If no heated bed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Target Temperature Request**
@@ -714,6 +718,8 @@ Retrieve the current bed state
If no heated bed is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires the ``STATUS`` permission.
.. note::
If you want tool, bed and chamber temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -793,7 +799,7 @@ Issue a chamber command
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Target Temperature Request**
@@ -862,6 +868,8 @@ Retrieve the current chamber state
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires the ``STATUS`` permission.
.. note::
If you want tool, bed and chamber temperature information at the same time, take a look at
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
@@ -944,7 +952,7 @@ Issue an SD command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example Init Request**
@@ -1022,6 +1030,8 @@ Retrieve the current SD state
Returns a :http:statuscode:`200` with an :ref:`SD State Response <sec-api-printer-datamodel-sdstate>` in the body
upon success.
Requires the ``STATUS`` permission.
**Example**
Read the current state of the SD card.
@@ -1058,7 +1068,7 @@ Send an arbitrary command to the printer
If successful returns a :http:statuscode:`204` and an empty body.
Requires user rights.
Requires the ``CONTROL`` permission.
**Example for sending a single command**
@@ -1101,6 +1111,26 @@ Send an arbitrary command to the printer
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
:statuscode 204: No error
.. _sec-api-printer-customcontrols:
Retrieve custom controls
========================
.. http:get:: /api/printer/command/custom
Retrieves the :ref:`custom controls <sec-features-custom_controls>` as configured in
:ref:`config.yaml <sec-configuration-config_yaml>`.
Please refer to the documentation of :ref:`custom controls <sec-features-custom_controls>` on what
data structure to expect here.
Returns a :http:statuscode:`200` with an :ref:`Custom Controls Response <sec-api-printer-datamodel-customcontrols>`
in the body upon success.
Requires the ``CONTROL`` permission.
:statuscode 200: No error
.. _sec-api-printer-datamodel:
Data model
@@ -1211,3 +1241,21 @@ Arbitrary Command Request
- 0..1
- Map of key value pairs
- (only if ``script`` is set) additional template variables to provide to the script renderer
.. _sec-api-printer-datamodel-customcontrols:
Custom Controls Response
------------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``controls``
- 0..n
- List of :ref:`custom controls <sec-features-custom_controls>`
- A list of custom control definitions as defined in ``config.yaml``.
+21 -3
View File
@@ -21,6 +21,8 @@ Retrieve all printer profiles
Returns a :http:statuscode:`200` with a list of :ref:`profiles <sec-api-printerprofiles-datamodel-profile>`.
Requires the ``CONNECTION`` permission.
**Example**
.. sourcecode:: http
@@ -124,6 +126,22 @@ Retrieve all printer profiles
}
.. _sec-api-printerprofiles-get:
Retrieve a single printer profile
=================================
.. http:get:: /api/printerprofiles/(string:identifier)
Retrieves an existing single printer profile.
Returns a :http:statuscode:`200` with a :ref:`profile <sec-api-printerprofiles-datamodel-profile>`.
Requires the ``CONNECTION`` permission.
:statuscode 200: No error
:statuscode 404: The profile does not exist
.. _sec-api-printerprofiles-add:
Add a new printer profile
@@ -143,7 +161,7 @@ Add a new printer profile
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
in the JSON body upon success.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example 1**
@@ -314,7 +332,7 @@ Update an existing printer profile
Returns a :http:statuscode:`200` with the saved profile as property ``profile``
in the JSON body upon success.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
@@ -400,7 +418,7 @@ Remove an existing printer profile
Returns a :http:statuscode:`204` an empty body upon success.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
+5 -3
View File
@@ -29,6 +29,9 @@ following message types are currently available for usage by 3rd party clients:
* ``connected``: Initial connection information, sent only right after establishing the socket connection. See
:ref:`the payload data model <sec-api-push-datamodel-connected>`.
* ``reauthRequired``: A reauthentication of the current login session is required. The ``reason`` parameter in the
payload defines whether a full active login is necessary (values ``logout`` and ``removed``) or a simple passive
login will suffice (all other values).
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
is available, but not more often than twice per second in order to not flood the client with messages (e.g.
@@ -51,9 +54,8 @@ OctoPrint's SockJS socket also accepts two commands from the client to the serve
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
existing user session with the socket. That is of special importance to receive
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
clients.
any kind of messages, since the permission system will prevent any kind of status messages to be sent to connected
clients lacking the ``STATUS`` permission.
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
+3 -1
View File
@@ -21,6 +21,8 @@ Retrieve current settings
The :ref:`data model <sec-api-settings-datamodel>` is similar to what can be found in
:ref:`config.yaml <sec-configuration-config_yaml>`, see below for details.
Requires the ``SETTINGS_READ`` permission.
.. _sec-api-settings-save:
Save settings
@@ -36,7 +38,7 @@ Save settings
Returns the currently active settings on success, as part of a :http:statuscode:`200` response.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
+62 -2
View File
@@ -28,6 +28,8 @@ List All Slicers and Slicing Profiles
Returns a :http:statuscode:`200` response with a :ref:`Slicer list <sec-api-slicing-datamodel-slicerlist>`
as the body upon successful completion.
Requires the ``SLICE`` permission.
**Example**
.. sourcecode:: http
@@ -77,6 +79,8 @@ List Slicing Profiles of a Specific Slicer
Returns a :http:statuscode:`200` response with a :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
as the body upon successful completion.
Requires the ``SLICE`` permission.
**Example**
.. sourcecode:: http
@@ -121,6 +125,8 @@ Retrieve Specific Profile
Returns a :http:statuscode:`200` response with a :ref:`full Profile <sec-api-slicing-datamodel-profile>`
as the body upon successful completion.
Requires the ``SLICE`` permission.
**Example**
.. sourcecode:: http
@@ -168,7 +174,7 @@ Add Slicing Profile
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
upon successful completion.
Requires admin rights.
Requires the ``SETTINGS`` permission.
**Example**
@@ -206,6 +212,31 @@ Add Slicing Profile
:statuscode 201: No error
:statuscode 404: If the ``slicer`` was unknown to the system.
.. _sec-api-slicing-patch:
Update Slicing Profile
======================
.. http:patch:: /api/slicing/(string:slicer)/profiles/(string:key)
Updates the slicing profile identified by ``key`` for the slicer ``slicer``.
Expects a :ref:`profile update request <sec-api-slicing-datamodel-profileupdate>` as body.
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
upon successful completion.
Requires the ``SETTINGS`` permission.
:param slicer: The identifying key of the slicer for which to update the profile
:param key: The identifying key of the profile to update
:json data: New profile overrides to apply
:json displayName: New display name
:json description: New description
:json default: Whether to make the profile default (true) or not (false) for the slicer
:statuscode 200: No error
:statuscode 404: Slicer or profile do not exist
.. _sec-api-slicing-delete:
Delete Slicing Profile
@@ -216,7 +247,7 @@ Delete Slicing Profile
Delete the slicing profile identified by ``key`` for the slicer ``slicer``. If the profile doesn't exist, the
request will succeed anyway.
Requires admin rights.
Requires the ``SETTINGS`` permission.
:param slicer: The identifying key of the slicer for which to delete the profile
:param key: The identifying key of the profile to delete
@@ -340,3 +371,32 @@ Profile
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
specific. Will be left out for list responses.
.. _sec-api-slicing-datamodel-profileupdate:
Profile Update Request
----------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``data``
- 0..1
- Object
- The profile data
* - ``displayName``
- 0..1
- ``string``
- The new display name for the profile
* - ``description``
- 0..1
- ``string``
- The new description for the profile
* - ``default``
- 0..1
- ``boolean``
- Whether to mark the profile as default for the slicer (true) or not (false)
+3 -1
View File
@@ -6,7 +6,7 @@ System
.. note::
All system operations require admin rights.
All system operations require the ``SYSTEM`` permission.
.. _sec-api-system-command-list:
@@ -20,6 +20,8 @@ List all registered system commands
A :http:statuscode:`200` with a :ref:`List all response <sec-api-system-commands-listall>`
will be returned.
Requires the ``SYSTEM`` permission.
**Example**
.. sourcecode:: http
+6 -4
View File
@@ -18,6 +18,8 @@ Retrieve a list of timelapses and the current config
Returns a :ref:`timelapse list <sec-api-timelapse-datamodel-list>` in the
response body.
Requires the ``TIMELAPSE_LIST`` permission.
:param unrendered: If provided and true, also include unrendered timelapses
.. _sec-api-timelapse-delete:
@@ -29,7 +31,7 @@ Delete a timelapse
Delete the timelapse ``filename``.
Requires user rights.
Requires the ``TIMELAPSE_DELETE`` permission.
.. _sec-api-timelapse-render:
@@ -41,7 +43,7 @@ Issue a command for an unrendered timelapse
Current only supports to render the unrendered timelapse ``name`` via the
``render`` command.
Requires user rights.
Requires the ``TIMELAPSE_ADMIN`` permission.
:json command: The command to issue, currently only ``render`` is supported
@@ -54,7 +56,7 @@ Delete an unrendered timelapse
Delete the unrendered timelapse ``name``.
Requires user rights.
Requires the ``TIMELAPSE_DELETE`` permission.
.. _sec-api-timelapse-saveconfig:
@@ -67,7 +69,7 @@ Change current timelapse config
The configuration is expected as the request body.
Requires user rights.
Requires the ``TIMELAPSE_ADMIN`` permission.
.. _sec-api-timelapse-datamodel:
+2 -307
View File
@@ -4,311 +4,6 @@
User
****
.. contents::
.. note::
.. _sec-api-users-list:
Retrieve a list of users
========================
.. http:get:: /api/users
Retrieves a list of all registered users in OctoPrint.
Will return a :http:statuscode:`200` with a :ref:`user list response <sec-api-users-datamodel-userlistresponse>`
as body.
Requires admin rights.
:status 200: No error
.. _sec-api-users-retrieve:
Retrieve a user
===============
.. http:get:: /api/users/(string:username)
Retrieves information about a user.
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-users-datamodel-userrecord>`
as body.
Requires either admin rights or to be logged in as the user.
:param username: Name of the user which to retrieve
:status 200: No error
:status 404: Unknown user
.. _sec-api-users-add:
Add a user
==========
.. http:post:: /api/users
Adds a user to OctoPrint.
Expects a :ref:`user registration request <sec-api-users-datamodel-adduserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
Requires admin rights.
:json name: The user's name
:json password: The user's password
:json active: Whether to activate the account (true) or not (false)
:json admin: Whether to give the account admin rights (true) or not (false)
:status 200: No error
:status 400: If any of the mandatory fields is missing or the request is otherwise
invalid
:status 409: A user with the provided name does already exist
.. _sec-api-users-update:
Update a user
=============
.. http:put:: /api/users/(string:username)
Updates a user record.
Expects a :ref:`user update request <sec-api-users-datamodel-updateuserrequest>`
as request body.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
Requires admin rights.
:param username: Name of the user to update
:json admin: Whether to mark the user as admin (true) or not (false), can be left out (no change)
:json active: Whether to mark the account as activated (true) or deactivated (false), can be left out (no change)
:status 200: No error
:status 404: Unknown user
.. _sec-api-users-delete:
Delete a user
=============
.. http:delete:: /api/users/(string:username)
Delete a user record.
Returns a list of registered users on success, see :ref:`Retrieve a list of users <sec-api-users-list>`.
Requires admin rights.
:param username: Name of the user to delete
:status 200: No error
:status 404: Unknown user
.. _sec-api-users-resetpassword:
Reset a user's password
=======================
.. http:put:: /api/users/(string:username)/password
Changes the password of a user.
Expects a JSON object with a single property ``password`` as request body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to change the password for
:json password: The new password to set
:status 200: No error
:status 400: If the request doesn't contain a ``password`` property or the request
is otherwise invalid
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-getsettings:
Retrieve a user's settings
==========================
.. http:get:: /api/users/(string:username)/settings
Retrieves a user's settings.
Will return a :http:statuscode:`200` with a JSON object representing the user's
personal settings (if any) as body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-updatesettings:
Update a user's settings
========================
.. http:patch:: /api/users/(string:username)/settings
Updates a user's settings.
Expects a new settings JSON object to merge with the current settings as
request body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-generateapikey:
Regenerate a user's personal API key
====================================
.. http:post:: /api/users/(string:username)/apikey
Generates a new API key for the user.
Does not expect a body. Will return the generated API key as ``apikey``
property in the JSON object contained in the response body.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 200: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-deleteapikey:
Delete a user's personal API key
================================
.. http:delete:: /api/users/(string:username)/apikey
Deletes a user's personal API key.
Requires admin rights or to be logged in as the user.
:param username: Name of the user to retrieve the settings for
:status 204: No error
:status 403: No admin rights and not logged in as the user
:status 404: The user is unknown
.. _sec-api-users-datamodel:
Data model
==========
.. _sec-api-users-datamodel-userlistresponse:
User list response
------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``users``
- 0..n
- List of :ref:`user records <sec-api-users-datamodel-userrecord>`
- The list of registered users
.. _sec-api-users-datamodel-userrecord:
User record
-----------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``active``
- 1
- bool
- Whether the user's account is active (true) or not (false)
* - ``user``
- 1
- bool
- Whether the user has user rights. Should always be true.
* - ``admin``
- 1
- bool
- Whether the user has admin rights (true) or not (false)
* - ``apikey``
- 0..1
- string
- The user's personal API key
* - ``settings``
- 1
- object
- The user's personal settings, might be an empty object.
.. _sec-api-users-datamodel-adduserrequest:
User registration request
-------------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- The user's name
* - ``password``
- 1
- string
- The user's password
* - ``active``
- 1
- bool
- Whether to activate the account (true) or not (false)
* - ``admin``
- 0..1
- bool
- Whether to give the user admin rights (true) or not (false or not present)
.. _sec-api-users-datamodel-updateuserrequest:
User update request
-------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``active``
- 0..1
- bool
- If present will set the user's active flag to the provided value. True for
activating the account, false for deactivating it.
* - ``admin``
- 0..1
- bool
- If present will set the user's admin flag to the provided value. True for
admin rights, false for no admin rights.
This API endpoint has been moved and is now part of :ref:`Access Control <sec-api-access-users>`.
+1 -1
View File
@@ -99,7 +99,7 @@ Test paths or URLs
The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result <sec-api-util-datamodel-servertestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
Requires admin rights.
Requires the ``ADMIN`` permission.
**Example 1**
+1 -1
View File
@@ -6,7 +6,7 @@ Wizard
.. note::
All wizard operations require either admin rights or the ``firstRun`` flag to be ``true``.
All wizard operations require either the ``ADMIN`` permission or the ``firstRun`` flag to be ``true``.
.. contents::
-35
View File
@@ -1,35 +0,0 @@
.. _sec-bundledplugins-forcelogin:
ForceLogin Plugin
=================
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
instead forces users to log in if they want to get any kind of information from OctoPrint.
.. _fig-bundledplugins-forcelogin:
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
:align: center
:alt: Forced login dialog
OctoPrint's new forced login dialog.
.. warning::
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
is not OctoPrint itself.
.. note::
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
the ForceLogin Plugin in OctoPrint's plugin manager.
.. _sec-bundledplugins-forcelogin-sourcecode:
Source code
-----------
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/forcelogin``.
+1 -1
View File
@@ -14,8 +14,8 @@ Bundled Plugins
backup.rst
discovery.rst
errortracking.rst
forcelogin.rst
logging.rst
loginui.rst
pluginmanager.rst
printer_safety_check.rst
softwareupdate.rst
+66
View File
@@ -0,0 +1,66 @@
.. _sec-bundledplugins-loginui:
Login UI
========
The Login UI plugin has been bundled since OctoPrint 1.4.0 and replaces the ForceLogin plugin bundled with prior
versions since 1.3.10.
If anonymous read-only access is disabled in the :ref:`Access Control settings <sec-features-access_control>`
it provides a stand alone login dialog that gets displayed instead of OctoPrint's regular UI.
.. _fig-bundledplugins-loginui:
.. figure:: ../images/bundledplugins-loginui-dialog.png
:align: center
:alt: Login dialog
OctoPrint's login dialog.
The plugin allows theming of the dialog through :ref:`a plugin hook <sec-bundledplugins-loginui-hooks-theming>`.
.. warning::
Since the plugin is absolutely required for the case of anonymous read-only access because in this case the
UI itself could not even fully initialize due to a lack of permissions required to do so, it is hidden in the plugin
manager and cannot be disabled through that.
.. _sec-bundledplugins-loginui-hooks:
Hooks
-----
.. _sec-bundledplugins-loginui-hooks-theming:
octoprint.plugin.loginui.theming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: loginui_theming_hook(*args, **kwargs)
Support theming of the login dialog, just in case the core UI is themed as well. Use to return a list of additional
CSS file URLs to inject into the login dialog HTML.
Example usage by a plugin:
.. code-block:: python
def loginui_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/loginui_theme.css")]
__plugin_hooks__ = {
"octoprint.plugin.loginui.theming": loginui_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
url_for like in the example above to be prepared for any configured prefix URLs.
:return: A list of additional CSS URLs to inject into the login dialog.
:rtype: A list of strings.
.. _sec-bundledplugins-loginui-sourcecode:
Source Code
-----------
The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/loginui``.
+14 -4
View File
@@ -100,7 +100,7 @@ Shutdown
The server is shutting down.
ClientOpened
A client has connected to the web server.
A client has connected to the push socket.
Payload:
@@ -109,12 +109,22 @@ ClientOpened
**Note:** Name changed in version 1.1.0
ClientClosed
A client has disconnected from the webserver
ClientAuthed
A client has authenticated a user session on the push socket.
Payload:
* ``remoteAddress``: the remote address (IP) of the client that disconnected
* ``remoteAddress``: the remote address (IP) of the client that authed. On the push socket only available with a
valid login session.
* ``username``: the name of the user who authed. On the push socket only available with a valid login session.
ClientClosed
A client has disconnected from the push socket.
Payload:
* ``remoteAddress``: the remote address (IP) of the client that disconnected. On the push socket only available
with a valid login session.
UserLoggedIn
A user logged in. On the push socket only available with a valid login session with admin rights.
+39 -4
View File
@@ -3,8 +3,20 @@
Access Control
==============
When Access Control is enabled, anonymous users (not logged in) will only see
the read-only parts of the UI which are the following:
OctoPrint's bundled access control feature allows granular permission control
over which users or user groups are allowed to access which parts of OctoPrint.
The default permissions will deny any kind of access to anonymous (not logged in)
users out of the box.
.. warning::
Please note that OctoPrint does *not* control the webcam and merely embeds it, and
thus also cannot limit access to it. If an anonymous user correctly guesses the
webcam URL, they will thus be able to see it.
If read-only access for anonymous users is enabled, anonymous users will have
read-only access to the following parts of the UI:
* printer state
* available gcode files and stats (upload is disabled)
@@ -16,8 +28,8 @@ the read-only parts of the UI which are the following:
* any components provided through plugins which are enabled for anonymous
users
Logged in users will get access to everything besides the Settings and System
Commands, which are admin-only.
Logged in users without admin flag will be allowed to access everything besides the
Settings and System Commands, which are admin-only.
If Access Control is disabled, everything is directly accessible. **That also
includes all administrative functionality as well as full control over the
@@ -39,6 +51,29 @@ internet or other untrusted networks!).
publicly reachable by everyone with an internet connection, even with access
control enabled.
.. _sec-features-access_control-hooks:
Available Extension Hooks
-------------------------
There are two hooks for plugins to utilize in order to
add new configurable permissions into the system and/or adjust the styling of the
login dialog.
.. _sec-features-access_control-hooks-permissions:
octoprint.access.permissions
............................
See :ref:`here <sec-plugins-hook-permissions>`.
.. _sec-features-access_control-hooks-loginui:
octoprint.plugin.loginui.theming
................................
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
.. _sec-features-access_control-rerunning_wizard:
Rerunning the wizard
File renamed without changes.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

+17 -3
View File
@@ -60,6 +60,7 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
__plugin_pythoncompat__ = ">=2.7,<4"
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
@@ -75,7 +76,10 @@ Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you somethin
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now.
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally
there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions
between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either
Python 2 or Python 3, and compatibility to both should be your goal.
.. _sec-plugins-gettingstarted-sayinghello:
@@ -86,7 +90,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this:
.. code-block:: python
:emphasize-lines: 4-8,13
:emphasize-lines: 4-8,14
:linenos:
# -*- coding: utf-8 -*-
@@ -101,6 +105,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
and restart OctoPrint. You now get this output in the log::
@@ -284,7 +289,7 @@ of information now defined twice:
The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
and ``__plugin_description__`` from ``__init__.py``:
and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implementation__`` and ``__plugin_pythoncompat__``:
.. code-block:: python
:linenos:
@@ -298,6 +303,7 @@ and ``__plugin_description__`` from ``__init__.py``:
def on_after_startup(self):
self._logger.info("Hello World!")
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
and restart OctoPrint::
@@ -324,6 +330,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
@@ -373,6 +380,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
@@ -443,6 +451,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Restart OctoPrint. You should see something like this::
@@ -480,6 +489,7 @@ Adjust your plugin's ``__init__.py`` like this:
return dict(url=self._settings.get(["url"]))
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
@@ -590,6 +600,7 @@ again since we don't use that anymore:
]
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
@@ -693,6 +704,7 @@ like so:
)
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
@@ -875,6 +887,7 @@ a reference to our CSS file:
)
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully
@@ -961,6 +974,7 @@ Then adjust our returned assets to include our LESS file as well:
)
__plugin_name__ = "Hello World"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = HelloWorldPlugin()
+24 -8
View File
@@ -1102,6 +1102,27 @@ octoprint.filemanager.preprocessor
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
:rtype: AbstractFileWrapper or None
.. _sec-plugins-hook-plugin-loginui-theming:
octoprint.plugin.loginui.theming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See :ref:`here <sec-bundledplugins-loginui-hooks-theming>`.
.. _sec-plugins-hook-plugin-pluginmanager-reconnect:
octoprint.plugin.pluginmanager.reconnect_hooks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See :ref:`here <sec-bundledplugins-pluginmanager-hooks-reconnect_hooks>`.
.. _sec-plugins-hook-plugin-softwareupdate-check_config:
octoprint.plugin.softwareupdate.check_config
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
.. _sec-plugins-hook-printer-factory:
octoprint.printer.factory
@@ -1273,8 +1294,7 @@ octoprint.server.api.after_request
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
Your plugin might need this to further restrict access to API methods.
.. important::
@@ -1289,8 +1309,7 @@ octoprint.server.api.before_request
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
Your plugin might need this to further restrict access to API methods.
.. important::
@@ -1305,8 +1324,7 @@ octoprint.server.http.access_validator
Allows adding additional access validators to the default tornado routers.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
"Force Login" plugin for a usage example.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further.
.. important::
@@ -1430,8 +1448,6 @@ octoprint.server.sockjs.authed
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
+2 -27
View File
@@ -20,31 +20,6 @@ from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROU
from octoprint.access.permissions import Permissions, OctoPrintPermission
from octoprint.vendor.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"`."""
@@ -151,8 +126,8 @@ class GroupManager(object):
return [group.key for group in groups]
def _to_groups(self, *groups):
return filter(lambda x: x is not None,
[self._to_group(g) for g in groups])
return list(filter(lambda x: x is not None,
[self._to_group(g) for g in groups]))
def _to_group(self, group):
# noinspection PyCompatibility
+34 -13
View File
@@ -79,6 +79,22 @@ class OctoPrintPermission(Permission):
def get_description(self):
return self._description
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
return True
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
@@ -259,8 +275,9 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
default_groups=[ADMIN_GROUP])
STATUS = OctoPrintPermission("Status",
gettext("Allows to gather status information, e.g. job progress, "
"printer state, temperatures, ..."),
gettext("Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP])
@@ -292,27 +309,26 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
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,
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files"),
RoleNeed("files_delete"), FILES_LIST,
RoleNeed("files_delete"),
default_groups=[USER_GROUP])
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"), FILES_LIST,
RoleNeed("files_select"),
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,
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
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,
gettext("Allows access to the GCODE viewer if the \"File Download\""
"permission is also set."),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP])
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
@@ -351,8 +367,13 @@ class Permissions(with_metaclass(PermissionsMetaClass)):
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP])
SETTINGS = OctoPrintPermission("Settings",
gettext("Allows to manage settings"),
SETTINGS_READ = OctoPrintPermission("Settings Access",
gettext("Allows to read non sensitive settings. Mandatory for the "
"default UI to work."),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP])
SETTINGS = OctoPrintPermission("Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True)
+17 -9
View File
@@ -105,11 +105,11 @@ class UserManager(GroupChangeListener, object):
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
self._logger.debug("Logged in user: %r" % user)
self._logger.info("Logged in user: {}".format(user.get_id()))
return user
def logout_user(self, user):
def logout_user(self, user, stale=False):
if user is None or user.is_anonymous or isinstance(user, AdminUser):
return
@@ -129,23 +129,27 @@ class UserManager(GroupChangeListener, object):
pass
if sessionid in self._session_users_by_session:
del self._session_users_by_session[sessionid]
try:
del self._session_users_by_session[sessionid]
except KeyError:
pass
for listener in self._login_status_listeners:
try:
listener.on_user_logged_out(user)
listener.on_user_logged_out(user, stale=stale)
except Exception:
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
self._logger.debug("Logged out user: %r" % user)
self._logger.info("Logged out user: {}".format(user.get_id()))
def _cleanup_sessions(self):
for session, user in list(self._session_users_by_session.items()):
if not isinstance(user, SessionUser):
continue
if user.created + (24 * 60 * 60) < monotonic_time():
self.logout_user(user)
self._logger.info("Cleaning up user session {} for user {}".format(session, user.get_id()))
self.logout_user(user, stale=True)
@staticmethod
def create_password_hash(password, salt=None, settings=None):
@@ -436,7 +440,7 @@ class LoginStatusListener(object):
def on_user_logged_in(self, user):
pass
def on_user_logged_out(self, user):
def on_user_logged_out(self, user, stale=False):
pass
def on_user_modified(self, user):
@@ -1125,6 +1129,12 @@ class User(UserMixin):
def groups(self):
return list(self._groups)
@property
def effective_permissions(self):
if self._permissions is None:
return []
return list(filter(lambda p: p is not None and self.has_permission(p), Permissions.all()))
@property
def needs(self):
needs = set()
@@ -1143,8 +1153,6 @@ class User(UserMixin):
return self.has_needs(*permission.needs)
def has_needs(self, *needs):
if Permissions.ADMIN in self._permissions:
return True
return set(needs).issubset(self.needs)
def __repr__(self):
+2
View File
@@ -46,6 +46,8 @@ class Events(object):
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
+8 -5
View File
@@ -107,7 +107,7 @@ class MultiStream(io.RawIOBase):
their contents in the order they are provided to the constructor.
Arguments:
*streams (io.IOBase): One or more streams to concatenate.
*streams (io.RawIOBase): One or more streams to concatenate.
"""
def __init__(self, *streams):
io.RawIOBase.__init__(self)
@@ -159,10 +159,12 @@ class LineProcessorStream(io.RawIOBase):
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Arguments:
input_stream (io.IOBase): The stream to process on the fly.
input_stream (io.RawIOBase): The stream to process on the fly.
"""
def __init__(self, input_stream):
@@ -220,10 +222,11 @@ class LineProcessorStream(io.RawIOBase):
wrapper `input_stream`.
Arguments:
line (str): The line as read from `self.input_stream`
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
Returns:
str or None: The processed version of the line (might also be multiple lines), or None if the line is to be
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
+32 -2
View File
@@ -130,6 +130,14 @@ class PluginInfo(object):
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = '__plugin_hidden__'
"""
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = '__plugin_hooks__'
""" Module attribute from which to retrieve the plugin's provided hooks. """
@@ -444,6 +452,18 @@ class PluginInfo(object):
default=">=2.7,<3",
incl_metadata=True)
@property
def hidden(self):
"""
Hidden flag.
Returns:
bool: Whether the plugin should be flagged as hidden or not
"""
return self._get_instance_attribute(self.__class__.attr_hidden,
default=False,
incl_metadata=True)
@property
def hooks(self):
"""
@@ -600,6 +620,16 @@ class PluginInfo(object):
result[key] = a.value.args[0].s
break
for key in (self.__class__.attr_hidden,):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Name) and a.value.id in ("True", "False"):
result[key] = bool(a.value.id)
break
except SyntaxError:
self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key))
self.invalid_syntax = True
@@ -1008,7 +1038,7 @@ class PluginManager(object):
# 1st pass: loading the plugins
for name, plugin in added.items():
try:
if not plugin.blacklisted and not plugin.forced_disabled:
if not plugin.blacklisted and not plugin.forced_disabled and not plugin.incompatible:
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
except PluginNeedsRestart:
pass
@@ -1022,7 +1052,7 @@ class PluginManager(object):
# 2nd pass: enabling those plugins that need enabling
for name, plugin in added.items():
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.loaded and not plugin.forced_disabled and not plugin.incompatible:
if plugin.blacklisted:
self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin))
continue
+4 -1
View File
@@ -1391,9 +1391,12 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
# noinspection PyMethodMayBeStatic
def is_blueprint_protected(self):
"""
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
Whether a login session by a registered user is needed to access the blueprint's endpoints. Requiring
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
are always accessible.
If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your
permissions checks explicitly.
"""
return True
@@ -242,6 +242,9 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return NO_CONTENT
def is_blueprint_protected(self):
return False
##~~ EventHandlerPlugin
def on_event(self, event, payload):
+3
View File
@@ -322,6 +322,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
return flask.jsonify(started=True)
def is_blueprint_protected(self):
return False
##~~ tornado hook
def route_hook(self, *args, **kwargs):
@@ -13,8 +13,8 @@ from octoprint.util.version import get_octoprint_version_string, is_released_oct
from flask import jsonify
from flask_babel import gettext
SENTRY_URL_SERVER = "https://e8dadc4407e74f159e77919e551bd1a7@sentry.io/1373987"
SENTRY_URL_COREUI = "https://1da95af9c999483ba5705577f24d1e28@sentry.io/1374096"
SENTRY_URL_SERVER = "https://24203d6e841d4f708846e77553dfb277@sentry.io/1373987"
SENTRY_URL_COREUI = "https://84a46e028bd54b768165817f64a35bb6@sentry.io/1374096"
SETTINGS_DEFAULTS = dict(enabled=False,
enabled_unreleased=False,
@@ -114,6 +114,9 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
self._set_logging_levels(json_data)
return self.get_logging_levels_api()
def is_blueprint_protected(self):
return False
def _get_usage(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
+120
View File
@@ -0,0 +1,120 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from flask_babel import gettext
from octoprint.access.permissions import Permissions
from collections import defaultdict
import threading
class LoginUiPlugin(octoprint.plugin.UiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin):
MAX_BACKLOG_LEN = 100
# noinspection PyMissingConstructor
def __init__(self):
self._message_backlog = defaultdict(list)
self._message_backlog_mutex = threading.RLock()
@property
def active(self):
# we are only active if ACL is enabled AND configured
return self._user_manager.enabled and self._user_manager.has_been_customized()
def get_assets(self):
return dict(
js=["js/viewmodel.js"]
)
def will_handle_ui(self, request):
if not self.active:
# not active, not responsible
return False
from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException
from octoprint.server.util.flask import passive_login
# first try to login via api key & authorization header, just in case that's set
try:
if loginUserFromApiKey():
# successful? No need for handling the UI
return False
except InvalidApiKeyException:
pass # ignored
if loginUserFromAuthorizationHeader():
# successful? No need for handling the UI
return False
# then try a passive login
passive_login()
if Permissions.STATUS.can() and Permissions.SETTINGS_READ.can():
# Status & settings_read permission? No need to handle UI
return False
else:
return True
def on_ui_render(self, now, request, render_kwargs):
from flask import render_template, make_response
def add_additional_assets(hook):
result = []
for name, hook in self._plugin_manager.get_hooks(hook).items():
try:
assets = hook()
if isinstance(assets, (tuple, list)):
result += assets
except:
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name),
extra=dict(plugin=name))
return result
additional_assets = []
additional_assets += add_additional_assets("octoprint.plugin.loginui.theming")
# backwards compatibility to old forcelogin plugin which was replaced by this one
additional_assets += add_additional_assets("octoprint.plugin.forcelogin.theming")
render_kwargs.update(dict(loginui_theming=additional_assets))
return make_response(render_template("loginui_index.jinja2", **render_kwargs))
def get_ui_custom_tracked_files(self):
from os.path import join as opj
paths = [opj("static", "css", "loginui.css"),
opj("static", "js", "main.js"),
opj("static", "js", "viewmodel.js"),
opj("static", "less", "loginui.less"),
opj("templates", "parts", "loginui_css.jinja2"),
opj("templates", "parts", "loginui_javascripts.jinja2"),
opj("templates", "loginui_index.jinja2")]
return [opj(self._basefolder, path) for path in paths]
def get_ui_preemptive_caching_enabled(self):
return False
def get_sorting_key(self, context=None):
if context == "UiPlugin.on_ui_render":
# If a plugin *really* wants to come before this plugin, it'll have to turn to negative numbers.
#
# This is obviously discouraged for security reasons, but very specific setups might make it necessary,
# so we make it possible. If this should get abused long term we can always turn this into -inf.
return 0
__plugin_name__ = "Login UI"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Displays a standalone login UI if needed"
__plugin_disabling_discouraged__ = gettext("Without this plugin there will be no dedicated login page for users in "
"case anonymous read only access is disabled - instead your non logged in "
"visitors will get a broken UI.")
__plugin_hidden__ = True
__plugin_implementation__ = LoginUiPlugin()
@@ -0,0 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
@@ -0,0 +1,59 @@
/*
* Will get included into the login dialog, NOT into the regular OctoPrint
* web application.
*/
$(function() {
var overlayElement = $("#login-overlay");
var errorElement = $("#login-error");
var offlineElement = $("#login-offline");
var buttonElement = $("#login-button");
var reconnectElement = $("#login-reconnect");
buttonElement.click(function() {
var usernameElement = $("#login-user");
var passwordElement = $("#login-password");
var rememberElement = $("#login-remember");
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.prop("checked");
overlayElement.addClass("in");
errorElement.removeClass("in");
OctoPrint.browser.login(username, password, remember)
.done(function() {
location.reload();
})
.fail(function() {
usernameElement.val("");
passwordElement.val("");
overlayElement.removeClass("in");
errorElement.addClass("in");
});
return false;
});
var OctoPrint = window.OctoPrint;
OctoPrint.options.baseurl = BASE_URL;
OctoPrint.socket.onConnected = function() {
buttonElement.prop("disabled", false);
offlineElement.removeClass("in");
};
OctoPrint.socket.onDisconnected = function() {
buttonElement.prop("disabled", true);
offlineElement.addClass("in");
};
reconnectElement.click(function() {
OctoPrint.socket.reconnect();
});
OctoPrint.socket.connect();
});
@@ -0,0 +1,31 @@
/*
* View model that takes care to redirect to / on logout in the regular
* OctoPrint web application.
*/
$(function() {
function LoginUiViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
self.coreWizardAcl = parameters[2];
self.onUserLoggedOut = self.onUserPermissionsChanged = function() {
// reload if user now lacks STATUS & SETTINGS_READ permissions and is not in first run setup, or is in
// first run setup but the ACL wizard has already run and ACL is active
if (!self.loginState.hasAllPermissions(self.access.permissions.STATUS, self.access.permissions.SETTINGS_READ)
&& (!CONFIG_FIRST_RUN || (self.coreWizardAcl
&& self.coreWizardAcl.setup()
&& self.coreWizardAcl.decision()))) {
location.reload();
}
};
}
OCTOPRINT_VIEWMODELS.push({
construct: LoginUiViewModel,
dependencies: ["loginStateViewModel", "accessViewModel", "coreWizardAclViewModel"],
optional: ["coreWizardAclViewModel"]
});
});
@@ -0,0 +1,90 @@
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
.form-signin-heading, .checkbox {
margin-bottom: 10px;
}
input[type="text"], input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
}
#login-error,
#login-offline {
display: none;
&.in {
display: block;
}
}
#login-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
display: none;
&.in {
display: block;
}
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
.outer {
display: table;
width: 100%;
height: 100%;
.inner {
display: table-cell;
vertical-align: middle;
.content {
text-align: center;
color: white;
}
}
}
}
}
@@ -0,0 +1,47 @@
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OctoPrint Login</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
<link rel="mask-icon" href="{{ url_for('static', filename='img/mask.svg') }}" color="#56BE37">
<link rel="mask-icon-theme" href="{{ url_for('static', filename='img/mask-theme.svg') }}" color="#56BE37">
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
{% include "parts/loginui_css.jinja2" %}
{% include "parts/loginui_javascripts.jinja2" %}
</head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username')|edq }}" autofocus>
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password')|edq }}">
<span class="pull-right"><small><a href="https://faq.octoprint.org/forgotten-password" id="login-forgotpassword" target="_blank" tabindex="-1">{{ _('Forgot password?') }}</a></small></span>
<label class="checkbox">
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
</label>
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
</form>
</div>
<div id="login-overlay">
<div class="background"></div>
<div class="wrapper">
<div class="outer">
<div class="inner">
<div class="content">
<i class="fa fa-spinner fa-spin fa-4x"></i>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,10 @@
<!-- le CSS -->
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
<link rel="stylesheet" href="{{ url_for("plugin.loginui.static", filename="css/loginui.css") }}">
{% for url in forcelogin_theming %}
<link rel="stylesheet" href="{{ url }}">
{% endfor %}
@@ -0,0 +1,15 @@
<!-- le javascript -->
<script>
var BASE_URL = "{{ url_for('index') }}";
</script>
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
{% assets "js_client" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
<script src="{{ url_for("plugin.loginui.static", filename="js/main.js") }}"></script>
+18 -1
View File
@@ -12,6 +12,9 @@ import sarge
from flask_babel import gettext
from octoprint.util import RepeatedTimer
from octoprint.access.permissions import Permissions
from octoprint.access.groups import USER_GROUP
import octoprint.plugin
import octoprint.events
@@ -187,6 +190,17 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
self._throttle_overheat = False
self._throttle_functional = True
# Additional permissions hook
def get_additional_permissions(self):
return [
dict(key="STATUS",
name="Status",
description=gettext("Allows to check for the Pi's throttling status and environment info"),
roles=["check"],
default_groups=[USER_GROUP])
]
#~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
@@ -200,6 +214,8 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
#~~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
return flask.abort(403)
result = dict(throttle_state=self._throttle_state.as_dict())
result.update(self.get_additional_environment())
return flask.jsonify(**result)
@@ -336,7 +352,8 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
global __plugin_helpers__
@@ -3,6 +3,9 @@ $(function() {
function PiSupportViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
self.model = ko.observable();
self.currentUndervoltage = ko.observable(false);
@@ -13,6 +16,10 @@ $(function() {
self.pastIssue = ko.observable(false);
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) {
return;
}
OctoPrint.plugins.pi_support.get()
.done(function(response) {
// Raspberry Pi model
@@ -70,11 +77,7 @@ $(function() {
+ "<p><small>" + gettext("Click the symbol in the navbar for more information.") + "</small></p>";
});
self.onStartup = function() {
self.requestData();
};
self.onServerReconnect = function() {
self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function() {
self.requestData();
};
@@ -82,6 +85,7 @@ $(function() {
if (plugin !== "pi_support") return;
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
if (data.type !== "throttle_state") return;
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) return;
self.fromThrottleState(data.state);
}
@@ -89,6 +93,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: PiSupportViewModel,
elements: ["#navbar_plugin_pi_support"]
elements: ["#navbar_plugin_pi_support"],
dependencies: ["loginStateViewModel", "accessViewModel"]
});
});
@@ -286,6 +286,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
except Exception as e:
self._logger.warning("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
def is_blueprint_protected(self):
return False
##~~ EventHandlerPlugin
def on_event(self, event, payload):
@@ -780,7 +783,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return True
def command_toggle(self, plugin, command):
if plugin.key == "pluginmanager":
if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled):
return make_response("Can't enable/disable Plugin Manager", 400)
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
@@ -1161,7 +1164,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hidden = self._settings.get(["hidden"])
result = []
for key, plugin in plugins.items():
if key in hidden:
if key in hidden or (plugin.bundled and plugin.hidden):
continue
result.append(self._to_external_plugin(plugin))
@@ -1182,6 +1185,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
enabled=plugin.enabled,
blacklisted=plugin.blacklisted,
forced_disabled=plugin.forced_disabled,
incompatible=plugin.incompatible,
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_victim", False) and plugin.key in self._pending_enable),
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key in self._pending_disable),
@@ -1234,6 +1238,7 @@ __plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
__plugin_license__ = "AGPLv3"
__plugin_hidden__ = True
def __plugin_load__():
global __plugin_implementation__
@@ -191,15 +191,16 @@ $(function() {
var command = self._getToggleCommand(data);
var not_safemode_victim = !data.safe_mode_victim;
var not_blacklisted = !data.blacklisted;
return self.enableManagement() && (command == "disable" || (not_safemode_victim && not_blacklisted)) && data.key != 'pluginmanager';
var not_incompatible = !data.incompatible;
return self.enableManagement() && (command === "disable" || (not_safemode_victim && not_blacklisted && not_incompatible)) && data.key != 'pluginmanager';
};
self.enableUninstall = function(data) {
return self.enableManagement()
&& (data.origin != "entry_point" || self.pipAvailable())
&& (data.origin !== "entry_point" || self.pipAvailable())
&& data.managable
&& !data.bundled
&& data.key != 'pluginmanager'
&& data.key !== 'pluginmanager'
&& !data.pending_uninstall;
};
@@ -84,7 +84,7 @@
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i class="fa fa-bolt" title="{{ _('Incompatible to OctoPrint or the underlying Python environment')|edq }}" data-bind="visible: incompatible"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
@@ -668,6 +668,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
to_be_checked, checks = self.perform_updates(targets=targets, force=force)
return flask.jsonify(dict(order=to_be_checked, checks=checks))
def is_blueprint_protected(self):
return False
#~~ Asset API
def get_assets(self):
+13 -5
View File
@@ -100,7 +100,7 @@ import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
from octoprint.server.util import loginFromApiKeyRequestHandler, corsRequestHandler, \
corsResponseHandler
corsResponseHandler, requireLoginRequestHandler
from octoprint.server.util.flask import PreemptiveCache
VERSION = __version__
@@ -478,6 +478,9 @@ class Server(object):
class TaggedFuncsPrinter(wrapt.ObjectProxy):
def __getattribute__(self, attr):
__wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__("__wrapped__")
if attr == "__wrapped__":
return __wrapped__
item = getattr(__wrapped__, attr)
if callable(item) \
and ("tags" in item.__code__.co_varnames or "kwargs" in item.__code__.co_varnames) \
@@ -1326,6 +1329,9 @@ class Server(object):
blueprint.before_request(loginFromApiKeyRequestHandler)
blueprint.after_request(corsResponseHandler)
if plugin.is_blueprint_protected():
blueprint.before_request(requireLoginRequestHandler)
url_prefix = "/plugin/{name}".format(name=name)
app.register_blueprint(blueprint, url_prefix=url_prefix)
@@ -1350,7 +1356,8 @@ class Server(object):
before_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.before_request")
after_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.after_request")
for plugin, hook in before_hooks.items():
for name, hook in before_hooks.items():
plugin = octoprint.plugin.plugin_manager().get_plugin(name)
for blueprint in blueprints:
try:
result = hook(plugin=plugin)
@@ -1359,9 +1366,10 @@ class Server(object):
blueprint.before_request(h)
except Exception:
self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin),
extra=dict(plugin=plugin))
extra=dict(plugin=name))
for plugin, hook in after_hooks.items():
for name, hook in after_hooks.items():
plugin = octoprint.plugin.plugin_manager().get_plugin(name)
for blueprint in blueprints:
try:
result = hook(plugin=plugin)
@@ -1370,7 +1378,7 @@ class Server(object):
blueprint.after_request(h)
except Exception:
self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin),
extra=dict(plugin=plugin))
extra=dict(plugin=name))
def _setup_mimetypes(self):
# Safety measures for Windows... apparently the mimetypes module takes its translation from the windows
+8 -1
View File
@@ -289,6 +289,13 @@ def _logout(user):
octoprint.server.userManager.logout_user(user)
@api.route("/currentuser", methods=["GET"])
def get_current_user():
return jsonify(name=current_user.get_name(),
permissions=[permission.key for permission in current_user.effective_permissions],
groups=[group.key for group in current_user.groups])
#~~ Test utils
@@ -380,7 +387,7 @@ def _test_path(data):
try:
test_path = os.path.join(path, ".testballoon.txt")
with io.open(test_path, 'wb') as f:
f.write("Test")
f.write(b"Test")
os.remove(test_path)
except Exception:
logging.getLogger(__name__).exception("Error while testing if {} is really writable".format(path))
+1 -1
View File
@@ -471,7 +471,7 @@ def uploadGcodeFile(target):
@api.route("/files/<string:target>/<path:filename>", methods=["GET"])
@Permissions.FILES_DOWNLOAD.require(403)
@Permissions.FILES_LIST.require(403)
def readGcodeFile(target, filename):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
+4 -8
View File
@@ -14,7 +14,6 @@ from octoprint.access.permissions import Permissions
@api.route("/job", methods=["POST"])
@no_firstrun_access
@Permissions.PRINT.require(403)
def controlJob():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
@@ -57,13 +56,10 @@ def controlJob():
printer.resume_print(tags=tags, user=user)
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, user=user)
elif 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, user=user)
return NO_CONTENT
-1
View File
@@ -478,7 +478,6 @@ def printerCommand():
@no_firstrun_access
@Permissions.CONTROL.require(403)
def getCustomControls():
# TODO: document me
customControls = settings().get(["controls"])
return jsonify(controls=customControls)
+5 -2
View File
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
from flask import request, jsonify, make_response
from flask import request, jsonify, make_response, abort
from flask_login import current_user
from werkzeug.exceptions import BadRequest
@@ -75,8 +75,11 @@ def _etag(lm=None):
@api.route("/settings", methods=["GET"])
@with_revalidation_checking(etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
unless=lambda: request.values.get("force", "false") in valid_boolean_trues or settings().getBoolean(["server", "firstRun"]))
def getSettings():
if not Permissions.SETTINGS_READ.can() and not settings().getBoolean(["server", "firstRun"]):
abort(403)
s = settings()
connectionOptions = printer.__class__.get_connection_options()
+14 -2
View File
@@ -102,6 +102,18 @@ def loginUser(user, remember=False):
return False
def requireLoginRequestHandler():
if _flask.request.endpoint.endswith(".static"):
return
if not (octoprint.server.userManager.enabled and octoprint.server.userManager.has_been_customized()):
return
user = flask_login.current_user
if user is None or user.is_anonymous or not user.is_active:
return flask.make_response("Forbidden", 403)
def corsRequestHandler():
"""
``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled
@@ -241,9 +253,9 @@ def get_user_for_authorization_header(header):
if not octoprint.server.userManager.enabled:
return None
user = octoprint.server.userManager.findUser(userid=name)
user = octoprint.server.userManager.find_user(userid=name)
if settings().getBoolean(["accessControl", "checkBasicAuthenticationPassword"]) \
and not octoprint.server.userManager.checkPassword(name, password):
and not octoprint.server.userManager.check_password(name, password):
# password check enabled and password don't match
return None
+2 -1
View File
@@ -584,7 +584,8 @@ def passive_login():
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
and settings().get(["accessControl", "autologinAs"]) is not None \
and settings().get(["accessControl", "localNetworks"]) is not None \
and not "active_logout" in flask.request.cookies:
and not "active_logout" in flask.request.cookies \
and remote_address:
# attempt local autologin
autologin_as = settings().get(["accessControl", "autologinAs"])
local_networks = _local_networks()
+37 -2
View File
@@ -78,12 +78,15 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
"*": []}
_event_payload_processors = {Events.CLIENT_OPENED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else dict()],
Events.CLIENT_AUTHED: [lambda user, payload: payload if user.has_permission(Permissions.ADMIN) else dict()],
"*": []}
_emit_permissions = {"connected": [],
"reauthRequired": [],
"*": [Permissions.STATUS]}
_unauthed_backlog_max = 100
def __init__(self, printer, fileManager, analysisQueue, userManager, groupManager, eventManager, pluginManager, session):
if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session):
session = JsonEncodingSessionWrapper(session)
@@ -99,6 +102,9 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
self._messageBacklog = []
self._messageBacklogMutex = threading.Lock()
self._unauthed_backlog = []
self._unauthed_backlog_mutex = threading.RLock()
self._printer = printer
self._fileManager = fileManager
self._analysisQueue = analysisQueue
@@ -119,6 +125,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
self._emit_hooks = self._pluginManager.get_hooks("octoprint.server.sockjs.emit")
self._registered = False
self._authed = False
@staticmethod
def _get_remote_address(info):
@@ -304,11 +311,15 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
with self._temperatureBacklogMutex:
self._temperatureBacklog.append(data)
def on_user_logged_out(self, user):
def on_user_logged_out(self, user, stale=False):
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._on_logout()
self._sendReauthRequired("logout")
if stale:
self._sendReauthRequired("stale")
else:
self._sendReauthRequired("logout")
def on_user_modified(self, user):
if user.get_id() == self._user.get_id():
@@ -411,6 +422,13 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
permissions = [x() if callable(x) else x for x in permissions]
if not self._user or not all(map(lambda p: self._user.has_permission(p), permissions)):
if not self._authed:
with self._unauthed_backlog_mutex:
if len(self._unauthed_backlog) < self._unauthed_backlog_max:
self._unauthed_backlog.append((type, payload))
self._logger.debug("Socket message held back until permissions cleared, added to backlog: {}".format(type))
else:
self._logger.debug("Socket message held back, but backlog full. Throwing message away: {}".format(type))
return
self._do_emit(type, payload)
@@ -428,6 +446,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
self._user = user
self._logger.info("User {} logged in on the socket from client {}".format(user.get_name(),
self._remoteAddress))
self._authed = True
for name, hook in self._authed_hooks.items():
try:
@@ -436,8 +455,24 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
self._logger.exception("Error processing authed hook handler for plugin {}".format(name),
extra=dict(plugin=name))
# if we have a backlog from being unauthed, process that now
with self._unauthed_backlog_mutex:
backlog = self._unauthed_backlog
self._unauthed_backlog = []
if len(backlog):
self._logger.debug("Sending {} messages on the socket that were held back".format(len(backlog)))
for message, payload in backlog:
self._do_emit(message, payload)
# trigger ClientAuthed event
octoprint.events.eventManager().fire(octoprint.events.Events.CLIENT_AUTHED,
payload=dict(username=user.get_name(),
remoteAddress=self._remoteAddress))
def _on_logout(self):
self._user = self._userManager.anonymous_user_factory()
self._authed = False
for name, hook in self._authed_hooks.items():
try:
+10 -2
View File
@@ -12,7 +12,7 @@ import io
from past.builtins import basestring
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort, Response
import octoprint.plugin
@@ -418,8 +418,12 @@ def index():
plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True)
if plugin is not None and isinstance(plugin.implementation, octoprint.plugin.UiPlugin):
response = plugin_view(plugin.implementation)
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
response.headers["X-Ui-Plugin"] = plugin._identifier
else:
response = default_view()
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
response.headers["X-Ui-Plugin"] = "_default"
else:
# select view from plugins and fall back on default view if no plugin will handle it
@@ -430,6 +434,8 @@ def index():
# plugin claims responsibility, let it render the UI
response = plugin_view(plugin)
if response is not None:
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
response.headers["X-Ui-Plugin"] = plugin._identifier
break
else:
_logger.warning("UiPlugin {} returned an empty response".format(plugin._identifier))
@@ -438,6 +444,8 @@ def index():
extra=dict(plugin=plugin._identifier))
else:
response = default_view()
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
response.headers["X-Ui-Plugin"] = "_default"
if response is None:
return abort(404)
@@ -593,7 +601,7 @@ def fetch_template_data(refresh=False):
templates["tab"]["entries"] = dict(
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)() && visible()")),
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)")),
gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode", styles=["display: none;"], data_bind="visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)")),
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)"))
)
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -0,0 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
@@ -0,0 +1,71 @@
/*
* Will get included into the login dialog, NOT into the regular OctoPrint
* web application.
*/
$(function() {
var overlayElement = $("#login-overlay");
var errorElement = $("#login-error");
var offlineElement = $("#login-offline");
var buttonElement = $("#login-button");
var reconnectElement = $("#login-reconnect");
buttonElement.click(function() {
var usernameElement = $("#login-user");
var passwordElement = $("#login-password");
var rememberElement = $("#login-remember");
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.prop("checked");
overlayElement.addClass("in");
errorElement.removeClass("in");
OctoPrint.browser.login(username, password, remember)
.done(function() {
location.reload();
})
.fail(function() {
usernameElement.val("");
passwordElement.val("");
overlayElement.removeClass("in");
errorElement.addClass("in");
});
return false;
});
var OctoPrint = window.OctoPrint;
OctoPrint.options.baseurl = BASE_URL;
var offlineTimer = undefined;
var clearOfflineTimer = function() {
if (offlineTimer !== undefined) {
window.clearTimeout(offlineTimer);
offlineTimer = undefined;
}
};
OctoPrint.socket.onConnected = function() {
clearOfflineTimer();
buttonElement.prop("disabled", false);
offlineElement.removeClass("in");
};
OctoPrint.socket.onDisconnected = function() {
clearOfflineTimer();
offlineTimer = window.setTimeout(function() {
buttonElement.prop("disabled", true);
offlineElement.addClass("in");
}, 1000);
};
reconnectElement.click(function() {
OctoPrint.socket.reconnect();
});
OctoPrint.socket.connect();
});
@@ -0,0 +1,90 @@
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
.form-signin-heading, .checkbox {
margin-bottom: 10px;
}
input[type="text"], input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
}
#login-error,
#login-offline {
display: none;
&.in {
display: block;
}
}
#login-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
display: none;
&.in {
display: block;
}
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
.outer {
display: table;
width: 100%;
height: 100%;
.inner {
display: table-cell;
vertical-align: middle;
.content {
text-align: center;
color: white;
}
}
}
}
}
+31 -10
View File
@@ -9,10 +9,13 @@
var normalClose = 1000;
var OctoPrintSocketClient = function(base) {
var self = this;
this.base = base;
this.options = {
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100],
connectTimeout: 5000,
rateSlidingWindowSize: 20
};
@@ -24,6 +27,16 @@
this.rateThrottleFactor = 1;
this.rateBase = 500;
this.rateLastMeasurements = [];
this.connectTimeout = undefined;
this.onMessage("connected", function() {
// Make sure to clear connection timeout on connect
if (self.connectTimeout) {
clearTimeout(self.connectTimeout);
self.connectTimeout = undefined;
}
})
};
OctoPrintSocketClient.prototype.propagateMessage = function(event, data) {
@@ -98,15 +111,15 @@
OctoPrintSocketClient.prototype.connect = function(opts) {
opts = opts || {};
this.disconnect();
var self = this;
var url = this.base.options.baseurl;
self.disconnect();
var url = self.base.options.baseurl;
if (!_.endsWith(url, "/")) {
url += "/";
}
var self = this;
var onOpen = function() {
self.reconnecting = false;
self.reconnectTrial = 0;
@@ -114,7 +127,7 @@
};
var onClose = function(e) {
if (e.code == normalClose) {
if (e.code === normalClose) {
return;
}
@@ -139,10 +152,17 @@
});
};
this.socket = new SockJS(url + "sockjs", undefined, opts);
this.socket.onopen = onOpen;
this.socket.onclose = onClose;
this.socket.onmessage = onMessage;
if (self.connectTimeout) {
clearTimeout(self.connectTimeout);
}
self.connectTimeout = setTimeout(function() {
self.onConnectTimeout();
}, self.options.connectTimeout);
self.socket = new SockJS(url + "sockjs", undefined, opts);
self.socket.onopen = onOpen;
self.socket.onclose = onClose;
self.socket.onmessage = onMessage;
};
OctoPrintSocketClient.prototype.reconnect = function() {
@@ -152,7 +172,7 @@
};
OctoPrintSocketClient.prototype.disconnect = function() {
if (this.socket != undefined) {
if (this.socket !== undefined) {
this.socket.close();
}
};
@@ -169,6 +189,7 @@
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
OctoPrintSocketClient.prototype.onConnected = function() {};
OctoPrintSocketClient.prototype.onDisconnected = function(code) {};
OctoPrintSocketClient.prototype.onConnectTimeout = function() {};
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
this.increaseRate();
+9 -2
View File
@@ -45,7 +45,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
self.connect = function() {
if (self._connectedDeferred) {
self._connectedDeferred.reject();
self._connectedDeferred.reject("reconnect");
}
self._connectedDeferred = $.Deferred();
OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG});
@@ -54,7 +54,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
self.reconnect = function() {
if (self._connectedDeferred) {
self._connectedDeferred.reject();
self._connectedDeferred.reject("reconnect");
}
self._connectedDeferred = $.Deferred();
OctoPrint.socket.reconnect();
@@ -121,6 +121,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
}
};
self._onConnectTimeout = function() {
if (self._connectedDeferred) {
self._connectedDeferred.reject("timeout");
}
};
self._onConnectMessage = function(event) {
if (self._initializedDeferred) {
self._initializedDeferred.reject();
@@ -399,6 +405,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
OctoPrint.socket.onDisconnected = self._onDisconnected;
OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
OctoPrint.socket.onConnectTimeout = self._onConnectTimeout;
OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
OctoPrint.socket
+4
View File
@@ -808,6 +808,10 @@ $(function() {
// make sure we trigger onServerConnect should we dis- and reconnect to the server
dataUpdater.connectCallback = onServerConnect;
// we are now connected to the server and need to change the loading message - jquery instead of
// binding because no bindings yet
$("#page-container-loading-header").html(gettext("Loading OctoPrint's UI, please wait..."));
// perform passive login first
onServerConnect()
.done(function() {
@@ -2,57 +2,24 @@ $(function() {
function UiStateViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
self.loading = ko.observable(CONFIG_LOADINGANIMATION);
self.loading_error = ko.observable(false);
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();
return !self.loading();
});
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;
}
}
});
};
self.showLoadingError = function(error) {
log.error("Loading error: " + error + " Please check prior messages and 'octoprint.log' for possible reasons.");
// we can't do this with bindings since the bindings are not initialized yet if we need this
$("#page-container-loading-header").text("Loading failed");
$("#page-container-loading-spinner").removeClass("fa-spinner fa-spin").addClass("fa-exclamation-triangle text-error");
$("#page-container-loading-error").html(error + " " + _.sprintf("Please check your <a href='%(browser)s' target='_blank' rel='noopener noreferrer'>browser's error console</a> and <code><a href='%(octoprint)s' target='_blank' rel='noopener noreferrer'>octoprint.log</a></code> for possible reasons.", {browser: "https://faq.octoprint.org/browser-console", octoprint: "https://faq.octoprint.org/logs"})).show();
$("#page-container-loading-error").html(error + " " + _.sprintf("Please check your <a href='%(browser)s' target='_blank' rel='noopener noreferrer'>browser's error console</a> and <code><a href='%(octoprint)s' target='_blank' rel='noopener noreferrer'>octoprint.log</a></code> for possible reasons.Also make sure that the server is actually running by reloading this page.", {browser: "https://faq.octoprint.org/browser-console", octoprint: "https://faq.octoprint.org/logs"})).show();
};
}
OCTOPRINT_VIEWMODELS.push({
construct: UiStateViewModel,
dependencies: ["loginStateViewModel", "accessViewModel"],
elements: ["#page-container-main", "#page-container-loading", "#page-container-needlogin"]
elements: ["#page-container-main", "#page-container-loading"]
});
});
-29
View File
@@ -1544,35 +1544,6 @@ input[type="number"].input-nospin {
}
}
// page wide login form
#page-container-needlogin {
background-color: #ffffff;
.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;
+2 -19
View File
@@ -20,8 +20,7 @@
<noscript>
<style type="text/css">
#page-container-main,
#page-container-loading,
#page-container-needlogin {
#page-container-loading {
display:none;
}
</style>
@@ -45,7 +44,7 @@
<div class="outer">
<div class="inner">
<div class="content">
<h1 id="page-container-loading-header">{{ _('Loading OctoPrint\'s UI, please wait...') }}</h1>
<h1 id="page-container-loading-header">{{ _('Connecting to OctoPrint\'s server...') }}</h1>
<i id="page-container-loading-spinner" class="fa fa-spinner fa-spin fa-4x"></i>
<p id="page-container-loading-error" style="display: none"></p>
</div>
@@ -55,22 +54,6 @@
</div>
{% endif %}
<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')|edq }}" autofocus>
<input type="password" data-bind="value: login_password" class="input-block-level" placeholder="{{ _('Password')|edq }}">
<span class="pull-right"><small><a href="https://faq.octoprint.org/forgotten-password" id="login-forgotpassword" target="_blank" tabindex="-1">{{ _('Forgot password?') }}</a></small></span>
<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>
<div class="page-container" id="page-container-main" {% if enableLoadAnimation %}style="display: none"{% endif %} data-bind="visible: visible">
<!-- ko allowBindings: false -->
<div id="navbar" class="navbar navbar-static-top">
+3 -3
View File
@@ -1,10 +1,10 @@
<form class="form-search" data-bind="submit: performSearch">
<form class="form-search" data-bind="submit: performSearch, visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_LIST)">
<div class="search-query-with-clear" data-bind="css: {'active-clear': searchQuery}">
<input type="search" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
<span class="search-clear" data-bind="click: clearSearchQuery"><i class="fa fa-remove"></i></span>
</div>
</form>
<div class="gcode_files">
<div class="gcode_files" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_LIST)">
<div class="entry back clickable" data-bind="visible: currentPath() != '', click: function() { $root.navigateUp(); }" style="display: none">
<div class="back-arrow"><i class="fa fa-arrow-left"></i> {{ _('Back') }}</div>
<div class="back-path"><small class="muted">{{ _('Currently in') }} <span data-bind="text: currentPath"></span></small></div>
@@ -50,7 +50,7 @@
</div>
</script>
</div>
<div class="text-right muted" data-bind="attr: {title: diskusageString}, css: {'text-error': diskusageCritical}, style: {'font-weight': diskusageCritical() || diskusageWarning() ? 'bold' : 'normal'}">
<div class="text-right muted" data-bind="attr: {title: diskusageString}, css: {'text-error': diskusageCritical}, style: {'font-weight': diskusageCritical() || diskusageWarning() ? 'bold' : 'normal'}, visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_LIST)">
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span> / {{ _('Total') }}: <span data-bind="text: totalSpaceString"></span> <i class="fa fa-exclamation-triangle" data-bind="visible: diskusageWarning" style="display: none"></i></small>
</div>
<div style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.FILES_UPLOAD)">
+14 -6
View File
@@ -859,10 +859,12 @@ class TimelapseRenderJob(object):
input = os.path.join(self._capture_dir,
self._capture_format.format(prefix=self._prefix,
postfix=self._postfix if self._postfix is not None else ""))
output = os.path.join(self._output_dir,
self._output_format.format(prefix=self._prefix,
postfix=self._postfix if self._postfix is not None else "",
extension=extension))
output_name = self._output_format.format(prefix=self._prefix,
postfix=self._postfix if self._postfix is not None else "",
extension=extension)
temporary = os.path.join(self._output_dir, ".{}".format(output_name))
output = os.path.join(self._output_dir, output_name)
for i in range(4):
if os.path.exists(input % i):
@@ -885,7 +887,7 @@ class TimelapseRenderJob(object):
watermark = watermark.replace("\\", "/").replace(":", "\\\\:")
# prepare ffmpeg command
command_str = self._create_ffmpeg_command_string(ffmpeg, self._fps, bitrate, self._threads, input, output,
command_str = self._create_ffmpeg_command_string(ffmpeg, self._fps, bitrate, self._threads, input, temporary,
self._videocodec, hflip=hflip, vflip=vflip, rotate=rotate,
watermark=watermark)
self._logger.debug("Executing command: {}".format(command_str))
@@ -898,11 +900,12 @@ class TimelapseRenderJob(object):
c = CommandlineCaller()
c.on_log_stderr = self._process_ffmpeg_output
returncode, stdout_text, stderr_text = c.call(command_str, universal_newlines=True)
returncode, stdout_text, stderr_text = c.call(command_str, delimiter=b'\r', buffer_size=512)
self._logger.debug("Done with parsing")
if returncode == 0:
shutil.move(temporary, output)
self._notify_callback("success", output)
else:
self._logger.warning("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
@@ -911,6 +914,11 @@ class TimelapseRenderJob(object):
self._logger.exception("Could not render movie due to unknown error")
self._notify_callback("fail", output, reason="unknown")
finally:
try:
if os.path.exists(temporary):
os.remove(temporary)
except Exception:
self._logger.warn("Could not delete temporary timelapse {}".format(temporary))
self._notify_callback("always", output)
def _process_ffmpeg_output(self, *lines):
File diff suppressed because it is too large. Load diff
+29 -30
View File
@@ -449,8 +449,6 @@ class MachineCom(object):
self._hello_sent = 0
self._trigger_ok_for_m29 = settings().getBoolean(["serial", "triggerOkForM29"])
self._hello_command = settings().get(["serial", "helloCommand"])
self._alwaysSendChecksum = settings().getBoolean(["serial", "alwaysSendChecksum"])
self._neverSendChecksum = settings().getBoolean(["serial", "neverSendChecksum"])
self._sendChecksumWithUnknownCommands = settings().getBoolean(["serial", "sendChecksumWithUnknownCommands"])
@@ -483,7 +481,7 @@ class MachineCom(object):
self._errorValue = ""
self._firmware_detection = settings().getBoolean(["serial", "firmwareDetection"])
self._firmware_info_received = not self._firmware_detection
self._firmware_info_received = False
self._firmware_info = dict()
self._firmware_capabilities = dict()
@@ -1919,43 +1917,44 @@ class MachineCom(object):
firmware_name = firmware_name.strip()
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
if "repetier" in firmware_name.lower() or "anet_a8" in firmware_name.lower():
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
if self._firmware_detection:
if "repetier" in firmware_name.lower() or "anet_a8" in firmware_name.lower():
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
self._alwaysSendChecksum = True
self._blockWhileDwelling = True
supportRepetierTargetTemp = True
disable_external_heatup_detection = True
self._alwaysSendChecksum = True
self._blockWhileDwelling = True
supportRepetierTargetTemp = True
disable_external_heatup_detection = True
sd_always_available = self._sdAlwaysAvailable
self._sdAlwaysAvailable = True
if not sd_always_available and not self._sdAvailable:
self.initSdCard()
sd_always_available = self._sdAlwaysAvailable
self._sdAlwaysAvailable = True
if not sd_always_available and not self._sdAvailable:
self.initSdCard()
elif "reprapfirmware" in firmware_name.lower():
self._logger.info("Detected RepRapFirmware, enabling relevant features for issue free communication")
self._sdRelativePath = True
elif "reprapfirmware" in firmware_name.lower():
self._logger.info("Detected RepRapFirmware, enabling relevant features for issue free communication")
self._sdRelativePath = True
elif "malyan" in firmware_name.lower():
self._logger.info("Detected Malyan firmware, enabling relevant features for issue free communication")
elif "malyan" in firmware_name.lower():
self._logger.info("Detected Malyan firmware, enabling relevant features for issue free communication")
self._alwaysSendChecksum = True
self._blockWhileDwelling = True
self._alwaysSendChecksum = True
self._blockWhileDwelling = True
sd_always_available = self._sdAlwaysAvailable
self._sdAlwaysAvailable = True
if not sd_always_available and not self._sdAvailable:
self.initSdCard()
sd_always_available = self._sdAlwaysAvailable
self._sdAlwaysAvailable = True
if not sd_always_available and not self._sdAvailable:
self.initSdCard()
elif "teacup" in firmware_name.lower():
self._logger.info("Detected Teacup firmware, enabling relevant features for issue free communication")
elif "teacup" in firmware_name.lower():
self._logger.info("Detected Teacup firmware, enabling relevant features for issue free communication")
disable_external_heatup_detection = True # see #2854
disable_external_heatup_detection = True # see #2854
elif "klipper" in firmware_name.lower():
self._logger.info("Detected Klipper firmware, enabling relevant features for issue free communication")
elif "klipper" in firmware_name.lower():
self._logger.info("Detected Klipper firmware, enabling relevant features for issue free communication")
self._unknownCommandsNeedAck = True
self._unknownCommandsNeedAck = True
self._firmware_info_received = True
self._firmware_info = data
+55 -3
View File
@@ -11,11 +11,16 @@ import logging
import re
import time
from . import to_unicode, to_bytes
from . import to_unicode, to_native_str
from .platform import get_os
from past.builtins import unicode
try:
import queue
except ImportError: # pragma: no cover
import Queue as queue
# These regexes are based on the colorama package
# Author: Jonathan Hartley
# License: BSD-3 (https://github.com/tartley/colorama/blob/master/LICENSE.txt)
@@ -167,9 +172,23 @@ class CommandlineCaller(object):
# if we are running under windows, make sure there are no unicode strings in the env
if get_os() == "windows" and "env" in kwargs:
kwargs["env"] = dict((k, to_bytes(v)) for k, v in kwargs["env"].items())
kwargs["env"] = dict((k, to_native_str(v)) for k, v in kwargs["env"].items())
kwargs.update(dict(async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
delimiter = kwargs.get("delimiter", b'\n')
try:
kwargs.pop("delimiter")
except KeyError:
pass
buffer_size = kwargs.get("buffer_size", -1)
try:
kwargs.pop("buffer_size")
except KeyError:
pass
kwargs.update(dict(async_=True,
stdout=DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
stderr=DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size)))
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
@@ -226,3 +245,36 @@ class CommandlineCaller(object):
def _preprocess_lines(self, *lines):
return lines
class DelimiterCapture(sarge.Capture):
def __init__(self, delimiter=b'\n', *args, **kwargs):
self._delimiter = delimiter
sarge.Capture.__init__(self, *args, **kwargs)
def readline(self, size=-1, block=True, timeout=None):
if not self.streams_open():
block = False
timeout = None
else:
timeout = timeout or self.timeout
if self.current is None:
try:
self.current = self.buffer.get(block, timeout)
except queue.Empty:
self.current = b''
while self._delimiter not in self.current:
try:
self.current += self.buffer.get(block, timeout)
except queue.Empty:
break
if self._delimiter not in self.current:
result = self.current
self.current = None
else:
i = self.current.index(self._delimiter)
if 0 < size < i:
i = size - 1
result = self.current[:i + 1]
self.current = self.current[i + 1:]
return result
+4
View File
@@ -45,6 +45,10 @@ else:
HAS_V6 = False
def is_lan_address(address, additional_private=None):
if not address:
# no address is LAN address
return True
try:
address = unmap_v4_as_v6(address)
address = strip_interface_tag(address)
+2 -1
View File
@@ -44,7 +44,8 @@ class UtilNetTest(unittest.TestCase):
("11.1.2.3", ["11/8"], True),
("12.1.1.123", [], True),
("2a01:4f8:1c0c:6958::1:23", [], True),
("fe80::89f3:31bb:ced0:2093%wlan0", [], True)
("fe80::89f3:31bb:ced0:2093%wlan0", [], True),
(None, [], True)
)
@ddt.unpack
@mock.patch("netifaces.interfaces", side_effect=patched_interfaces)
Binary file not shown.
File diff suppressed because it is too large. Load diff
+232 -193
View File
File diff suppressed because it is too large. Load diff