Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d99af420ac | ||
|
|
73c2baa39e | ||
|
|
054df68741 | ||
|
|
f7756698e9 | ||
|
|
453ef0cb97 | ||
|
|
5015422086 | ||
|
|
2d85d8acf8 | ||
|
|
2af589a823 | ||
|
|
20c55f4d3d | ||
|
|
b7fdc82d30 | ||
|
|
770ebf2cf9 | ||
|
|
a75c641c18 | ||
|
|
38c09153ac | ||
|
|
e30e18e431 | ||
|
|
249d19f55b | ||
|
|
2e043ecf5b | ||
|
|
831edf234d | ||
|
|
b42c753d3f | ||
|
|
924cd5cb4c | ||
|
|
73f7c4d8a1 | ||
|
|
10079b8d9d | ||
|
|
c31566a626 | ||
|
|
0cfc7a2976 | ||
|
|
de5a10163e | ||
|
|
0a22c4e66c | ||
|
|
a88d95af77 | ||
|
|
010221ab5b | ||
|
|
6471a04a86 | ||
|
|
7b2762c590 | ||
|
|
de0b97b99c | ||
|
|
60d2bd1ac1 | ||
|
|
4d716647e5 | ||
|
|
43ab47a260 | ||
|
|
88ecfbdb65 | ||
|
|
8087967683 | ||
|
|
cb43197105 | ||
|
|
b1b9329614 | ||
|
|
7317814ce0 | ||
|
|
66ef7b66bb | ||
|
|
be3ff5f043 | ||
|
|
c36fa6da90 | ||
|
|
aadcf650c7 | ||
|
|
95c3fa0b04 | ||
|
|
1d0829a1db | ||
|
|
8d31d6687e | ||
|
|
3f3cb556a7 | ||
|
|
4460c8bee0 | ||
|
|
89b597a656 | ||
|
|
e1a25a8913 | ||
|
|
482c2f7115 | ||
|
|
7fa4ebd1ec | ||
|
|
9c3b552aa8 | ||
|
|
3229e65a8d | ||
|
|
7191d39b51 | ||
|
|
58bc5171ee | ||
|
|
74f3bc9ae6 | ||
|
|
464d9c0757 | ||
|
|
94ae90ab80 | ||
|
|
33b89550a4 | ||
|
|
9661469532 | ||
|
|
b06c222a7d | ||
|
|
9f85b54681 | ||
|
|
5d1ad5d75d | ||
|
|
dc32f955b7 | ||
|
|
220592c267 | ||
|
|
0faa6879b4 | ||
|
|
71b5de91bf | ||
|
|
928d62a517 | ||
|
|
78bd3b1a52 | ||
|
|
b9bab0577b | ||
|
|
c41551a643 | ||
|
|
6c92dd1303 | ||
|
|
124f01ca2d | ||
|
|
0dece85fa7 | ||
|
|
caebf90ee9 | ||
|
|
0c77014903 | ||
|
|
231a796200 | ||
|
|
fe755405e8 | ||
|
|
2200f2186c | ||
|
|
b57b7cb606 | ||
|
|
f2b2496e58 | ||
|
|
e603b98d0d | ||
|
|
e235fc299f | ||
|
|
4f25ed546e | ||
|
|
f72b9db6a9 | ||
|
|
80e8e33283 | ||
|
|
00d0396417 | ||
|
|
59e39662f1 | ||
|
|
038e1b9a57 | ||
|
|
bbefeeeb02 | ||
|
|
2801da5c51 | ||
|
|
471dab9406 | ||
|
|
1deb247ce5 | ||
|
|
4469a2d84a |
No files matched your search
+12
-9
@@ -18,16 +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
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc 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
|
||||
+14
-11
@@ -6,57 +6,60 @@ thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* ANTONIO AUGUSTO DE LIMA PONTES
|
||||
* Arnljot Arntsen
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Dorian Gray
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* 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
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Martin Majewski
|
||||
* 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
|
||||
* Samer Najia
|
||||
* Shawn Lewis
|
||||
* Ronald Griehsler
|
||||
* Sacha Telgenhof
|
||||
* sghnsk
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
* Vladislav Kuzemchik
|
||||
|
||||
and 1653 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)!
|
||||
@@ -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
|
||||
@@ -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**
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -20,7 +20,7 @@ REST API
|
||||
slicing.rst
|
||||
system.rst
|
||||
timelapse.rst
|
||||
users.rst
|
||||
access.rst
|
||||
util.rst
|
||||
wizard.rst
|
||||
push.rst
|
||||
|
||||
+3
-1
@@ -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
|
||||
|
||||
@@ -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
@@ -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,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
@@ -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>`.
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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::
|
||||
|
||||
|
||||
@@ -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``.
|
||||
@@ -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
|
||||
@@ -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
@@ -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.
|
||||
|
||||
@@ -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 |
@@ -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()
|
||||
|
||||
|
||||
|
||||
+112
-42
@@ -200,6 +200,94 @@ Available plugin hooks
|
||||
.. contents::
|
||||
:local:
|
||||
|
||||
.. _sec-plugins-hook-permissions:
|
||||
|
||||
octoprint.access.permissions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: additional_permissions_hook(*args, **kwargs)
|
||||
|
||||
Return a list of additional permissions to register in the system on behalf of the plugin. Use this
|
||||
to add granular permissions to your plugin which can be configured for users and user groups in the general
|
||||
access control settings of OctoPrint.
|
||||
|
||||
Additional permissions must be modelled as ``dict``s with at least a ``key`` and ``name`` field. Possible
|
||||
fields are as follows:
|
||||
|
||||
* ``key``: A key for the permission to be used for referring to it from source code. This will turned uppercase
|
||||
and prefixed with ``PLUGIN_<PLUGIN IDENTIFIER>_`` before being made available on ``octoprint.access.permissions.Permissions``,
|
||||
e.g. ``my_permission`` on the plugin with identifier ``example`` turns into ``PLUGIN_EXAMPLE_MY_PERMISSION`` and
|
||||
can be accessed as ``octoprint.access.permissions.Permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the server and
|
||||
``permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the ``AccessViewModel`` on the client. Must only contain a-z, A-Z, 0-9 and _.
|
||||
* ``name``: A human readable name for the permission.
|
||||
* ``description``: A human readable description of the permission.
|
||||
* ``permissions``: A list of permissions this permission includes, by key.
|
||||
* ``roles``: A list of roles this permission includes. Roles are simple strings you define. Usually one role will
|
||||
suffice.
|
||||
* ``dangerous``: Whether this permission should be considered dangerous (``True``) or not (``False``)
|
||||
* ``default_groups``: A list of standard groups this permission should be apply to by default. Standard groups
|
||||
are ``admins``, ``users``, ``readonly`` and ``guests``
|
||||
|
||||
The following example is based on some actual code included in the bundled Application Keys plugin and defines
|
||||
one additional permission called ``ADMIN`` with a role ``admin`` which is marked as dangerous (since it gives
|
||||
access to the management to other user's application keys) and by default will only be given to the standard admin
|
||||
group:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_additional_permissions(*args, **kwargs):
|
||||
return [
|
||||
dict(key="ADMIN",
|
||||
name="Admin access",
|
||||
description=gettext("Allows administrating all application keys"),
|
||||
roles=["admin"],
|
||||
dangerous=True,
|
||||
default_groups=[ADMIN_GROUP])
|
||||
]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.access.permissions": get_additional_permissions
|
||||
}
|
||||
|
||||
Once registered it can be referenced under the key ``PLUGIN_APPKEYS_ADMIN``.
|
||||
|
||||
:return: A list of additional permissions to register in the system.
|
||||
:rtype: A list of dicts.
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.access.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
|
||||
.. _sec-plugins-hook-accesscontrol-keyvalidator:
|
||||
|
||||
octoprint.accesscontrol.keyvalidator
|
||||
@@ -1014,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
|
||||
@@ -1185,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::
|
||||
|
||||
@@ -1201,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::
|
||||
|
||||
@@ -1217,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::
|
||||
|
||||
@@ -1342,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
|
||||
|
||||
@@ -1525,40 +1629,6 @@ octoprint.ui.web.templatetypes
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.access.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||
|
||||
octoprint.timelapse.capture.pre
|
||||
|
||||
@@ -37,9 +37,9 @@ INSTALL_REQUIRES = [
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
"Flask-Login>=0.4.1,<0.5",
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"blinker>=1.4,<1.5", # dependency of the now vendor bundled flask_principal
|
||||
"werkzeug>=0.16,<0.17",
|
||||
"cachelib>=0.1,<0.2",
|
||||
"PyYAML>=5.1,<6",
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
#import sys
|
||||
#if sys.version_info[0] >= 3:
|
||||
# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -18,32 +18,7 @@ from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from flask_principal import Need, Permission
|
||||
|
||||
DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN]
|
||||
"""Default admin permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.CONNECTION,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_UPLOAD,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.FILES_DELETE,
|
||||
Permissions.FILES_SELECT,
|
||||
Permissions.PRINT,
|
||||
Permissions.MONITOR_TERMINAL,
|
||||
Permissions.CONTROL,
|
||||
Permissions.SLICE,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.TIMELAPSE_ADMIN]
|
||||
"""Default user permissions are the legacy permissions from before 1.4.0"""
|
||||
|
||||
DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
|
||||
Permissions.WEBCAM,
|
||||
Permissions.FILES_DOWNLOAD,
|
||||
Permissions.TIMELAPSE_LIST,
|
||||
Permissions.MONITOR_TERMINAL]
|
||||
"""Default guest permissions are the legacy permissions from before 1.4.0"""
|
||||
from octoprint.vendor.flask_principal import Need, Permission
|
||||
|
||||
|
||||
GroupNeed = partial(Need, '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
|
||||
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
from future.utils import with_metaclass
|
||||
from flask import g, abort
|
||||
from flask_babel import gettext
|
||||
from flask_principal import Permission, PermissionDenied, RoleNeed, Need
|
||||
from octoprint.vendor.flask_principal import Permission, PermissionDenied, RoleNeed, Need
|
||||
|
||||
from functools import wraps
|
||||
from collections import OrderedDict, defaultdict
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ from builtins import range, bytes
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time, generate_api_key
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
@@ -55,7 +55,10 @@ class UserManager(GroupChangeListener, object):
|
||||
if self.enabled:
|
||||
return AnonymousUser([self._group_manager.guest_group])
|
||||
else:
|
||||
return AdminUser([self._group_manager.admin_group])
|
||||
return AdminUser([self._group_manager.admin_group, self._group_manager.user_group])
|
||||
|
||||
def api_user_factory(self):
|
||||
return ApiUser([self._group_manager.admin_group, self._group_manager.user_group])
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
@@ -102,12 +105,12 @@ 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):
|
||||
if user is None or user.is_anonymous:
|
||||
def logout_user(self, user, stale=False):
|
||||
if user is None or user.is_anonymous or isinstance(user, AdminUser):
|
||||
return
|
||||
|
||||
if isinstance(user, LocalProxy):
|
||||
@@ -126,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):
|
||||
@@ -433,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):
|
||||
@@ -743,7 +750,7 @@ class FilebasedUserManager(UserManager):
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
user._apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
user._apikey = generate_api_key()
|
||||
self._dirty = True
|
||||
self._save()
|
||||
return user._apikey
|
||||
@@ -1122,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()
|
||||
@@ -1140,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):
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -7,7 +7,7 @@ import os
|
||||
import yaml
|
||||
import io
|
||||
import time
|
||||
from binascii import hexlify
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from flask_babel import gettext
|
||||
|
||||
@@ -15,12 +15,11 @@ import octoprint.plugin
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, no_firstrun_access
|
||||
from octoprint.server import NO_CONTENT, current_user, admin_permission
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
|
||||
from octoprint.util import atomic_write, monotonic_time, ResettableTimer, generate_api_key
|
||||
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
|
||||
@@ -381,7 +380,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
for user_id, data in self._keys.items():
|
||||
if any(filter(lambda x: x.api_key == api_key, data)):
|
||||
if self._user_manager.enabled:
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
return self._user_manager.find_user(userid=user_id)
|
||||
elif user_id == "_admin" or user_id == "dummy":
|
||||
# dummy = backwards compatible
|
||||
return self._user_manager.anonymous_user_factory()
|
||||
@@ -399,7 +398,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
return result
|
||||
|
||||
def _generate_key(self):
|
||||
return hexlify(os.urandom(16))
|
||||
return generate_api_key()
|
||||
|
||||
def _load_keys(self):
|
||||
with self._keys_lock:
|
||||
|
||||
@@ -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://90eab6758d324033b1523a47633d17f3@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://ae03048024f841fc9724c3f5c19557a4@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))
|
||||
|
||||
@@ -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>
|
||||
@@ -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"> </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):
|
||||
|
||||
@@ -36,7 +36,7 @@ class PrintTimeEstimator(object):
|
||||
interval = settings().getFloat(["serial", "timeout", "sdStatus"])
|
||||
if interval <= 0:
|
||||
interval = 1.0
|
||||
rolling_window = 15 / interval
|
||||
rolling_window = int(15 // interval)
|
||||
if rolling_window < 1:
|
||||
rolling_window = 1
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import uuid
|
||||
from octoprint.vendor.sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
|
||||
from flask_login import LoginManager, current_user, session_protected, user_logged_out
|
||||
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, Identity, AnonymousIdentity
|
||||
from octoprint.vendor.flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, Identity, AnonymousIdentity
|
||||
from flask_babel import Babel, gettext, ngettext
|
||||
from flask_assets import Environment, Bundle
|
||||
from babel import Locale
|
||||
@@ -31,9 +31,11 @@ import os
|
||||
import sys
|
||||
import logging
|
||||
import logging.config
|
||||
import mimetypes
|
||||
import atexit
|
||||
import signal
|
||||
import base64
|
||||
import re
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
@@ -98,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__
|
||||
@@ -123,8 +125,7 @@ def on_identity_loaded(sender, identity):
|
||||
def _clear_identity(sender):
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
|
||||
if key in session:
|
||||
del session[key]
|
||||
session.pop(key, None)
|
||||
|
||||
# switch to anonymous identity
|
||||
identity_changed.send(sender, identity=AnonymousIdentity())
|
||||
@@ -132,8 +133,9 @@ def _clear_identity(sender):
|
||||
|
||||
@session_protected.connect_via(app)
|
||||
def on_session_protected(sender):
|
||||
# session was protected, that means the user is no more and we need to clear our identity
|
||||
_clear_identity(sender)
|
||||
# session was deleted by session protection, that means the user is no more and we need to clear our identity
|
||||
if session.get("remember", None) == "clear":
|
||||
_clear_identity(sender)
|
||||
|
||||
|
||||
@user_logged_out.connect_via(app)
|
||||
@@ -147,7 +149,7 @@ def load_user(id):
|
||||
return None
|
||||
|
||||
if id == "_api":
|
||||
return users.ApiUser([groupManager.admin_group])
|
||||
return userManager.api_user_factory()
|
||||
|
||||
if session and "usersession.id" in session:
|
||||
sessionid = session["usersession.id"]
|
||||
@@ -278,10 +280,12 @@ class Server(object):
|
||||
self._setup_heartbeat_logging()
|
||||
pluginManager = self._plugin_manager
|
||||
|
||||
# monkey patch some stuff
|
||||
# monkey patch/fix some stuff
|
||||
util.tornado.fix_json_encode()
|
||||
util.flask.fix_flask_jsonify()
|
||||
|
||||
self._setup_mimetypes()
|
||||
|
||||
additional_translation_folders = []
|
||||
if not safe_mode:
|
||||
additional_translation_folders += [self._settings.getBaseFolder("translations")]
|
||||
@@ -474,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) \
|
||||
@@ -1322,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)
|
||||
|
||||
@@ -1346,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)
|
||||
@@ -1355,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)
|
||||
@@ -1366,7 +1378,18 @@ 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
|
||||
# registry, and if for some weird reason that gets borked the reported MIME types can be all over the place.
|
||||
# Since at least in Chrome that can cause hilarious issues with JS files (refusal to run them and thus a
|
||||
# borked UI) we make sure that .js always maps to the correct application/javascript, and also throw in a
|
||||
# .css -> text/css for good measure.
|
||||
#
|
||||
# See #3367
|
||||
mimetypes.add_type("application/javascript", ".js")
|
||||
mimetypes.add_type("text/css", ".css")
|
||||
|
||||
def _setup_assets(self):
|
||||
global app
|
||||
@@ -1700,8 +1723,6 @@ class Server(object):
|
||||
assets.register("less_app", less_app_bundle)
|
||||
|
||||
def _setup_login_manager(self):
|
||||
util.flask.fix_flask_login_remote_address()
|
||||
|
||||
global loginManager
|
||||
|
||||
loginManager = LoginManager()
|
||||
@@ -1870,6 +1891,8 @@ class Server(object):
|
||||
|
||||
from octoprint.access.permissions import PluginOctoPrintPermission
|
||||
|
||||
key_whitelist = re.compile(r"[A-Za-z0-9_]*")
|
||||
|
||||
def permission_key(plugin, definition):
|
||||
return "PLUGIN_{}_{}".format(plugin.upper(), definition["key"].upper())
|
||||
|
||||
@@ -1942,6 +1965,10 @@ class Server(object):
|
||||
if not "key" in p or not "name" in p:
|
||||
continue
|
||||
|
||||
if not key_whitelist.match(p["key"]):
|
||||
self._logger.warn("Got permission with invalid key from plugin {}: {}".format(name, p["key"]))
|
||||
continue
|
||||
|
||||
if not process_regular_permission(plugin_info, p):
|
||||
postponed.append((plugin_info, p))
|
||||
except Exception:
|
||||
|
||||
@@ -10,7 +10,8 @@ import logging
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g
|
||||
from flask_login import login_user, logout_user, current_user
|
||||
from flask_principal import Identity, identity_changed, AnonymousIdentity
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from octoprint.vendor.flask_principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.access.users
|
||||
import octoprint.util.net as util_net
|
||||
@@ -72,6 +73,8 @@ def pluginData(name):
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error calling SimpleApiPlugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
@@ -107,6 +110,8 @@ def pluginCommand(name):
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while executing SimpleApiPlugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
@@ -205,7 +210,7 @@ def apiVersion():
|
||||
@api.route("/login", methods=["POST"])
|
||||
def login():
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
if not data:
|
||||
data = request.values
|
||||
|
||||
if octoprint.server.userManager.enabled and "user" in data and "pass" in data:
|
||||
@@ -284,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
|
||||
|
||||
|
||||
@@ -375,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))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -12,14 +12,13 @@ PY3 = sys.version_info[0] == 3
|
||||
from octoprint.settings import settings
|
||||
import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.access.users import ApiUser
|
||||
|
||||
from octoprint.util import deprecated
|
||||
from octoprint.util import deprecated, to_unicode
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
import flask as _flask
|
||||
import flask_login
|
||||
import flask_principal
|
||||
import octoprint.vendor.flask_principal as flask_principal
|
||||
import logging
|
||||
|
||||
from . import flask
|
||||
@@ -103,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
|
||||
@@ -180,7 +191,7 @@ def get_user_for_apikey(apikey):
|
||||
if apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
return ApiUser([octoprint.server.groupManager.admin_group])
|
||||
return octoprint.server.userManager.api_user_factory()
|
||||
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.find_user(apikey=apikey)
|
||||
@@ -234,7 +245,7 @@ def get_user_for_authorization_header(header):
|
||||
|
||||
header = header.replace('Basic ', '', 1)
|
||||
try:
|
||||
header = base64.b64decode(header)
|
||||
header = to_unicode(base64.b64decode(header))
|
||||
except TypeError:
|
||||
return None
|
||||
|
||||
@@ -242,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
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import tornado.web
|
||||
import flask
|
||||
import flask.json
|
||||
import flask_login
|
||||
import flask_principal
|
||||
import octoprint.vendor.flask_principal as flask_principal
|
||||
import flask_assets
|
||||
import webassets.updater
|
||||
import webassets.utils
|
||||
@@ -242,20 +242,6 @@ def fix_webassets_filtertool():
|
||||
|
||||
FilterTool._wrap_cache = fixed_wrap_cache
|
||||
|
||||
def fix_flask_login_remote_address():
|
||||
def fixed_get_remote_addr():
|
||||
"""Backported from https://github.com/maxcountryman/flask-login/pull/217"""
|
||||
|
||||
from flask import request
|
||||
address = request.headers.get('X-Forwarded-For', request.remote_addr)
|
||||
if address is not None:
|
||||
# An 'X-Forwarded-For' header includes a comma separated list of the
|
||||
# addresses, the first address being the actual remote address.
|
||||
address = address.encode('utf-8').split(b',')[0].strip()
|
||||
return address
|
||||
|
||||
flask_login._get_remote_addr = fixed_get_remote_addr
|
||||
|
||||
def fix_flask_jsonify():
|
||||
def fixed_jsonify(*args, **kwargs):
|
||||
"""Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257"""
|
||||
@@ -590,31 +576,37 @@ def passive_login():
|
||||
|
||||
return u
|
||||
|
||||
if user is not None and user.is_active:
|
||||
# login known user
|
||||
logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address))
|
||||
user = login(user)
|
||||
def determine_user(u):
|
||||
if not u.is_anonymous and u.is_active:
|
||||
# known active user
|
||||
logger.info("Passively logging in user {} from {}".format(u.get_id(), remote_address))
|
||||
|
||||
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:
|
||||
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 remote_address:
|
||||
# attempt local autologin
|
||||
autologin_as = settings().get(["accessControl", "autologinAs"])
|
||||
local_networks = _local_networks()
|
||||
logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks))
|
||||
|
||||
autologin_as = settings().get(["accessControl", "autologinAs"])
|
||||
local_networks = _local_networks()
|
||||
logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks))
|
||||
try:
|
||||
if netaddr.IPAddress(remote_address) in local_networks:
|
||||
autologin_user = octoprint.server.userManager.find_user(autologin_as)
|
||||
if autologin_user is not None and autologin_user.is_active:
|
||||
logger.info("Passively logging in user {} from {} via autologin".format(autologin_as, remote_address))
|
||||
return autologin_user
|
||||
except Exception:
|
||||
logger.exception("Could not autologin user {} from {} for networks {}".format(autologin_as, remote_address, local_networks))
|
||||
|
||||
try:
|
||||
if netaddr.IPAddress(remote_address) in local_networks:
|
||||
autologin_user = octoprint.server.userManager.findUser(autologin_as)
|
||||
if autologin_user is not None and autologin_user.is_active:
|
||||
autologin_user = octoprint.server.userManager.login_user(autologin_user)
|
||||
if not u.is_active:
|
||||
# inactive user, switch to anonymous
|
||||
u = octoprint.server.userManager.anonymous_user_factory()
|
||||
|
||||
logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(), local_networks))
|
||||
user = login(autologin_user)
|
||||
except Exception:
|
||||
logger.exception("Could not autologin user {} for networks {}".format(autologin_as, local_networks))
|
||||
return u
|
||||
|
||||
user = login(determine_user(user))
|
||||
response = user.as_dict()
|
||||
response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address,
|
||||
additional_private=ip_check_trusted)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -460,6 +460,8 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in parameters.items())
|
||||
for n, p in fields.items():
|
||||
if n is None or p is None:
|
||||
continue
|
||||
key = name + b"." + octoprint.util.to_bytes(n)
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||
|
||||
@@ -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)
|
||||
@@ -591,9 +599,9 @@ def fetch_template_data(refresh=False):
|
||||
# tabs
|
||||
|
||||
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()")),
|
||||
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)"))
|
||||
)
|
||||
|
||||
@@ -49,7 +49,7 @@ try:
|
||||
except ImportError:
|
||||
from collections import KeysView
|
||||
|
||||
from octoprint.util import atomic_write, is_hidden_path, dict_merge, CaseInsensitiveSet
|
||||
from octoprint.util import atomic_write, is_hidden_path, dict_merge, CaseInsensitiveSet, generate_api_key
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
|
||||
@@ -1811,7 +1811,7 @@ class Settings(object):
|
||||
f.write(script)
|
||||
|
||||
def generateApiKey(self):
|
||||
apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
apikey = generate_api_key()
|
||||
self.set(["api", "key"], apikey)
|
||||
self.save(force=True)
|
||||
return apikey
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,7 @@
|
||||
return entry;
|
||||
}
|
||||
|
||||
if (!entry.hasOwnProperty("children")) {
|
||||
if (!entry.hasOwnProperty("children") || !entry.children) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
@@ -263,7 +269,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
self._printerErrorCancelNotification = new PNotify({
|
||||
title: gettext("Error reported by printer"),
|
||||
text: _.sprintf(gettext("Your printer's firmware reported an error. Due to that the ongoing print job will be cancelled. Reported error: %(firmwareError)s"), _.escape(payload)),
|
||||
text: _.sprintf(gettext("Your printer's firmware reported an error. Due to that the ongoing print job will be cancelled. Reported error: %(firmwareError)s"), {firmwareError: _.escape(payload.firmwareError)}),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
@@ -274,24 +280,24 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
switch (payload.reason) {
|
||||
case "firmware": {
|
||||
title = gettext("Error reported by printer");
|
||||
text = _.sprintf(gettext("Your printer's firmware reported an error. Due to that OctoPrint will disconnect. Reported error: %(error)s"), _.escape(payload));
|
||||
text = _.sprintf(gettext("Your printer's firmware reported an error. Due to that OctoPrint will disconnect. Reported error: %(error)s"), {error: _.escape(payload.error)});
|
||||
break;
|
||||
}
|
||||
case "resend":
|
||||
case "resend_loop":
|
||||
case "timeout": {
|
||||
title = gettext("Communication error");
|
||||
text = _.sprintf(gettext("There was a communication error while talking to your printer. Please consult the terminal output and octoprint.log for details. Error: %(error)s"), _.escape(payload));
|
||||
text = _.sprintf(gettext("There was a communication error while talking to your printer. Please consult the terminal output and octoprint.log for details. Error: %(error)s"), {error: _.escape(payload.error)});
|
||||
break;
|
||||
}
|
||||
case "connection": {
|
||||
title = gettext("Error connecting to printer");
|
||||
text = _.sprintf(gettext("There was an error while trying to connect to your printer. Error: %(error)s"), _.escape(payload));
|
||||
text = _.sprintf(gettext("There was an error while trying to connect to your printer. Error: %(error)s"), {error: _.escape(payload.error)});
|
||||
break;
|
||||
}
|
||||
case "start_print": {
|
||||
title = gettext("Error starting a print");
|
||||
text = _.sprintf(gettext("There was an error while trying to start a print job. Error: %(error)s"), _.escape(payload));
|
||||
text = _.sprintf(gettext("There was an error while trying to start a print job. Error: %(error)s"), {error: _.escape(payload.error)});
|
||||
break;
|
||||
}
|
||||
case "autodetect_port":
|
||||
@@ -301,7 +307,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
default: {
|
||||
title = gettext("Unknown error");
|
||||
text = _.sprintf(gettext("There was an unknown error while talking to your printer. Please consult the terminal output and octoprint.log for details. Error: %(error)s"), _.escape(payload));
|
||||
text = _.sprintf(gettext("There was an unknown error while talking to your printer. Please consult the terminal output and octoprint.log for details. Error: %(error)s"), {error: _.escape(payload.error)});
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -227,6 +227,7 @@ $(function() {
|
||||
PNotify.prototype.options.stack.firstpos2 = 20;
|
||||
PNotify.prototype.options.stack.spacing1 = 20;
|
||||
PNotify.prototype.options.stack.spacing2 = 20;
|
||||
PNotify.prototype.options.stack.context = $("#page-container-main");
|
||||
PNotify.prototype.options.delay = 5000;
|
||||
PNotify.prototype.options.animate_speed = "fast";
|
||||
|
||||
@@ -807,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() {
|
||||
|
||||
@@ -837,7 +837,7 @@ $(function() {
|
||||
return element;
|
||||
}
|
||||
|
||||
if (!element.hasOwnProperty("children")) {
|
||||
if (!element.hasOwnProperty("children") || !element.children) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ $(function() {
|
||||
self.userneeds({});
|
||||
}
|
||||
|
||||
if (data.name) {
|
||||
if (data && data.name) {
|
||||
self.username(data.name);
|
||||
self.currentUser(data);
|
||||
|
||||
|
||||
@@ -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"]
|
||||
});
|
||||
});
|
||||
@@ -1004,6 +1004,10 @@ ul.dropdown-menu li a {
|
||||
|
||||
/** Notifications */
|
||||
|
||||
.ui-pnotify{
|
||||
position:fixed;
|
||||
}
|
||||
|
||||
.ui-pnotify .alert a {
|
||||
color: #c09853;
|
||||
}
|
||||
@@ -1540,36 +1544,6 @@ input[type="number"].input-nospin {
|
||||
}
|
||||
}
|
||||
|
||||
// page wide login form
|
||||
#page-container-needlogin {
|
||||
background-color: #ffffff;
|
||||
z-index: 12300;
|
||||
.form-signin {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
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;
|
||||
|
||||
@@ -20,8 +20,7 @@
|
||||
<noscript>
|
||||
<style type="text/css">
|
||||
#page-container-main,
|
||||
#page-container-loading,
|
||||
#page-container-needlogin {
|
||||
#page-container-loading {
|
||||
display:none;
|
||||
}
|
||||
</style>
|
||||
@@ -39,7 +38,23 @@
|
||||
</div>
|
||||
</noscript>
|
||||
|
||||
<div class="page-container" id="page-container-main" {% if enableLoadAnimation -%}style="display: none"{%- endif %} data-bind="visible: visible">
|
||||
{% if enableLoadingAnimation %}
|
||||
<div id="page-container-loading" data-bind="visible: loading">
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<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">
|
||||
<div class="navbar-inner" data-bind="css: appearanceClasses">
|
||||
@@ -176,36 +191,5 @@
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
|
||||
{% if enableLoadingAnimation %}
|
||||
<div id="page-container-loading" data-bind="visible: loading">
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<h1 id="page-container-loading-header">{{ _('Loading OctoPrint\'s UI, please wait...') }}</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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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)">
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
</div>
|
||||
|
||||
{% if enableSdSupport %}
|
||||
<div class="sd-trigger accordion-heading-button btn-group" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.CONTROL) && $root.filesListVisible()">
|
||||
<div class="sd-trigger accordion-heading-button btn-group" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.CONTROL)() && $root.filesListVisible()">
|
||||
<a class="dropdown-toggle" data-toggle="dropdown" href="#" title="{{ _('SD Card operations')|edq }}">
|
||||
<span class="icon-sd-black-14"></span>
|
||||
</a>
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="visible: keycontrolPossible && loginState.hasPermissionKo(access.permissions.WEBCAM) && loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<div data-bind="visible: keycontrolPossible() && loginState.hasPermissionKo(access.permissions.WEBCAM)() && loginState.hasPermissionKo(access.permissions.CONTROL)()">
|
||||
<small class="muted">{{ _("Hint: If you move your mouse over the picture, you enter keyboard control mode.") }}</small>
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -85,7 +85,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<!-- Extrusion control panel -->
|
||||
<div id="control-jog-extrusion" class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL) && tools().length > 0">
|
||||
<div id="control-jog-extrusion" class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)() && tools().length > 0">
|
||||
<h1>Tool (E)</h1>
|
||||
<div>
|
||||
<div class="btn-group control-box">
|
||||
|
||||
+19
-11
@@ -465,7 +465,7 @@ class Timelapse(object):
|
||||
"""
|
||||
Override this to perform additional actions upon start of a print job.
|
||||
"""
|
||||
self.start_timelapse(payload["file"])
|
||||
self.start_timelapse(payload["name"])
|
||||
|
||||
def on_print_done(self, event, payload):
|
||||
"""
|
||||
@@ -478,7 +478,7 @@ class Timelapse(object):
|
||||
Override this to perform additional actions upon the pausing of a print job.
|
||||
"""
|
||||
if not self._in_timelapse:
|
||||
self.start_timelapse(payload["file"])
|
||||
self.start_timelapse(payload["name"])
|
||||
|
||||
def event_subscriptions(self):
|
||||
"""
|
||||
@@ -502,14 +502,14 @@ class Timelapse(object):
|
||||
"""
|
||||
return None
|
||||
|
||||
def start_timelapse(self, gcodeFile):
|
||||
self._logger.debug("Starting timelapse for %s" % gcodeFile)
|
||||
def start_timelapse(self, gcode_file):
|
||||
self._logger.debug("Starting timelapse for %s" % gcode_file)
|
||||
|
||||
self._image_number = 0
|
||||
self._capture_errors = 0
|
||||
self._capture_success = 0
|
||||
self._in_timelapse = True
|
||||
self._gcode_file = os.path.basename(gcodeFile)
|
||||
self._gcode_file = os.path.basename(gcode_file)
|
||||
self._file_prefix = "{}_{}".format(os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S"))
|
||||
|
||||
def stop_timelapse(self, do_create_movie=True, success=True):
|
||||
@@ -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):
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -33,6 +33,7 @@ try:
|
||||
except ImportError:
|
||||
import Queue as queue
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring, unicode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -131,8 +132,6 @@ def pp(value):
|
||||
def warning_decorator_factory(warning_type):
|
||||
def specific_warning(message, stacklevel=1, since=None, includedoc=None, extenddoc=False):
|
||||
def decorator(func):
|
||||
func.__qualname__ = to_native_str('warning_decorator_factory')
|
||||
func.__annotations__ = dict()
|
||||
@wraps(func)
|
||||
def func_wrapper(*args, **kwargs):
|
||||
# we need to increment the stacklevel by one because otherwise we'll get the location of our
|
||||
@@ -1836,3 +1835,11 @@ def timing(f):
|
||||
logging.getLogger("octoprint.util.timing").debug("func:{} took {:0.2f}s".format(f.__name__,
|
||||
end - start))
|
||||
return decorator
|
||||
|
||||
|
||||
def generate_api_key():
|
||||
# noinspection PyCompatibility
|
||||
from builtins import bytes
|
||||
import uuid
|
||||
|
||||
return ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
@@ -31,7 +31,7 @@ class IspBase():
|
||||
def chipErase(self):
|
||||
self.sendISP([0xAC, 0x80, 0x00, 0x00])
|
||||
|
||||
class IspError():
|
||||
class IspError(Exception):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
def __str__(self):
|
||||
|
||||
@@ -98,8 +98,8 @@ class Stk500v2(ispBase.IspBase):
|
||||
for c in data:
|
||||
message += struct.pack(">B", c)
|
||||
checksum = 0
|
||||
for c in message:
|
||||
checksum ^= ord(c)
|
||||
for c in bytearray(message):
|
||||
checksum ^= c
|
||||
message += struct.pack(">B", checksum)
|
||||
try:
|
||||
self.serial.write(message)
|
||||
|
||||
+29
-30
@@ -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
|
||||
|
||||
@@ -11,10 +11,16 @@ import logging
|
||||
import re
|
||||
import time
|
||||
|
||||
from . import to_unicode
|
||||
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)
|
||||
@@ -164,7 +170,25 @@ class CommandlineCaller(object):
|
||||
self._logger.debug("Calling: {}".format(joined_command))
|
||||
self.on_log_call(joined_command)
|
||||
|
||||
kwargs.update(dict(async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
|
||||
# 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_native_str(v)) for k, v in kwargs["env"].items())
|
||||
|
||||
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:
|
||||
@@ -221,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
|
||||
@@ -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)
|
||||
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask_principal
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Identity management for Flask.
|
||||
|
||||
:copyright: (c) 2012 by Ali Afshar.
|
||||
:license: MIT, see LICENSE for more details.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import with_statement
|
||||
|
||||
__version__ = '0.4.0'
|
||||
|
||||
import sys
|
||||
|
||||
from functools import partial, wraps
|
||||
from collections import deque
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from flask import g, session, current_app, abort, request
|
||||
from flask.signals import Namespace
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
signals = Namespace()
|
||||
|
||||
|
||||
identity_changed = signals.signal('identity-changed', doc="""
|
||||
Signal sent when the identity for a request has been changed.
|
||||
|
||||
Actual name: ``identity-changed``
|
||||
|
||||
Authentication providers should send this signal when authentication has been
|
||||
successfully performed. Flask-Principal connects to this signal and
|
||||
causes the identity to be saved in the session.
|
||||
|
||||
For example::
|
||||
|
||||
from flaskext.principal import Identity, identity_changed
|
||||
|
||||
def login_view(req):
|
||||
username = req.form.get('username')
|
||||
# check the credentials
|
||||
identity_changed.send(app, identity=Identity(username))
|
||||
""")
|
||||
|
||||
|
||||
identity_loaded = signals.signal('identity-loaded', doc="""
|
||||
Signal sent when the identity has been initialised for a request.
|
||||
|
||||
Actual name: ``identity-loaded``
|
||||
|
||||
Identity information providers should connect to this signal to perform two
|
||||
major activities:
|
||||
|
||||
1. Populate the identity object with the necessary authorization provisions.
|
||||
2. Load any additional user information.
|
||||
|
||||
For example::
|
||||
|
||||
from flaskext.principal import identity_loaded, RoleNeed, UserNeed
|
||||
|
||||
@identity_loaded.connect
|
||||
def on_identity_loaded(sender, identity):
|
||||
# Get the user information from the db
|
||||
user = db.get(identity.name)
|
||||
# Update the roles that a user can provide
|
||||
for role in user.roles:
|
||||
identity.provides.add(RoleNeed(role.name))
|
||||
# Save the user somewhere so we only look it up once
|
||||
identity.user = user
|
||||
""")
|
||||
|
||||
|
||||
Need = namedtuple('Need', ['method', 'value'])
|
||||
"""A required need
|
||||
|
||||
This is just a named tuple, and practically any tuple will do.
|
||||
|
||||
The ``method`` attribute can be used to look up element 0, and the ``value``
|
||||
attribute can be used to look up element 1.
|
||||
"""
|
||||
|
||||
|
||||
UserNeed = partial(Need, 'id')
|
||||
UserNeed.__doc__ = """A need with the method preset to `"id"`."""
|
||||
|
||||
|
||||
RoleNeed = partial(Need, 'role')
|
||||
RoleNeed.__doc__ = """A need with the method preset to `"role"`."""
|
||||
|
||||
|
||||
TypeNeed = partial(Need, 'type')
|
||||
TypeNeed.__doc__ = """A need with the method preset to `"type"`."""
|
||||
|
||||
|
||||
ActionNeed = partial(Need, 'action')
|
||||
TypeNeed.__doc__ = """A need with the method preset to `"action"`."""
|
||||
|
||||
|
||||
ItemNeed = namedtuple('ItemNeed', ['method', 'value', 'type'])
|
||||
"""A required item need
|
||||
|
||||
An item need is just a named tuple, and practically any tuple will do. In
|
||||
addition to other Needs, there is a type, for example this could be specified
|
||||
as::
|
||||
|
||||
ItemNeed('update', 27, 'posts')
|
||||
('update', 27, 'posts') # or like this
|
||||
|
||||
And that might describe the permission to update a particular blog post. In
|
||||
reality, the developer is free to choose whatever convention the permissions
|
||||
are.
|
||||
"""
|
||||
|
||||
|
||||
class PermissionDenied(RuntimeError):
|
||||
"""Permission denied to the resource"""
|
||||
|
||||
|
||||
class Identity(object):
|
||||
"""Represent the user's identity.
|
||||
|
||||
:param id: The user id
|
||||
:param auth_type: The authentication type used to confirm the user's
|
||||
identity.
|
||||
|
||||
The identity is used to represent the user's identity in the system. This
|
||||
object is created on login, or on the start of the request as loaded from
|
||||
the user's session.
|
||||
|
||||
Once loaded it is sent using the `identity-loaded` signal, and should be
|
||||
populated with additional required information.
|
||||
|
||||
Needs that are provided by this identity should be added to the `provides`
|
||||
set after loading.
|
||||
"""
|
||||
def __init__(self, id, auth_type=None):
|
||||
self.id = id
|
||||
self.auth_type = auth_type
|
||||
self.provides = set()
|
||||
|
||||
def can(self, permission):
|
||||
"""Whether the identity has access to the permission.
|
||||
|
||||
:param permission: The permission to test provision for.
|
||||
"""
|
||||
return permission.allows(self)
|
||||
|
||||
def __repr__(self):
|
||||
return '<{0} id="{1}" auth_type="{2}" provides={3}>'.format(
|
||||
self.__class__.__name__, self.id, self.auth_type, self.provides
|
||||
)
|
||||
|
||||
|
||||
class AnonymousIdentity(Identity):
|
||||
"""An anonymous identity"""
|
||||
|
||||
def __init__(self):
|
||||
Identity.__init__(self, None)
|
||||
|
||||
|
||||
class IdentityContext(object):
|
||||
"""The context of an identity for a permission.
|
||||
|
||||
.. note:: The principal is usually created by the flaskext.Permission.require method
|
||||
call for normal use-cases.
|
||||
|
||||
The principal behaves as either a context manager or a decorator. The
|
||||
permission is checked for provision in the identity, and if available the
|
||||
flow is continued (context manager) or the function is executed (decorator).
|
||||
"""
|
||||
|
||||
def __init__(self, permission, http_exception=None):
|
||||
self.permission = permission
|
||||
self.http_exception = http_exception
|
||||
"""The permission of this principal
|
||||
"""
|
||||
|
||||
@property
|
||||
def identity(self):
|
||||
"""The identity of this principal
|
||||
"""
|
||||
return g.identity
|
||||
|
||||
def can(self):
|
||||
"""Whether the identity has access to the permission
|
||||
"""
|
||||
return self.identity.can(self.permission)
|
||||
|
||||
def __call__(self, f):
|
||||
@wraps(f)
|
||||
def _decorated(*args, **kw):
|
||||
with self:
|
||||
rv = f(*args, **kw)
|
||||
return rv
|
||||
return _decorated
|
||||
|
||||
def __enter__(self):
|
||||
# check the permission here
|
||||
if not self.can():
|
||||
if self.http_exception:
|
||||
abort(self.http_exception)
|
||||
raise PermissionDenied(self.permission)
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
|
||||
class Permission(object):
|
||||
"""Represents needs, any of which must be present to access a resource
|
||||
|
||||
:param needs: The needs for this permission
|
||||
"""
|
||||
def __init__(self, *needs):
|
||||
"""A set of needs, any of which must be present in an identity to have
|
||||
access.
|
||||
"""
|
||||
|
||||
self.needs = set(needs)
|
||||
self.excludes = set()
|
||||
|
||||
def _bool(self):
|
||||
return bool(self.can())
|
||||
|
||||
def __nonzero__(self):
|
||||
"""Equivalent to ``self.can()``.
|
||||
"""
|
||||
return self._bool()
|
||||
|
||||
def __bool__(self):
|
||||
"""Equivalent to ``self.can()``.
|
||||
"""
|
||||
return self._bool()
|
||||
|
||||
def __and__(self, other):
|
||||
"""Does the same thing as ``self.union(other)``
|
||||
"""
|
||||
return self.union(other)
|
||||
|
||||
def __or__(self, other):
|
||||
"""Does the same thing as ``self.difference(other)``
|
||||
"""
|
||||
return self.difference(other)
|
||||
|
||||
def __contains__(self, other):
|
||||
"""Does the same thing as ``other.issubset(self)``.
|
||||
"""
|
||||
return other.issubset(self)
|
||||
|
||||
def __repr__(self):
|
||||
return '<{0} needs={1} excludes={2}>'.format(
|
||||
self.__class__.__name__, self.needs, self.excludes
|
||||
)
|
||||
|
||||
def require(self, http_exception=None):
|
||||
"""Create a principal for this permission.
|
||||
|
||||
The principal may be used as a context manager, or a decroator.
|
||||
|
||||
If ``http_exception`` is passed then ``abort()`` will be called
|
||||
with the HTTP exception code. Otherwise a ``PermissionDenied``
|
||||
exception will be raised if the identity does not meet the
|
||||
requirements.
|
||||
|
||||
:param http_exception: the HTTP exception code (403, 401 etc)
|
||||
"""
|
||||
return IdentityContext(self, http_exception)
|
||||
|
||||
def test(self, http_exception=None):
|
||||
"""
|
||||
Checks if permission available and raises relevant exception
|
||||
if not. This is useful if you just want to check permission
|
||||
without wrapping everything in a require() block.
|
||||
|
||||
This is equivalent to::
|
||||
|
||||
with permission.require():
|
||||
pass
|
||||
"""
|
||||
|
||||
with self.require(http_exception):
|
||||
pass
|
||||
|
||||
def reverse(self):
|
||||
"""
|
||||
Returns reverse of current state (needs->excludes, excludes->needs)
|
||||
"""
|
||||
|
||||
p = Permission()
|
||||
p.needs.update(self.excludes)
|
||||
p.excludes.update(self.needs)
|
||||
return p
|
||||
|
||||
def union(self, other):
|
||||
"""Create a new permission with the requirements of the union of this
|
||||
and other.
|
||||
|
||||
:param other: The other permission
|
||||
"""
|
||||
p = Permission(*self.needs.union(other.needs))
|
||||
p.excludes.update(self.excludes.union(other.excludes))
|
||||
return p
|
||||
|
||||
def difference(self, other):
|
||||
"""Create a new permission consisting of requirements in this
|
||||
permission and not in the other.
|
||||
"""
|
||||
|
||||
p = Permission(*self.needs.difference(other.needs))
|
||||
p.excludes.update(self.excludes.difference(other.excludes))
|
||||
return p
|
||||
|
||||
def issubset(self, other):
|
||||
"""Whether this permission needs are a subset of another
|
||||
|
||||
:param other: The other permission
|
||||
"""
|
||||
return (
|
||||
self.needs.issubset(other.needs) and
|
||||
self.excludes.issubset(other.excludes)
|
||||
)
|
||||
|
||||
def allows(self, identity):
|
||||
"""Whether the identity can access this permission.
|
||||
|
||||
:param identity: The identity
|
||||
"""
|
||||
if self.needs and not self.needs.intersection(identity.provides):
|
||||
return False
|
||||
|
||||
if self.excludes and self.excludes.intersection(identity.provides):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def can(self):
|
||||
"""Whether the required context for this permission has access
|
||||
|
||||
This creates an identity context and tests whether it can access this
|
||||
permission
|
||||
"""
|
||||
return self.require().can()
|
||||
|
||||
|
||||
class Denial(Permission):
|
||||
"""
|
||||
Shortcut class for passing excluded needs.
|
||||
"""
|
||||
|
||||
def __init__(self, *excludes):
|
||||
self.excludes = set(excludes)
|
||||
self.needs = set()
|
||||
|
||||
|
||||
def session_identity_loader():
|
||||
if 'identity.id' in session and 'identity.auth_type' in session:
|
||||
identity = Identity(session['identity.id'],
|
||||
session['identity.auth_type'])
|
||||
return identity
|
||||
|
||||
|
||||
def session_identity_saver(identity):
|
||||
session['identity.id'] = identity.id
|
||||
session['identity.auth_type'] = identity.auth_type
|
||||
session.modified = True
|
||||
|
||||
|
||||
class Principal(object):
|
||||
"""Principal extension
|
||||
|
||||
:param app: The flask application to extend
|
||||
:param use_sessions: Whether to use sessions to extract and store
|
||||
identification.
|
||||
:param skip_static: Whether to ignore static endpoints.
|
||||
"""
|
||||
def __init__(self, app=None, use_sessions=True, skip_static=False):
|
||||
self.identity_loaders = deque()
|
||||
self.identity_savers = deque()
|
||||
# XXX This will probably vanish for a better API
|
||||
self.use_sessions = use_sessions
|
||||
self.skip_static = skip_static
|
||||
|
||||
if app is not None:
|
||||
self.init_app(app)
|
||||
|
||||
def _init_app(self, app):
|
||||
from warnings import warn
|
||||
warn(DeprecationWarning(
|
||||
'_init_app is deprecated, use the new init_app '
|
||||
'method instead.'), stacklevel=1
|
||||
)
|
||||
self.init_app(app)
|
||||
|
||||
def init_app(self, app):
|
||||
if hasattr(app, 'static_url_path'):
|
||||
self._static_path = app.static_url_path
|
||||
else:
|
||||
self._static_path = app.static_path
|
||||
|
||||
app.before_request(self._on_before_request)
|
||||
identity_changed.connect(self._on_identity_changed, app)
|
||||
|
||||
if self.use_sessions:
|
||||
self.identity_loader(session_identity_loader)
|
||||
self.identity_saver(session_identity_saver)
|
||||
|
||||
def set_identity(self, identity):
|
||||
"""Set the current identity.
|
||||
|
||||
:param identity: The identity to set
|
||||
"""
|
||||
|
||||
self._set_thread_identity(identity)
|
||||
for saver in self.identity_savers:
|
||||
saver(identity)
|
||||
|
||||
def identity_loader(self, f):
|
||||
"""Decorator to define a function as an identity loader.
|
||||
|
||||
An identity loader function is called before request to find any
|
||||
provided identities. The first found identity is used to load from.
|
||||
|
||||
For example::
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
principals = Principal(app)
|
||||
|
||||
@principals.identity_loader
|
||||
def load_identity_from_weird_usecase():
|
||||
return Identity('ali')
|
||||
"""
|
||||
self.identity_loaders.appendleft(f)
|
||||
return f
|
||||
|
||||
def identity_saver(self, f):
|
||||
"""Decorator to define a function as an identity saver.
|
||||
|
||||
An identity loader saver is called when the identity is set to persist
|
||||
it for the next request.
|
||||
|
||||
For example::
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
principals = Principal(app)
|
||||
|
||||
@principals.identity_saver
|
||||
def save_identity_to_weird_usecase(identity):
|
||||
my_special_cookie['identity'] = identity
|
||||
"""
|
||||
self.identity_savers.appendleft(f)
|
||||
return f
|
||||
|
||||
def _set_thread_identity(self, identity):
|
||||
g.identity = identity
|
||||
identity_loaded.send(current_app._get_current_object(),
|
||||
identity=identity)
|
||||
|
||||
def _on_identity_changed(self, app, identity):
|
||||
if self._is_static_route():
|
||||
return
|
||||
|
||||
self.set_identity(identity)
|
||||
|
||||
def _on_before_request(self):
|
||||
if self._is_static_route():
|
||||
return
|
||||
|
||||
g.identity = AnonymousIdentity()
|
||||
for loader in self.identity_loaders:
|
||||
identity = loader()
|
||||
if identity is not None:
|
||||
self.set_identity(identity)
|
||||
return
|
||||
|
||||
def _is_static_route(self):
|
||||
return (
|
||||
self.skip_static and
|
||||
request.path.startswith(self._static_path)
|
||||
)
|
||||
@@ -105,7 +105,11 @@ class SettingsTestCase(unittest.TestCase):
|
||||
def test_deprecated_forwarded_getter(self, deprecated, current, forwarded):
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
called_method = getattr(self.settings, forwarded)
|
||||
|
||||
# further mock out our mocked function so things work as they should
|
||||
called_method.__name__ = to_native_str(forwarded)
|
||||
called_method.__qualname__ = to_native_str(forwarded)
|
||||
called_method.__annotations__ = dict()
|
||||
|
||||
method = getattr(self.plugin_settings, deprecated)
|
||||
self.assertTrue(callable(method))
|
||||
@@ -169,7 +173,11 @@ class SettingsTestCase(unittest.TestCase):
|
||||
def test_deprecated_forwarded_setter(self, deprecated, current, forwarded, value):
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
called_method = getattr(self.settings, forwarded)
|
||||
|
||||
# further mock out our mocked function so things work as they should
|
||||
called_method.__name__ = to_native_str(forwarded)
|
||||
called_method.__qualname__ = to_native_str(forwarded)
|
||||
called_method.__annotations__ = dict()
|
||||
|
||||
method = getattr(self.plugin_settings, deprecated)
|
||||
self.assertTrue(callable(method))
|
||||
|
||||
@@ -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
+235
-196
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user