32 Commits
Author SHA1 Message Date
Arksine f4ebb93546 docs: update documentation for the Authorization component
USER_CHANGE:  The "enable" and "api_key_file" options in the [authorizaton] section are now deprecated.  A new API Key will be generated.  Use the "fetch-apikey.sh" script to retrieve the new key.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 64e794f1b5 scripts: add fetch-apikey helper script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 5bba0fc2fa scripts: bump lmdb version to 1.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine a4273d2d0a test: implement JWT Authorization for test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 0c765f7b71 app: improve http request logging
Log the current user for each request.   Dont' log requests that return with 200, 204, 206, or 304 in release mode.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 4e0e223599 authorization: allow auth related CORS Headers
Allow Authorization, X-Api-Key, and X-Access-Token headers when CORS is enabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 7eba8e58e3 authorization: add support for JWT User Authorizaton
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 43a8d25619 websockets: Store IP Address in WebRequest object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 24e6fded91 authorization: use database to store API Key
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine dee9055347 database: introduce forbidden namespaces
A Moonraker component may now register a namespace as "forbidden".   API requests have no read/write access to forbidden namespaces and this cannot be overridden by the database debug option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 0ce53bd98f app: return HTTP errors in json format
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 14991ac3b9 authorization: convert module to component
CONFIG CHANGE:  This deprecates the "enabled" option in the [authorization] section.  Authorization will be enabled if the section is included in moonraker.conf,  otherwise it will be disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 57836047f6 octoprint compat: use subscriptions to update printer data
This tends to be more efficient than polling, particularly on slower machines.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:12:26 -04:00
Arksine 9873084667 octoprint_compat: correctly report printer state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 06:20:27 -04:00
Arksine e8f6862fd2 app: cache modified time in static file handler
Force an update to cached file hashes should the modified time change.  Re-enable the "should_return_304" check so clients can re-implement caching.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-17 07:05:31 -04:00
th33xitus 4d69a1f1c6 extract_metadata: parse filament_total and filament_total_weight for Slic3r
Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
th33xitus f203567381 extract_metadata: add Cura filament weight parsing
Adds a simple implementation for parsing filament weight from Cura g-code with help of a custom start-g-code comment.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
th33xitus 0d601073a6 extract_metadata: add parsing of filament weight
This will parse the total used filament weight of g-code files created by Simplify3D, PrusaSlicer, SuperSlicer and ideaMaker

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
Arksine daf3b202c3 app: restrict static file size to the detected content length
Some static files, such as logs, can change size during a request.  This results in a content length mismatch and error.   Cap the amount read based on the original content length.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-16 07:49:44 -04:00
Arksine 087240aa67 app: don't return 304 for static files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-16 07:29:18 -04:00
Arksine 210cae2736 file_manager: check for broken symlinks in "get_file_list()"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-13 15:26:32 -04:00
th33xitus dae0f05378 extract_metadata: assign correct data parameter
This fix will now correctly parse the used filament from g-code generated by ideaMaker. The used filament is located in the footer of the g-code file.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-11 11:36:06 -04:00
Arksine 4d1a2668f5 docs: add notes about sending M112 gcodes
Also  document the new "full_version_string" field reported by the update_manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-09 14:59:39 -04:00
Arksine 7d3bba75e1 update_manager: report full version string for git repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-09 14:59:39 -04:00
fsironman b111e3d6c7 power.py add parameter timer
Add a timer parameter to shelly and tasmota integration.

Use case: 3D printer mains power is connected to one of these devices. Just turning off the smart switch will just kill power to the RaspberryPI. Adding a timer will allow the PI to shutdown cleanly before killing the power

Signed-off-by: Dominik Weis fsironman@gmail.com
2021-04-06 17:58:51 -04:00
Kamil Trzciński 6cc11276c8 Extend history API with reverse order
Signed-off-by: Kamil Trzciński <ayufan@ayufan.eu>
2021-04-05 11:41:14 -04:00
Arksine 5db596f0a5 docs: Add database debugging option to configuration.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:58:43 -04:00
Arksine aa3ffdbaaf power: fix whitespace issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:37:21 -04:00
Arksine 8724d5e9ed database: add "enable_database_debug" option
This allows protected namespaces to be modified externally.  This is for dev use only, modifying protected namespaces can potentially corrupt the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:37:21 -04:00
Arksine da9401dd1a database: make protected namespaces persistent
This fixes a bug where it is protected namespace can be modified in an optional component if that component is disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 08:25:40 -04:00
Arnaud Schaer 85b1b44e20 power.py: fix issue with single relay tasmota
add a check and handle consequently in case tasmota device is only one relay and would return a power value when asked a power1 value

Signed-off-by:  Arnaud Schaer <arnaud.schaer@wanadoo.fr>
2021-04-02 08:24:32 -04:00
Michael Kreitzer c36f989c52 power: Adding TPLinkSmartPlug multi plug support (clean-up and sign off)
Signed-off-by:  Michael Kreitzer <reztierk@gmail.com>
2021-03-31 06:55:32 -04:00
24 changed files with 1851 additions and 484 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](https://moonraker.readthedocs.io/en/latest/user_changes/) - March 10th 2021
[user_changes.md](https://moonraker.readthedocs.io/en/latest/user_changes/) - April 19th 2021
Developers:\
[api_changes.md](https://moonraker.readthedocs.io/en/latest/api_changes/) - March 15th 2021
+13 -8
View File
@@ -41,6 +41,8 @@ database_path: ~/.moonraker_database
# Moonraker (such as the "config_path" or the location where gcode
# files are stored). If the folder does not exist an attempt will be made
# to create it. The default is ~/.moonraker_database.
enable_database_debug: False
# For developer use only. End users should leave this option set to False.
temperature_store_size: 1200
# The maximum number of temperature values to store for each sensor. Note
# that this value also applies to the "target", "power", and "fan_speed"
@@ -52,19 +54,17 @@ gcode_store_size: 1000
## `[authorization]`
The `[authorization]` section provides configuration for Moonraker's
authorization module. This section is required.
authorization module.
```ini
# moonraker.conf
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
# a valid API key or originate from a trusted client. Default is True.
api_key_file: ~/.moonraker_api_key
# Path of the file that stores Moonraker's API key. The default is
# ~/.moonraker_api_key
trusted_clients:
login_timeout:
# The time, in days, after which a user is forced to re-enter their
# credentials to log in. This period begins when a logged out user
# first logs in. Successive logins without logging out will not
# renew the timeout. The default is 90 days.
192.168.1.30
192.168.1.0/24
# A list of newline separated ip addresses and/or ip ranges that are
@@ -217,6 +217,7 @@ port:
address:
password:
output_id:
timer:
# The above options are used for "tasmota" devices. The
# address should be a valid ip or hostname for the tasmota device.
# Provide a password if configured in Tasmota (default is empty).
@@ -229,12 +230,16 @@ address:
user:
password:
output_id:
timer:
# The above options are used for "shelly" devices. The
# address should be a valid ip or hostname for the Shelly device.
# Provide a user and password if configured in Shelly (default is empty).
# If password is set but user is empty the default user "admin" will be used
# Provided an output_id (relay id) if the Shelly device supports
# more than one (default is 0).
# When timer option is used to delay the turn off make sure to set
# the state to "on" in action call_remote_method.
# So we send a command to turn it on for x sec when its already on then it turns off.
address:
device:
user:
+23
View File
@@ -178,6 +178,29 @@ These options may be changed by editing
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
may also be used to modify the config file location.
### Retreiving the API Key
Some clients may require an API Key to connect to Moonraker. After the
`[authorization]` component is first configured Moonraker will automatically
generate an API Key. There are two ways in which the key may be retreived
by the user:
Retreive the API Key via the command line (SSH):
```
cd ~/moonraker/scripts
./fetch-apikey.sh
```
Retreive the API Key via the browser from a trusted client:
- Navigate to `http://{moonraker-host}/access/api_key`, where
`{moonraker-host}` is the host name or ip address of the desired
moonraker instance.
- The result will appear in the browser window in JSON format. Copy
The API Key without the quotes.
{"result": "8ce6ae5d354a4365812b83140ed62e4b"}
### Additional Notes
- Make sure that Moonraker and Klipper both have read and write access to the
+13
View File
@@ -2,6 +2,19 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### April 19th 2021
- The `[authorization]` module is now a component, thus is only
loaded if the user has it configured in `moonraker.conf`. This
deprecates the previous `enable` option, as it is enabled
if configured and disabled otherwise.
- The API Key is now stored in the database. This deprecates the
`api_key_file` option in the `[authorization]` module. Users can
no longer read the contents of the API Key file to retreive the
API Key. Instead, users can run `scripts/fetch-apikey.sh` to
print the API Key. Alternative a user can navigate to
`http://{moonraker-host}/access/api_key` from a trusted client
to retreive the API Key.
### March 10th 2021
- The `cors_domain` option in the `[authoriztion]` section is now
checked for dangerous entries. If a domain entry contains a
+227 -31
View File
@@ -163,6 +163,12 @@ JSON-RPC request:
"id": 4564
}
```
!!! note
This endpoint will immediately halt the printer and put it in a "shutdown"
state. It should be used to implement an "emergency stop" button and
also used if a user enters `M112`(emergency stop) via a console.
Returns:
`ok`
@@ -659,6 +665,14 @@ JSON-RPC request:
"id": 7466}
```
!!! warning
When `M112`(emergency stop) is requested via this endpoint it will not
immediately stop the printer. `M112` will be placed on the gcode queue and
executed after all previous gcodes are complete. If a client detects
`M112` via user input (such as a console) it should request the
`/printer/emergency_stop` endpoint to immediately halt the printer. This
may be done in addition to sending the `M112` gcode if desired.
Returns:
`ok` when the gcode has completed execution.
@@ -1417,9 +1431,209 @@ The requested file
### Authorization
Untrusted Clients must use a key to access the API by including it in the
`X-Api-Key` header for each HTTP Request. The APIs below allow authorized
clients to request or modify the current API Key.
The Authorization endpoints are enabled when the user has the
`[authorization]` component configured in `moonraker.conf`.
Untrusted clients must use either a JSON Web Token or an API key to access
Moonraker's HTTP APIs. JWTs should be included in the `Authorization`
header as a `Bearer` type for each HTTP request. If using an API Key it
should be included in the `X-Api-Key` header for each HTTP Request.
!!! warning
Clients should not use the query string to pass arguments to these
APIs. Arguments may be passed as part of the body either in JSON
format or as form-data.
#### Login User
HTTP Request:
```http
POST /access/login
Content-Type: application/json
{
"username": "my_user",
"password": "my_password"
}
```
JSON-RPC request: Not Available
Returns: An object the logged in username, auth token, refresh token,
and action summary:
```json
{
"username": "my_user",
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY4MDAuNDgxNjU1LCAiZXhwIjogMTYxODg4MDQwMC40ODE2NTUsICJ1c2VybmFtZSI6ICJteV91c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.QdieeEskrU0FrH7rXKuPDSZxscM54kV_vH60uJqdU9g",
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY4MDAuNDgxNzUxNCwgImV4cCI6IDE2MjY2NTI4MDAuNDgxNzUxNCwgInVzZXJuYW1lIjogIm15X3VzZXIiLCAidG9rZW5fdHlwZSI6ICJyZWZyZXNoIn0.btJF0LJfymInhGJQ2xvPwkp2dFUqwgcw4OA_wE-EcCM",
"action": "user_logged_in"
}
```
- The `token` field is a JSON Web Token used to authorize the user. It should
be included in the `Authorization` header as a `Bearer` type for all HTTP
requests. The `token` expires after 1 hour.
- The `refresh_token` field contains a JWT that can be used to generate new
tokens after they are expire. See the
[refresh token section](#refresh-json-web-token) for details.
!!! Note
This endpoint may be accessed by unauthorized clients. A 401 would
only be returned if the username and/or password is invalid.
#### Logout Current User
HTTP Request:
```http
POST /access/logout
```
JSON-RPC request: Not Available
Returns: An object containing the logged out username and action summary.
```json
{
"username": "my_user",
"action": "user_logged_out"
}
```
#### Get Current User
HTTP Request:
```http
GET /access/user
```
JSON-RPC request: Not Available
Returns: An object containing the currently logged in user name and
the date on which the user was created (in unix time).
```json
{
"username": "my_user",
"created_on": 1618876783.8896716
}
```
#### Create User
HTTP Request:
```http
POST /access/user
Content-Type: application/json
{
"username": "my_user",
"password": "my_password"
}
```
JSON-RPC request: Not Available
Returns: An object containing the created user name, an auth token,
a refresh token, and an action summary. Creating a user also effectively
logs the user in.
```json
{
"username": "my_user",
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY3ODMuODkxNjE5LCAiZXhwIjogMTYxODg4MDM4My44OTE2MTksICJ1c2VybmFtZSI6ICJteV91c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.oH0IShTL7mdlVs4kcx3BIs_-1j0Oe-qXezJKjo-9Xgo",
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY3ODMuODkxNzAyNCwgImV4cCI6IDE2MjY2NTI3ODMuODkxNzAyNCwgInVzZXJuYW1lIjogIm15X3VzZXIiLCAidG9rZW5fdHlwZSI6ICJyZWZyZXNoIn0.a6ZeRjk8RQQJDDH0JV-qGY_d_HIgfI3XpsqUlUaFT7c",
"action": "user_created"
}
```
!!! note
Unlike `/access/login`, `/access/user` is a protected endpoint. To
create a new user a client must either be trusted, use the API Key,
or be logged in as another user.
#### Delete User
Deletes the currently logged in user.
HTTP Request:
```http
DELETE /access/user
Content-Type: application/json
{
"password": "my_password"
}
```
JSON-RPC request: Not Available
Returns: The username of the deleted user and an action summary. This
effectively logs the user out.
```json
{
"username": "my_user",
"action": "user_deleted"
}
```
#### Reset User Password
HTTP Request:
```http
POST /access/user/password
Content-Type: application/json
{
"password": "my_current_password",
"new_password": "my_new_pass"
}
```
JSON-RPC request: Not Available
Returns: The username and action summary.
```json
{
"username": "my_user",
"action": "user_password_reset"
}
```
#### Refresh JSON Web Token
This endpoint can be used to refresh an expired auth token. If this
request returns an error then the refresh token is no longer valid and
the user must login with their credentials.
HTTP Request:
```http
POST /access/refresh_jwt
Content-Type: application/json
{
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4Nzc0ODUuNzcyMjg5OCwgImV4cCI6IDE2MjY2NTM0ODUuNzcyMjg5OCwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAicmVmcmVzaCJ9.Y5YxGuYSzwJN2WlunxlR7XNa2Y3GWK-2kt-MzHvLbP8"
}
```
JSON-RPC request: Not Available
Returns: The username, new auth token, and action summary.
```json
{
"username": "my_user",
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzgyNDMuNTE2Nzc5MiwgImV4cCI6IDE2MTg4ODE4NDMuNTE2Nzc5MiwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.Ia_X_pf20RR4RAEXcxalZIOzOBOs2OwearWHfRnTSGU",
"action": "user_jwt_refresh"
}
```
!!! Note
This endpoint may be accessed by unauthorized clients. A 401 would
only be returned if the refresh token is invalid.
#### Generate a Oneshot Token
Javascript is not capable of modifying the headers for some HTTP requests
(for example, the `websocket`), which is a requirement to apply JWT or API Key
authorization. To work around this clients may request a Oneshot Token and
pass it via the query string for these requests. Tokens expire in 5 seconds
and may only be used once, making them relatively safe for inclusion in the
query string.
HTTP request:
```http
GET /access/oneshot_token
```
JSON-RPC request: Not Available
Returns:
A temporary token that may be added to a request's query string for access
to any API endpoint. The query string should be added in the form of:
```
?token={base32_ramdom_token}
```
#### Get the Current API Key
HTTP request:
@@ -1445,29 +1659,6 @@ The newly generated API key. This overwrites the previous key. Note that
the API key change is applied immediately, all subsequent HTTP requests
from untrusted clients must use the new key.
#### Generate a Oneshot Token
Javascript is not capable of modifying the headers for some HTTP requests
(for example, the `websocket`), which is a requirement to apply `X-Api-Key`
authorization. To work around this clients may request a Oneshot Token and
pass it via the query string for these requests. Tokens expire in 5 seconds
and may only be used once, making them relatively safe for inclusion in the
query string.
HTTP request:
```http
GET /access/oneshot_token
```
JSON-RPC request: Not Available
Returns:
A temporary token that may be added to a request's query string for access
to any API endpoint. The query string should be added in the form of:
```
?token={base32_ramdom_token}
```
### Database APIs
The following endpoints provide access to Moonraker's ldbm database. The
database is divided into `namespaces`. Each client may define its own
@@ -1707,6 +1898,7 @@ and `fluidd` are present as clients configured in `moonraker.conf`
"owner": "Arksine",
"version": "v0.4.1-45",
"remote_version": "v0.4.1-45",
"full_version_string": "v0.4.1-45-g7e230c1c",
"current_hash": "7e230c1c77fa406741ab99fb9156951c4e5c9cb4",
"remote_hash": "7e230c1c77fa406741ab99fb9156951c4e5c9cb4",
"is_dirty": false,
@@ -1733,6 +1925,7 @@ and `fluidd` are present as clients configured in `moonraker.conf`
"owner": "KevinOConnor",
"version": "v0.9.1-317",
"remote_version": "v0.9.1-324",
"full_version_string": "v0.9.1-324-gd77928b1",
"current_hash": "d77928b17ba6b32189033b3d6decdb5bcc7c342c",
"remote_hash": "22753f3b389e3f21a6047bac70abc42b6cf4a7dc",
"is_dirty": false,
@@ -1783,8 +1976,9 @@ as git repos have the following fields:
be "master".
- `remote_alias`: the alias for the remote. This should typically be
"origin".
- `version`: version of the current repo on disk
- `remote_version`: version of the latest available update
- `version`: abbreviated version of the current repo on disk
- `remote_version`: abbreviated version of the latest available update
- `full_version_string`: The complete version string of the current repo.
- `current_hash`: hash of the most recent commit on disk
- `remote_hash`: hash of the most recent commit pushed to the remote
- `is_valid`: true if installation is a valid git repo on the master branch
@@ -2305,7 +2499,7 @@ The APIs below are avilable when the `[history]` component has been configured.
#### Get job list
HTTP request:
```http
GET /server/history/list?limit=50&start=50&since=1&before=5
GET /server/history/list?limit=50&start=50&since=1&before=5&order=asc
```
JSON-RPC request:
```json
@@ -2316,7 +2510,8 @@ JSON-RPC request:
"limit": 50,
"start": 10,
"since": 464.54,
"before": 1322.54
"before": 1322.54,
"order": "asc"
},
"id": 5656
}
@@ -2325,9 +2520,10 @@ JSON-RPC request:
All arguments are optional. Arguments are as follows:
- `start` Record number to start from (i.e. 10 would start at the 10th print)
- `limit` Maximum Number of prints to return
- `limit` Maximum Number of prints to return (default: 50)
- `before` All jobs before this UNIX timestamp
- `since` All jobs after this UNIX timestamp
- `order` Define return order `asc` or `desc` (default)
Returns:
+231 -21
View File
@@ -8,15 +8,17 @@ import os
import mimetypes
import logging
import json
import datetime
import traceback
import tornado
import tornado.iostream
import tornado.httputil
from inspect import isclass
from tornado.escape import url_unescape
from tornado.routing import Rule, PathMatches, AnyMatches
from tornado.log import access_log
from utils import ServerError
from websockets import WebRequest, WebsocketManager, WebSocket
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
from authorization import Authorization
from streaming_form_data import StreamingFormDataParser
from streaming_form_data.targets import FileTarget, ValueTarget
@@ -86,24 +88,23 @@ class MoonrakerApp:
# Set Up Websocket and Authorization Managers
self.wsm = WebsocketManager(self.server)
self.auth = Authorization(config['authorization'])
mimetypes.add_type('text/plain', '.log')
mimetypes.add_type('text/plain', '.gcode')
mimetypes.add_type('text/plain', '.cfg')
debug = config.getboolean('enable_debug_logging', False)
log_level = logging.DEBUG if debug else logging.INFO
self.debug = config.getboolean('enable_debug_logging', False)
log_level = logging.DEBUG if self.debug else logging.INFO
logging.getLogger().setLevel(log_level)
app_args = {
'serve_traceback': debug,
'serve_traceback': self.debug,
'websocket_ping_interval': 10,
'websocket_ping_timeout': 30,
'parent': self,
'default_handler_class': AuthorizedErrorHandler,
'default_handler_args': {}
'default_handler_args': {},
'log_function': self.log_request
}
if not debug:
app_args['log_function'] = self.log_release_mode
# Set up HTTP only requests
self.mutable_router = MutableRouter(self)
@@ -120,17 +121,16 @@ class MoonrakerApp:
"moonraker.log", logfile, force=True)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
self.auth.register_handlers(self)
def listen(self, host, port):
self.tornado_server = self.app.listen(
port, address=host, max_body_size=MAX_BODY_SIZE,
xheaders=True)
def log_release_mode(self, handler):
def log_request(self, handler):
status_code = handler.get_status()
if status_code in [200, 204]:
# don't log OK and No Content
if not self.debug and status_code in [200, 204, 206, 304]:
# don't log successful requests in release mode
return
if status_code < 400:
log_method = access_log.info
@@ -139,15 +139,17 @@ class MoonrakerApp:
else:
log_method = access_log.error
request_time = 1000.0 * handler.request.request_time()
log_method("%d %s %.2fms", status_code,
handler._request_summary(), request_time)
user = handler.current_user
username = "No User"
if user is not None and 'username' in user:
username = user['username']
log_method(
f"{status_code} {handler._request_summary()} "
f"[{username}] {request_time:.2f}ms")
def get_server(self):
return self.server
def get_auth(self):
return self.auth
def get_websocket_manager(self):
return self.wsm
@@ -156,7 +158,6 @@ class MoonrakerApp:
self.tornado_server.stop()
await self.tornado_server.close_all_connections()
await self.wsm.close()
self.auth.close()
def register_remote_handler(self, endpoint):
if endpoint in RESERVED_ENDPOINTS:
@@ -262,6 +263,92 @@ class MoonrakerApp:
self.api_cache[endpoint] = api_def
return api_def
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self):
self.server = self.settings['parent'].get_server()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
server = self.settings['parent'].get_server()
auth = server.lookup_component('authorization', None)
self.cors_enabled = False
if auth is not None:
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
auth = self.server.lookup_component('authorization', None)
if auth is not None:
self.current_user = auth.check_authorized(self.request)
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
wsm = self.settings['parent'].get_websocket_manager()
conn = wsm.get_websocket(conn_id)
return conn
def write_error(self, status_code, **kwargs):
err = {'code': status_code, 'message': self._reason}
if 'exc_info' in kwargs:
err['traceback'] = "\n".join(
traceback.format_exception(*kwargs['exc_info']))
self.finish({'error': err})
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
self.server = self.settings['parent'].get_server()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
server = self.settings['parent'].get_server()
auth = server.lookup_component('authorization', None)
self.cors_enabled = False
if auth is not None:
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
auth = self.server.lookup_component('authorization', None)
if auth is not None:
self.current_user = auth.check_authorized(self.request)
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedFileHandler, self).options()
def write_error(self, status_code, **kwargs):
err = {'code': status_code, 'message': self._reason}
if 'exc_info' in kwargs:
err['traceback'] = "\n".join(
traceback.format_exception(*kwargs['exc_info']))
self.finish({'error': err})
class DynamicRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, methods, need_object_parser=False,
is_remote=True, wrap_result=True):
@@ -348,11 +435,14 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
async def _do_local_request(self, args, conn):
return await self.callback(
WebRequest(self.request.path, args, self.request.method,
conn=conn))
conn=conn, ip_addr=self.request.remote_ip,
user=self.current_user))
async def _do_remote_request(self, args, conn):
return await self.server.make_request(
WebRequest(self.callback, args, conn=conn))
WebRequest(self.callback, args, conn=conn,
ip_addr=self.request.remote_ip,
user=self.current_user))
async def _process_http_request(self):
if self.request.method not in self.methods:
@@ -391,6 +481,119 @@ class FileRequestHandler(AuthorizedFileHandler):
raise tornado.web.HTTPError(e.status_code, str(e))
self.finish({'result': filename})
async def get(self, path: str, include_body: bool = True) -> None:
# Set up our path instance variables.
self.path = self.parse_url_path(path)
del path # make sure we don't refer to path instead of self.path again
absolute_path = self.get_absolute_path(self.root, self.path)
self.absolute_path = self.validate_absolute_path(
self.root, absolute_path)
if self.absolute_path is None:
return
self.modified = self.get_modified_time()
self.set_headers()
if self.should_return_304():
self.set_status(304)
return
request_range = None
range_header = self.request.headers.get("Range")
if range_header:
# As per RFC 2616 14.16, if an invalid Range header is specified,
# the request will be treated as if the header didn't exist.
request_range = tornado.httputil._parse_request_range(range_header)
size = self.get_content_size()
if request_range:
start, end = request_range
if start is not None and start < 0:
start += size
if start < 0:
start = 0
if (
start is not None
and (start >= size or (end is not None and start >= end))
) or end == 0:
# As per RFC 2616 14.35.1, a range is not satisfiable only: if
# the first requested byte is equal to or greater than the
# content, or when a suffix with length 0 is specified.
# https://tools.ietf.org/html/rfc7233#section-2.1
# A byte-range-spec is invalid if the last-byte-pos value is
# present and less than the first-byte-pos.
self.set_status(416) # Range Not Satisfiable
self.set_header("Content-Type", "text/plain")
self.set_header("Content-Range", "bytes */%s" % (size,))
return
if end is not None and end > size:
# Clients sometimes blindly use a large range to limit their
# download size; cap the endpoint at the actual file size.
end = size
# Note: only return HTTP 206 if less than the entire range has been
# requested. Not only is this semantically correct, but Chrome
# refuses to play audio if it gets an HTTP 206 in response to
# ``Range: bytes=0-``.
if size != (end or size) - (start or 0):
self.set_status(206) # Partial Content
self.set_header(
"Content-Range", tornado.httputil._get_content_range(
start, end, size)
)
else:
start = end = None
if start is not None and end is not None:
content_length = end - start
elif end is not None:
content_length = end
elif start is not None:
content_length = size - start
else:
end = size
content_length = size
self.set_header("Content-Length", content_length)
if include_body:
content = self.get_content(self.absolute_path, start, end)
if isinstance(content, bytes):
content = [content]
for chunk in content:
try:
self.write(chunk)
await self.flush()
except tornado.iostream.StreamClosedError:
return
else:
assert self.request.method == "HEAD"
@classmethod
def _get_cached_version(cls, abs_path: str):
with cls._lock:
hashes = cls._static_hashes
try:
mtime = datetime.datetime.fromtimestamp(
os.path.getmtime(abs_path), tz=datetime.timezone.utc)
except Exception:
logging.exception(
f"Unable to get modified time for file: {abs_path}")
hashes.pop(abs_path, None)
return None
if abs_path not in hashes or mtime != hashes[abs_path]['modified']:
try:
hashes[abs_path] = {
'modified': mtime,
'hash': cls.get_content_version(abs_path)
}
except Exception:
logging.exception(f"Could not open static file {abs_path}")
hashes.pop(abs_path, None)
return None
hsh = hashes.get(abs_path, {}).get('hash')
if hsh:
return hsh
return None
@tornado.web.stream_request_body
class FileUploadHandler(AuthorizedRequestHandler):
def initialize(self, max_upload_size):
@@ -444,3 +647,10 @@ class AuthorizedErrorHandler(AuthorizedRequestHandler):
def check_xsrf_cookie(self):
pass
def write_error(self, status_code, **kwargs):
err = {'code': status_code, 'message': self._reason}
if 'exc_info' in kwargs:
err['traceback'] = "\n".join(
traceback.format_exception(*kwargs['exc_info']))
self.finish({'error': err})
-307
View File
@@ -1,307 +0,0 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import base64
import uuid
import os
import time
import ipaddress
import re
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
from utils import ServerError
TOKEN_TIMEOUT = 5
CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
class Authorization:
def __init__(self, config):
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
self.api_key_file = os.path.expanduser(api_key_file)
self.api_key = self._read_api_key()
self.auth_enabled = config.getboolean('enabled', True)
self.trusted_connections = {}
self.access_tokens = {}
# Get allowed cors domains
self.cors_domains = []
cors_cfg = config.get('cors_domains', "").strip()
cds = [d.strip() for d in cors_cfg.split('\n')if d.strip()]
for domain in cds:
bad_match = re.search(r"^.+\.[^:]*\*", domain)
if bad_match is not None:
raise config.error(
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
" permitted in the top level domain.")
self.cors_domains.append(
domain.replace(".", "\\.").replace("*", ".*"))
# Get Trusted Clients
self.trusted_ips = []
self.trusted_ranges = []
trusted_clients = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
if c.strip()]
for ip in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(ip)
except ValueError:
tc = None
if tc is None:
# Check ip network
try:
tc = ipaddress.ip_network(ip)
except ValueError:
raise ServerError(
f"Invalid option in trusted_clients: {ip}")
self.trusted_ranges.append(tc)
else:
self.trusted_ips.append(tc)
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Auth Enabled: {self.auth_enabled}\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
def register_handlers(self, app):
# Register Authorization Endpoints
app.register_local_handler(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
app.register_local_handler(
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
async def _handle_apikey_request(self, web_request):
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, web_request):
return self.get_access_token()
def _read_api_key(self):
if os.path.exists(self.api_key_file):
with open(self.api_key_file, 'r') as f:
api_key = f.read()
return api_key
# API Key file doesn't exist. Generate
# a new api key and create the file.
logging.info(
f"No API Key file found, creating new one at:"
f"\n{self.api_key_file}")
return self._create_api_key()
def _create_api_key(self):
api_key = uuid.uuid4().hex
with open(self.api_key_file, 'w') as f:
f.write(api_key)
return api_key
def _check_authorized_ip(self, ip):
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
return False
def _prune_conn_handler(self):
cur_time = time.time()
expired_conns = []
for ip, access_time in self.trusted_connections.items():
if cur_time - access_time > CONNECTION_TIMEOUT:
expired_conns.append(ip)
for ip in expired_conns:
self.trusted_connections.pop(ip, None)
logging.info(
f"Trusted Connection Expired, IP: {ip}")
def _token_expire_handler(self, token):
self.access_tokens.pop(token, None)
def is_enabled(self):
return self.auth_enabled
def get_access_token(self):
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
self.access_tokens[token] = ioloop.call_later(
TOKEN_TIMEOUT, self._token_expire_handler, token)
return token
def _check_trusted_connection(self, ip):
if ip is not None:
if ip in self.trusted_connections:
self.trusted_connections[ip] = time.time()
return True
elif self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_connections[ip] = time.time()
return True
return False
def _check_access_token(self, token):
if token in self.access_tokens:
token_handler = self.access_tokens.pop(token, None)
IOLoop.current().remove_timeout(token_handler)
return True
else:
return False
def check_authorized(self, request):
# Authorization is disabled, request may pass
if not self.auth_enabled:
return True
# Check if IP is trusted
try:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
f"Unable to Create IP Address {request.remote_ip}")
ip = None
if self._check_trusted_connection(ip):
return True
# Check API Key Header
key = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return True
# Check one-shot access token
token = request.arguments.get('token', [b""])[0].decode()
if self._check_access_token(token):
return True
return False
def check_cors(self, origin, request=None):
if origin is None or not self.cors_domains:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, request)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
# Check to see if the origin contains an IP that matches a
# current trusted connection
match = re.search(r"^https?://([^/:]+)", origin)
if match is not None:
ip = match.group(1)
try:
ipaddr = ipaddress.ip_address(ip)
except ValueError:
pass
else:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, request)
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self, origin, request):
if request is None:
return
request.set_header("Access-Control-Allow-Origin", origin)
request.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
request.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self):
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
conn = self.wsm.get_websocket(conn_id)
return conn
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedFileHandler, self).options()
+498
View File
@@ -0,0 +1,498 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import base64
import uuid
import hashlib
import hmac
import secrets
import os
import time
import datetime
import ipaddress
import json
import re
import logging
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.web import HTTPError
from utils import ServerError
ONESHOT_TIMEOUT = 5
TRUSTED_CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
HASH_ITER = 100000
API_USER = "_API_KEY_USER_"
TRUSTED_USER = "_TRUSTED_USER_"
RESERVED_USERS = [API_USER, TRUSTED_USER]
JWT_EXP_TIME = datetime.timedelta(hours=1)
JWT_HEADER = {
'alg': "HS256",
'typ': "JWT"
}
# Helpers for base64url encoding and decoding
def base64url_encode(data):
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data):
pad_cnt = len(data) % 4
if pad_cnt:
data += b"=" * (4 - pad_cnt)
return base64.urlsafe_b64decode(data)
class Authorization:
def __init__(self, config):
self.server = config.get_server()
self.login_timeout = config.getint('login_timeout', 90)
database = self.server.lookup_component('database')
database.register_local_namespace('authorized_users', forbidden=True)
self.users = database.wrap_namespace('authorized_users')
api_user = self.users.get(API_USER, None)
if api_user is None:
self.api_key = uuid.uuid4().hex
self.users[API_USER] = {
'username': API_USER,
'api_key': self.api_key,
'created_on': time.time()
}
else:
self.api_key = api_user['api_key']
self.trusted_users = {}
self.oneshot_tokens = {}
self.permitted_paths = set()
# Get allowed cors domains
self.cors_domains = []
cors_cfg = config.get('cors_domains', "").strip()
cds = [d.strip() for d in cors_cfg.split('\n')if d.strip()]
for domain in cds:
bad_match = re.search(r"^.+\.[^:]*\*", domain)
if bad_match is not None:
raise config.error(
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
" permitted in the top level domain.")
self.cors_domains.append(
domain.replace(".", "\\.").replace("*", ".*"))
# Get Trusted Clients
self.trusted_ips = []
self.trusted_ranges = []
trusted_clients = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
if c.strip()]
for ip in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(ip)
except ValueError:
tc = None
if tc is None:
# Check ip network
try:
tc = ipaddress.ip_network(ip)
except ValueError:
raise ServerError(
f"Invalid option in trusted_clients: {ip}")
self.trusted_ranges.append(tc)
else:
self.trusted_ips.append(tc)
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
# Register Authorization Endpoints
self.permitted_paths.add("/access/login")
self.permitted_paths.add("/access/refresh_jwt")
self.server.register_endpoint(
"/access/login", ['POST'], self._handle_login)
self.server.register_endpoint(
"/access/logout", ['POST'], self._handle_logout)
self.server.register_endpoint(
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt)
self.server.register_endpoint(
"/access/user", ['GET', 'POST', 'DELETE'],
self._handle_user_request)
self.server.register_endpoint(
"/access/user/password", ['POST'], self._handle_password_reset)
self.server.register_endpoint(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
self.server.register_endpoint(
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
async def _handle_apikey_request(self, web_request):
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = uuid.uuid4().hex
self.users[f'{API_USER}.api_key'] = self.api_key
return self.api_key
async def _handle_token_request(self, web_request):
ip = web_request.get_ip_address()
user_info = web_request.get_current_user()
return self.get_oneshot_token(ip, user_info)
async def _handle_login(self, web_request):
return self._login_jwt_user(web_request)
async def _handle_logout(self, web_request):
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No user logged in")
username = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid log out request for user {username}")
self.users.pop(f"{username}.jwt_secret", None)
return {
"username": username,
"action": "user_logged_out"
}
async def _handle_refresh_jwt(self, web_request):
refresh_token = web_request.get_str('refresh_token')
user_info = self._decode_jwt(refresh_token, token_type="refresh")
username = user_info['username']
secret = bytes.fromhex(user_info['jwt_secret'])
token = self._generate_jwt(username, secret)
return {
'username': username,
'token': token,
'action': 'user_jwt_refresh'
}
async def _handle_user_request(self, web_request):
action = web_request.get_action()
if action == "GET":
user = web_request.get_current_user()
if user is None:
return {
'username': None,
'created_on': None,
}
else:
return {
'username': user['username'],
'created_on': user.get('created_on')
}
elif action == "POST":
# Create User
return self._login_jwt_user(web_request, create=True)
elif action == "DELETE":
# Delete User
return self._delete_jwt_user(web_request)
async def _handle_password_reset(self, web_request):
password = web_request.get_str('password')
new_pass = web_request.get_str('new_password')
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No Current User")
username = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Reset Request for user {username}")
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
new_hashed_pass = hashlib.pbkdf2_hmac(
'sha256', new_pass.encode(), salt, HASH_ITER).hex()
self.users[f'{username}.password'] = new_hashed_pass
return {
'username': username,
'action': "user_password_reset"
}
def _login_jwt_user(self, web_request, create=False):
username = web_request.get_str('username')
password = web_request.get_str('password')
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for user {username}")
if create:
if username in self.users:
raise self.server.error(f"User {username} already exists")
salt = secrets.token_bytes(32)
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
user_info = {
'username': username,
'password': hashed_pass,
'salt': salt.hex(),
'created_on': time.time()
}
self.users[username] = user_info
action = "user_created"
else:
if username not in self.users:
raise self.server.error(f"Unregistered User: {username}")
user_info = self.users[username]
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
action = "user_logged_in"
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
jwt_secret = user_info.get('jwt_secret', None)
if jwt_secret is None:
jwt_secret = secrets.token_bytes(32)
user_info['jwt_secret'] = jwt_secret.hex()
self.users[username] = user_info
else:
jwt_secret = bytes.fromhex(jwt_secret)
token = self._generate_jwt(username, jwt_secret)
refresh_token = self._generate_jwt(
username, jwt_secret, token_type="refresh",
exp_time=datetime.timedelta(days=self.login_timeout))
return {
'username': username,
'token': token,
'refresh_token': refresh_token,
'action': action
}
def _delete_jwt_user(self, web_request):
password = web_request.get_str('password')
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No Current User")
username = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid request for user {username}")
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
del self.users[username]
return {
"username": username,
"action": "user_deleted"
}
def _generate_jwt(self, username, secret, token_type="auth",
exp_time=JWT_EXP_TIME):
curtime = time.time()
payload = {
'iss': "Moonraker",
'iat': curtime,
'exp': curtime + exp_time.total_seconds(),
'username': username,
'token_type': token_type
}
enc_header = base64url_encode(json.dumps(JWT_HEADER).encode())
enc_payload = base64url_encode(json.dumps(payload).encode())
message = enc_header + b"." + enc_payload
signature = base64url_encode(hmac.digest(secret, message, "sha256"))
message += b"." + signature
return message.decode()
def _decode_jwt(self, jwt, token_type="auth"):
parts = jwt.encode().split(b".")
if len(parts) != 3:
raise self.server.error(f"Invalid JWT length of {len(parts)}")
header = json.loads(base64url_decode(parts[0]))
payload = json.loads(base64url_decode(parts[1]))
if header != JWT_HEADER:
raise self.server.error("Invalid JWT header")
recd_type = payload.get('token_type', "")
if token_type != recd_type:
raise self.server.error(
f"JWT Token type mismatch: Expected {token_type}, "
f"Recd: {recd_type}", 401)
if time.time() > payload['exp']:
raise self.server.error("JWT expired", 401)
username = payload.get('username')
user_info = self.users.get(username, None)
if user_info is None:
raise self.server.error(
f"Invalid JWT, no registered user {username}", 401)
jwt_secret = user_info.get('jwt_secret', None)
if jwt_secret is None:
raise self.server.error(
f"Invalid JWT, user {username} not logged in", 401)
secret = bytes.fromhex(jwt_secret)
# Decode and verify signature
signature = base64url_decode(parts[2])
calc_sig = hmac.digest(
secret, parts[0] + b"." + parts[1], "sha256")
if signature != calc_sig:
raise self.server.error("Invalid JWT signature")
return user_info
def _prune_conn_handler(self):
cur_time = time.time()
for ip, user_info in list(self.trusted_users.items()):
exp_time = user_info['expires_at']
if cur_time >= exp_time:
self.trusted_users.pop(ip, None)
logging.info(
f"Trusted Connection Expired, IP: {ip}")
def _oneshot_token_expire_handler(self, token):
self.oneshot_tokens.pop(token, None)
def get_oneshot_token(self, ip_addr, user):
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
hdl = ioloop.call_later(
ONESHOT_TIMEOUT, self._oneshot_token_expire_handler, token)
self.oneshot_tokens[token] = (ip_addr, user, hdl)
return token
def _check_json_web_token(self, request):
auth_token = request.headers.get("Authorization")
if auth_token is None:
auth_token = request.headers.get("X-Access-Token")
if auth_token and auth_token.startswith("Bearer "):
auth_token = auth_token[7:]
try:
return self._decode_jwt(auth_token)
except Exception as e:
raise HTTPError(401, str(e))
return None
def _check_authorized_ip(self, ip):
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
return False
def _check_trusted_connection(self, ip):
if ip is not None:
curtime = time.time()
exp_time = curtime + TRUSTED_CONNECTION_TIMEOUT
if ip in self.trusted_users:
self.trusted_users[ip]['expires_at'] = exp_time
return self.trusted_users[ip]
elif self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_users[ip] = {
'username': TRUSTED_USER,
'password': None,
'created_on': curtime,
'expires_at': exp_time
}
return self.trusted_users[ip]
return None
def _check_oneshot_token(self, token, cur_ip):
if token in self.oneshot_tokens:
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
IOLoop.current().remove_timeout(hdl)
if cur_ip != ip_addr:
logging.info(f"Oneshot Token IP Mismatch: expected{ip_addr}"
f", Recd: {cur_ip}")
return None
return user
else:
return None
def check_authorized(self, request):
if request.path in self.permitted_paths:
return None
# Check JSON Web Token
jwt_user = self._check_json_web_token(request)
if jwt_user is not None:
return jwt_user
try:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
f"Unable to Create IP Address {request.remote_ip}")
ip = None
# Check oneshot access token
ost = request.arguments.get('token', None)
if ost is not None:
ost_user = self._check_oneshot_token(ost[-1].decode(), ip)
if ost_user is not None:
return ost_user
# Check API Key Header
key = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return self.users[API_USER]
# Check if IP is trusted
trusted_user = self._check_trusted_connection(ip)
if trusted_user is not None:
return trusted_user
raise HTTPError(401, "Unauthorized")
def check_cors(self, origin, request=None):
if origin is None or not self.cors_domains:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, request)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
# Check to see if the origin contains an IP that matches a
# current trusted connection
match = re.search(r"^https?://([^/:]+)", origin)
if match is not None:
ip = match.group(1)
try:
ipaddr = ipaddress.ip_address(ip)
except ValueError:
pass
else:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, request)
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self, origin, request):
if request is None:
return
request.set_header("Access-Control-Allow-Origin", origin)
request.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
request.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token, Authorization, X-Access-Token, "
"X-Api-Key")
def close(self):
self.prune_handler.stop()
def load_component(config):
return Authorization(config)
+34 -7
View File
@@ -46,7 +46,7 @@ class MoonrakerDatabase:
def __init__(self, config):
self.server = config.get_server()
self.namespaces = {}
self.protected_namespaces = {"moonraker"}
self.enable_debug = config.get("enable_database_debug", False)
self.database_path = os.path.expanduser(config.get(
'database_path', "~/.moonraker_database"))
if not os.path.isdir(self.database_path):
@@ -68,7 +68,20 @@ class MoonrakerDatabase:
txn.put(b'database_version',
self._encode_value(DATABASE_VERSION),
db=mrdb)
# Protected Namespaces have read-only API access. Write access can
# be granted by enabling the debug option. Forbidden namespaces
# have no API access. This cannot be overridden.
self.protected_namespaces = set(self.get_item(
"moonraker", "database.protected_namespaces", ["moonraker"]))
self.forbidden_namespaces = set(self.get_item(
"moonraker", "database.forbidden_namespaces", []))
debug_counter = self.get_item("moonraker", "database.debug_counter", 0)
if self.enable_debug:
debug_counter += 1
self.insert_item("moonraker", "database.debug_counter",
debug_counter)
if debug_counter:
logging.info(f"Database Debug Count: {debug_counter}")
self.server.register_endpoint(
"/server/database/list", ['GET'], self._handle_list_request)
self.server.register_endpoint(
@@ -191,17 +204,25 @@ class MoonrakerDatabase:
return False
return True
def register_local_namespace(self, namespace):
def register_local_namespace(self, namespace, forbidden=False):
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
self.protected_namespaces.add(namespace)
if forbidden:
if namespace not in self.forbidden_namespaces:
self.forbidden_namespaces.add(namespace)
self.insert_item(
"moonraker", "database.forbidden_namespaces",
list(self.forbidden_namespaces))
elif namespace not in self.protected_namespaces:
self.protected_namespaces.add(namespace)
self.insert_item("moonraker", "database.protected_namespaces",
list(self.protected_namespaces))
def wrap_namespace(self, namespace, parse_keys=True):
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
self.protected_namespaces.add(namespace)
return NamespaceWrapper(namespace, self, parse_keys)
def _process_key(self, key):
@@ -270,10 +291,16 @@ class MoonrakerDatabase:
async def _handle_item_request(self, web_request):
action = web_request.get_action()
namespace = web_request.get_str("namespace")
if namespace in self.forbidden_namespaces:
raise self.server.error(
f"Read/Write access to namespace '{namespace}'"
" is forbidden", 403)
if action != "GET":
if namespace in self.protected_namespaces:
if namespace in self.protected_namespaces and \
not self.enable_debug:
raise self.server.error(
f"Namespace '{namespace}' is write protected")
f"Write access to namespaces '{namespace}'"
" is forbidden", 403)
key = web_request.get("key")
valid_types = (list, str)
else:
+6 -1
View File
@@ -510,7 +510,10 @@ class FileManager:
# Filter out directories that have already been visted. This
# prevents infinite recrusion "followlinks" is set to True
for dname in dir_names:
st = os.stat(os.path.join(dir_path, dname))
full_path = os.path.join(dir_path, dname)
if not os.path.exists(full_path):
continue
st = os.stat(full_path)
key = (st.st_dev, st.st_ino)
if key not in visited_dirs:
visited_dirs.add(key)
@@ -527,6 +530,8 @@ class FileManager:
except Exception:
logging.exception("Error processing ufp file")
continue
if not os.path.exists(full_path):
continue
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
+39 -15
View File
@@ -88,7 +88,8 @@ class History:
async def _handle_jobs_list(self, web_request):
i = 0
end_num = len(self.history_ns)
count = 0
end_num = len(self.cached_job_ids)
jobs = []
start_num = 0
@@ -96,26 +97,49 @@ class History:
since = web_request.get_float("since", -1)
limit = web_request.get_int("limit", 50)
start = web_request.get_int("start", 0)
if start >= end_num or end_num == 0:
order = web_request.get_str("order", "desc")
if not order in ["asc", "desc"]:
raise self.server.error(f"Invalid `order` value: {order}", 400)
reverse_order = (order == "desc")
# cached jobs is asc order, find lower and upper boundary
if since != -1:
while start_num < end_num:
job_id = self.cached_job_ids[start_num]
job = self.history_ns[job_id]
if job.get('start_time') > since:
break
start_num += 1
if before != -1:
while end_num > 0:
job_id = self.cached_job_ids[end_num-1]
job = self.history_ns[job_id]
if job.get('end_time') < before:
break
end_num -= 1
if start_num >= end_num or end_num == 0:
return {"count": 0, "jobs": []}
for job_id in self.cached_job_ids:
i = start
count = end_num - start_num
if limit == 0:
limit = MAX_JOBS
while i < count and len(jobs) < limit:
if reverse_order:
job_id = self.cached_job_ids[end_num - i - 1]
else:
job_id = self.cached_job_ids[start_num + i]
job = self.history_ns[job_id]
if since != -1 and since > job.get('start_time'):
start_num += 1
continue
if before != -1 and before < job.get('end_time'):
end_num -= 1
continue
if limit != 0 and i >= limit:
continue
if start != 0:
start -= 1
continue
jobs.append(self._prep_requested_job(job, job_id))
i += 1
return {"count": end_num - start_num, "jobs": jobs}
return {"count": count, "jobs": jobs}
async def _handle_job_totals(self, web_request):
return {'job_totals': self.job_totals}
+48 -38
View File
@@ -28,12 +28,15 @@ class OctoprintCompat:
self.software_version = config['system_args'].get('software_version')
# Local variables
self.klippy_apis = None
self.heaters = []
self.klippy_apis = self.server.lookup_component('klippy_apis')
self.heaters = {}
self.last_print_stats = {}
# Register status update event
self.server.register_event_handler(
'server:klippy_ready', self._init)
self.server.register_event_handler(
'server:status_update', self._handle_status_update)
# Version & Server information
self.server.register_endpoint(
@@ -76,53 +79,59 @@ class OctoprintCompat:
# TODO: shutdown/reboot/restart operations
async def _init(self):
self.klippy_apis = self.server.lookup_component('klippy_apis')
self.heaters = {}
# Fetch heaters
try:
result = await self.klippy_apis.query_objects({'heaters': None})
sensors = result.get('heaters', {}).get('available_sensors', [])
except self.server.error as e:
logging.info(f'Error Configuring heaters: {e}')
return
self.heaters = result.get('heaters', {}).get('available_sensors', [])
sensors = []
# subscribe objects
sub = {s: None for s in sensors}
sub['print_stats'] = None
result = await self.klippy_apis.subscribe_objects(sub)
self.last_print_stats = result.get('print_stats', {})
if sensors:
self.heaters = {name: result.get(name, {}) for name in sensors}
async def printer_state(self):
if not self.klippy_apis:
def _handle_status_update(self, status):
if 'print_stats' in status:
self.last_print_stats.update(status['print_stats'])
for heater_name, data in self.heaters.items():
if heater_name in status:
data.update(status[heater_name])
def printer_state(self):
klippy_state = self.server.get_klippy_state()
if klippy_state in ["disconnected", "startup"]:
return 'Offline'
if self.server.klippy_state != 'ready':
elif klippy_state != 'ready':
return 'Error'
result = await self.klippy_apis.query_objects({'print_stats': None})
return {
'standby': 'Operational',
'printing': 'Printing',
'paused': 'Paused',
'complete': 'Operational'
}.get(result.get('state', 'standby'), 'Error')
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
async def printer_temps(self):
def printer_temps(self):
temps = {}
if not self.klippy_apis:
return temps
if self.heaters:
result = await self.klippy_apis.query_objects(
{heater: None for heater in self.heaters})
for heater in self.heaters:
if heater not in result:
continue
data = result[heater]
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
elif heater != "heater_bed":
continue
temps[name] = {
'actual': round(data.get('temperature', 0.), 2),
'offset': 0,
'target': data.get('target', 0.),
}
for heater, data in self.heaters.items():
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
elif heater != "heater_bed":
continue
temps[name] = {
'actual': round(data.get('temperature', 0.), 2),
'offset': 0,
'target': data.get('target', 0.),
}
return temps
async def _get_version(self, web_request):
@@ -139,10 +148,11 @@ class OctoprintCompat:
"""
Server status
"""
klippy_state = self.server.get_klippy_state()
return {
'server': OCTO_VERSION,
'safemode': (
None if self.server.klippy_state == 'ready' else 'settings')
None if klippy_state == 'ready' else 'settings')
}
async def _post_login_user(self, web_request):
@@ -217,16 +227,16 @@ class OctoprintCompat:
'printTimeLeft': None,
'printTimeOrigin': None,
},
'state': await self.printer_state()
'state': self.printer_state()
}
async def _get_printer(self, web_request):
"""
Get Printer status
"""
state = await self.printer_state()
state = self.printer_state()
return {
'temperature': await self.printer_temps(),
'temperature': self.printer_temps(),
'state': {
'text': state,
'flags': {
+41 -8
View File
@@ -311,14 +311,22 @@ class TPLinkSmartPlug(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.addr = config.get("address").split('/')
self.port = config.getint("port", 9999)
async def _send_tplink_command(self, command):
out_cmd = {}
if command in ["on", "off"]:
out_cmd = {'system': {'set_relay_state':
{'state': int(command == "on")}}}
out_cmd = {
'system': {'set_relay_state': {'state': int(command == "on")}}
}
# TPLink device controls multiple devices
if len(self.addr) == 2:
sysinfo = await self._send_tplink_command("info")
dev_id = sysinfo["system"]["get_sysinfo"]["deviceId"]
out_cmd["context"] = {
'child_ids': [f"{dev_id}{int(self.addr[1]):02}"]
}
elif command == "info":
out_cmd = {'system': {'get_sysinfo': {}}}
else:
@@ -326,7 +334,7 @@ class TPLinkSmartPlug(PowerDevice):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stream = IOStream(s)
try:
await stream.connect((self.addr, self.port))
await stream.connect((self.addr[0], self.port))
await stream.write(self._encrypt(out_cmd))
data = await stream.read_bytes(2048, partial=True)
length = struct.unpack(">I", data[:4])[0]
@@ -378,7 +386,12 @@ class TPLinkSmartPlug(PowerDevice):
async def refresh_status(self):
try:
res = await self._send_tplink_command("info")
state = res['system']['get_sysinfo']['relay_state']
if len(self.addr) == 2:
# TPLink device controls multiple devices
children = res['system']['get_sysinfo']['children']
state = children[int(self.addr[1])]['state']
else:
state = res['system']['get_sysinfo']['relay_state']
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
@@ -407,10 +420,13 @@ class Tasmota(PowerDevice):
self.addr = config.get("address")
self.output_id = config.getint("output_id", 1)
self.password = config.get("password", "")
self.timer = config.get("timer","")
async def _send_tasmota_command(self, command, password=None):
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
if self.timer != "" and command == "off":
out_cmd = f"Backlog%20Delay%20{self.timer}0%3B%20{out_cmd}"
elif command == "info":
out_cmd = f"Power{self.output_id}"
else:
@@ -441,7 +457,13 @@ class Tasmota(PowerDevice):
async def refresh_status(self):
try:
res = await self._send_tasmota_command("info")
state = res[f"POWER{self.output_id}"].lower()
try:
state = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1 :
state = res[f"POWER"].lower()
else:
raise KeyError(e)
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
@@ -452,7 +474,14 @@ class Tasmota(PowerDevice):
async def set_power(self, state):
try:
res = await self._send_tasmota_command(state)
state = res[f"POWER{self.output_id}"].lower()
if self.timer == "" or state != "off":
try:
state = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1 :
state = res[f"POWER"].lower()
else:
raise KeyError(e)
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
@@ -469,10 +498,14 @@ class Shelly(PowerDevice):
self.output_id = config.getint("output_id", 0)
self.user = config.get("user", "admin")
self.password = config.get("password", "")
self.timer = config.get("timer","")
async def _send_shelly_command(self, command):
if command in ["on", "off"]:
out_cmd = f"relay/{self.output_id}?turn={command}"
if self.timer != "":
out_cmd = f"relay/{self.output_id}?turn={command}&timer={self.timer}"
else:
out_cmd = f"relay/{self.output_id}?turn={command}"
elif command == "info":
out_cmd = f"relay/{self.output_id}"
else:
+4 -1
View File
@@ -830,6 +830,7 @@ class GitRepo:
self.current_commit = "?"
self.upstream_commit = "?"
self.upstream_url = "?"
self.full_version_string = "?"
self.branches = []
self.dirty = False
self.head_detached = False
@@ -885,6 +886,7 @@ class GitRepo:
f"{self.git_remote}/{self.git_branch}")
current_version = await self.describe(
"--always --tags --long --dirty")
self.full_version_string = current_version.strip()
upstream_version = await self.describe(
f"{self.git_remote}/{self.git_branch} "
"--always --tags --long")
@@ -1185,7 +1187,8 @@ class GitRepo:
'is_dirty': self.dirty,
'detached': self.head_detached,
'commits_behind': self.commits_behind,
'git_messages': self.git_messages
'git_messages': self.git_messages,
'full_version_string': self.full_version_string
}
def get_version(self, upstream=False):
+4 -1
View File
@@ -138,7 +138,7 @@ class Server:
# check for optional components
opt_sections = set([s.split()[0] for s in config.sections()]) - \
set(['server', 'authorization', 'system_args'])
set(['server', 'system_args'])
for section in opt_sections:
self.load_component(config, section, None)
@@ -211,6 +211,9 @@ class Server:
def get_klippy_info(self):
return dict(self.klippy_info)
def get_klippy_state(self):
return self.klippy_state
# ***** Klippy Connection *****
async def _connect_klippy(self):
if not self.server_running:
+28 -7
View File
@@ -5,6 +5,7 @@
# This file may be distributed under the terms of the GNU GPLv3 license
import logging
import ipaddress
import tornado
import json
from tornado.ioloop import IOLoop
@@ -15,11 +16,17 @@ class Sentinel:
pass
class WebRequest:
def __init__(self, endpoint, args, action="", conn=None):
def __init__(self, endpoint, args, action="",
conn=None, ip_addr="", user=None):
self.endpoint = endpoint
self.action = action
self.args = args
self.conn = conn
try:
self.ip_addr = ipaddress.ip_address(ip_addr)
except Exception:
self.ip_addr = None
self.current_user = user
def get_endpoint(self):
return self.endpoint
@@ -33,6 +40,12 @@ class WebRequest:
def get_connection(self):
return self.conn
def get_ip_address(self):
return self.ip_addr
def get_current_user(self):
return self.current_user
def _get_converted_arg(self, key, default=Sentinel, dtype=str):
if key not in self.args:
if default == Sentinel:
@@ -202,14 +215,16 @@ class WebsocketManager:
def _generate_callback(self, endpoint):
async def func(ws, **kwargs):
result = await self.server.make_request(
WebRequest(endpoint, kwargs, conn=ws))
WebRequest(endpoint, kwargs, conn=ws, ip_addr=ws.ip_addr,
user=ws.current_user))
return result
return func
def _generate_local_callback(self, endpoint, request_method, callback):
async def func(ws, **kwargs):
result = await callback(
WebRequest(endpoint, kwargs, request_method, ws))
WebRequest(endpoint, kwargs, request_method, ws,
ip_addr=ws.ip_addr, user=ws.current_user))
return result
return func
@@ -259,11 +274,12 @@ class WebsocketManager:
class WebSocket(WebSocketHandler):
def initialize(self):
app = self.settings['parent']
self.auth = app.get_auth()
self.server = app.get_server()
self.wsm = app.get_websocket_manager()
self.rpc = self.wsm.rpc
self.uid = id(self)
self.is_closed = False
self.ip_addr = self.request.remote_ip
async def open(self):
await self.wsm.add_websocket(self)
@@ -303,9 +319,14 @@ class WebSocket(WebSocketHandler):
def check_origin(self, origin):
if not super(WebSocket, self).check_origin(origin):
return self.auth.check_cors(origin)
auth = self.server.lookup_component('authorization', None)
if auth is not None:
return auth.check_cors(origin)
return False
return True
# Check Authorized User
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
auth = self.server.lookup_component('authorization', None)
if auth is not None:
self.current_user = auth.check_authorized(self.request)
+44 -3
View File
@@ -109,6 +109,9 @@ class BaseSlicer(object):
def parse_filament_total(self):
return None
def parse_filament_weight_total(self):
return None
def parse_estimated_time(self):
return None
@@ -183,6 +186,10 @@ class PrusaSlicer(BaseSlicer):
return _regex_find_first(
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_filament_weight_total(self):
return _regex_find_first(
r"total\sfilament\sused\s\[g\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
time_match = re.search(
r';\sestimated\sprinting\stime.*', self.footer_data)
@@ -275,6 +282,17 @@ class Slic3r(Slic3rPE):
}
return None
def parse_filament_total(self):
filament = _regex_find_first(
r";\sfilament\_length\_m\s=\s(\d+\.\d*)", self.footer_data)
if filament is not None:
filament *= 1000
return filament
def parse_filament_weight_total(self):
return _regex_find_first(
r";\sfilament\smass\_g\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
return None
@@ -316,6 +334,10 @@ class Cura(PrusaSlicer):
filament *= 1000
return filament
def parse_filament_weight_total(self):
return _regex_find_first(
r";Filament\sweight\s=\s.(\d+\.\d+).", self.header_data)
def parse_estimated_time(self):
return self._parse_max_float(r";TIME:.*", self.header_data)
@@ -396,6 +418,10 @@ class Simplify3D(BaseSlicer):
return _regex_find_first(
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
def parse_filament_weight_total(self):
return _regex_find_first(
r";\s+Plastic\sweight:\s(\d+\.?\d*)\sg", self.footer_data)
def parse_estimated_time(self):
time_match = re.search(
r';\s+Build time:.*', self.footer_data)
@@ -521,11 +547,26 @@ class IdeaMaker(BaseSlicer):
def parse_filament_total(self):
filament = _regex_find_floats(
r";Material.\d\sUsed:.*", self.header_data, strict=True)
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
if filament:
return sum(filament)
return None
def parse_filament_weight_total(self):
pi = 3.141592653589793
length = _regex_find_floats(
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
diameter = _regex_find_floats(
r";Filament\sDiameter\s.\d:.*", self.header_data, strict=True)
density = _regex_find_floats(
r";Filament\sDensity\s.\d:.*", self.header_data, strict=True)
if len(length) == len(density) == len(diameter):
# calc individual weight for each filament with m=pi/4*d²*l*rho
weights = [(pi/4 * diameter[i]**2 * length[i] * density[i]/10**6)
for i in range(len(length))]
return sum(weights)
return None
def parse_estimated_time(self):
return _regex_find_first(
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
@@ -575,8 +616,8 @@ SUPPORTED_SLICERS = [
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'layer_height', 'first_layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails',
'first_layer_bed_temp', 'first_layer_extr_temp',
'filament_total', 'filament_weight_total', 'estimated_time',
'thumbnails', 'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path):
+42
View File
@@ -0,0 +1,42 @@
#!/bin/bash
# Helper Script for fetching the API Key from a moonraker database
DATABASE_PATH="${HOME}/.moonraker_database"
MOONRAKER_ENV="${HOME}/moonraker-env"
DB_ARGS="--read=READ --db=authorized_users get _API_KEY_USER_"
API_REGEX='(?<="api_key": ")([^"]+)'
print_help()
{
echo "Moonraker API Key Extraction Utility"
echo
echo "usage: fetch-apikey.sh [-h] [-e <python env path>] [-d <database path>]"
echo
echo "optional arguments:"
echo " -h show this message"
echo " -e <env path> path to Moonraker env folder"
echo " -d <database path> path to Moonraker LMDB database folder"
exit 0
}
# Parse command line arguments
while getopts "he:d:" arg; do
case $arg in
h) print_help;;
e) MOONRAKER_ENV=$OPTARG;;
d) DATABASE_PATH=$OPTARG;;
esac
done
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
if [ ! -f $PYTHON_BIN ]; then
echo "No Python binary found at '${PYTHON_BIN}'"
exit -1
fi
if [ ! -d $DATABASE_PATH ]; then
echo "No Moonraker database found at '${DATABASE_PATH}'"
exit -1
fi
${PYTHON_BIN} -mlmdb --env=${DATABASE_PATH} ${DB_ARGS} | grep -Po "${API_REGEX}"
+1 -1
View File
@@ -2,5 +2,5 @@
tornado==6.1.0
pyserial==3.4
pillow==8.1.2
lmdb==1.1.1
lmdb==1.2.0
streaming-form-data==1.8.1
+128
View File
@@ -0,0 +1,128 @@
#lean_overlay {
position: fixed;
z-index:100;
top: 0px;
left: 0px;
height:100%;
width:100%;
background: #000;
display: none;
}
.user {
width: 404px;
padding-bottom: 2px;
display:none;
background: #FFF;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
box-shadow: 0px 0px 4px rgba(0,0,0,0.7);
-webkit-box-shadow: 0 0 4px rgba(0,0,0,0.7);
-moz-box-shadow: 0 0px 4px rgba(0,0,0,0.7);
}
.user-header {
/*background: url(../img/hd-bg.png);*/
background: #cecece;
padding: 8px 8px 8px 8px;
border-bottom: 1px solid #CCC;
border-top-left-radius: 5px;
-moz-border-radius-topleft: 5px;
-webkit-border-top-left-radius: 5px;
border-top-right-radius: 5px;
-moz-border-radius-topright: 5px;
-webkit-border-top-right-radius: 5px;
}
.user-header h2 {
color: #444;
font-size: 1.2em;
font-weight: 700;
margin-bottom: 3px;
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
}
.user-header p {
color: #444;
font-size: 1em;
margin: 0;
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
text-shadow: none;
}
.user .text-field {
position: relative;
width: 364px;
padding: 14px 20px;
border-bottom: 1px solid #EEE;
text-align: right;
}
.user .button-field {
width: 254px;
overflow: hidden;
padding: 12px 20px 12px 130px;
}
.user .text-field label {
display: block;
float: left;
width: 90px;
padding-top: 8px;
color: #222;
font-size: 1em;
text-align: left;
}
.user .text-field input {
width: 244px;
padding: 8px;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 1em; color: #222;
background: #F7F7F7;
font-family: "Helvetica Neue";
outline: none;
border-top: 1px solid #CCC;
border-left: 1px solid #CCC;
border-right: 1px solid #E7E6E6;
border-bottom: 1px solid #E7E6E6;
}
/*.user .text-field input.good_input {
background: #DEF5E1 url(../img/good.png) 236px center no-repeat;
}*/
.user .text-field input.error_input {
background: #FDE0E0;
}
.user-button {
float: right;
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background: #cecece;
border: none;
width: auto;
overflow: visible;
font-size: 1.1em;
color: rgb(0, 0, 0);
padding: 7px 10px;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
text-shadow: 0 1px 0 rgba(0,0,0,0.4);
}
.modal_close {
position: absolute;
top: 12px;
right: 12px;
display: inline-block;
border: none;
width: 20px;
height: 20px;
background: url(../img/close-button.png);
z-index: 2;
}
+5
View File
@@ -0,0 +1,5 @@
// leanModal v1.1 by Ray Stone - http://finelysliced.com.au
// Dual licensed under the MIT and GPL
(function($){$.fn.extend({leanModal:function(options){var defaults={top:100,overlay:0.5,closeButton:null};var overlay=$("<div id='lean_overlay'></div>");$("body").append(overlay);options=$.extend(defaults,options);return this.each(function(){var o=options;$(this).click(function(e){var modal_id=$(this).attr("href");$("#lean_overlay").click(function(){close_modal(modal_id)});$(o.closeButton).click(function(){close_modal(modal_id)});var modal_height=$(modal_id).outerHeight();var modal_width=$(modal_id).outerWidth();
$("#lean_overlay").css({"display":"block",opacity:0});$("#lean_overlay").fadeTo(200,o.overlay);$(modal_id).css({"display":"block","position":"fixed","opacity":0,"z-index":11000,"left":50+"%","margin-left":-(modal_width/2)+"px","top":o.top+"px"});$(modal_id).fadeTo(200,1);e.preventDefault()})});function close_modal(modal_id){$("#lean_overlay").fadeOut(200);$(modal_id).css({"display":"none"})}}})})(jQuery);
Binary file not shown.

After

Width:  |  Height:  |  Size: 643 B

+90 -1
View File
@@ -2,9 +2,11 @@
<html>
<head>
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
<link rel="stylesheet" href="css/login_dialog.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="dist/jstree.min.js"></script>
<script src="/js/main.js?v=0.1.2" type="module"></script>
<script src="dist/jquery.leanModal.min.js"></script>
<script src="/js/main.js?v=0.1.3" type="module"></script>
</head>
<body>
<h3>Klippy Web API Test</h3>
@@ -67,10 +69,97 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
<button id="btnshutdown" style="width: 9em">Shutdown OS</button>
<button id="btngetlog" style="width: 9em">Klippy Log</button>
<button id="btnmoonlog" style="width: 9em">Moonraker Log</button>
<br/><br/>
<button id="btnloginuser" style="width: 9em">Login User</button>
<button id="btncreateuser" style="width: 9em">Create User</button>
<button id="btnsetapikey" style="width: 9em">Set API Key</button>
<button id="btnlogout" style="width: 9em" class="req-login">Log Out</button>
<button id="btndeluser" style="width: 9em" class="req-login">Delete User</button>
<button id="btnchangepass" style="width: 9em" class="req-login">Change Pass</button>
<br/><br/>
<span id="filename" hidden></span></br>
<div id="streamdiv">
</div>
<a id="nav_home" href="#" hidden>Hidden Home</a>
<a id="do_login" rel="leanModal" name="login" href="#login" hidden>Hidden Login</a>
<div id="login" class="user">
<div id="login-ct">
<div id="login-header" class="user-header">
<h2>Moonraker Login</h2>
<button id="login_close" class="modal_close"></a>
</div>
<form id="login_form" class="user-form">
<div class="text-field">
<label for="login_username">Username</label>
<input id="login_username" class="good_input" name="login_username" type="text" />
</div>
<div class="text-field">
<label for="login_password">Password</label>
<input id="login_password" name="login_password" type="password" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Login</button>
</div>
</form>
</div>
</div>
<a id="do_signup" rel="leanModal" name="signup" href="#signup" hidden>Hidden Signup</a>
<div id="signup" class="user">
<div id="signup-ct">
<div id="signup-header" class="user-header">
<h2>Create User</h2>
<button id="signup_close" class="modal_close"></a>
</div>
<form id="signup_form" class="user-form">
<div class="text-field">
<label for="signup_username">Username</label>
<input id="signup_username" class="good_input" name="signup_username" type="text" />
</div>
<div class="text-field">
<label for="signup_password">Password</label>
<input id="signup_password" name="signup_password" type="password" />
</div>
<div class="text-field">
<label for="signup_verify_pass">Re-Enter Password</label>
<input id="signup_verify_pass" name="signup_verify_pass" type="password" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Signup</button>
</div>
</form>
</div>
</div>
<a id="do_changepass" rel="leanModal" name="changepass" href="#changepass" hidden></a>
<div id="changepass" class="user">
<div id="changepass-ct">
<div id="changepass-header" class="user-header">
<h2>Change Password</h2>
<button id="changepass_close" class="modal_close"></a>
</div>
<form id="changepass_form" class="user-form">
<div class="text-field">
<label for="changepass_oldpass">Current Password</label>
<input id="changepass_oldpass" name="changepass_oldpass" type="password" />
</div>
<div class="text-field">
<label for="changepass_newpass">New Password</label>
<input id="changepass_newpass" name="changepass_newpass" type="password" />
</div>
<div class="text-field">
<label for="changepass_verify_pass">Re-Enter New Password</label>
<input id="changepass_verify_pass" name="changepass_verify_pass" type="password" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
+331 -33
View File
@@ -120,6 +120,12 @@ var api = {
url: "/server/files/config_examples/"
},
// Server APIs
server_info: {
url: "/server/info",
method: "server.info"
},
// Machine APIs
reboot: {
url: "/machine/reboot",
@@ -136,11 +142,28 @@ var api = {
},
oneshot_token: {
url: "/access/oneshot_token"
},
login: {
url: "/access/login"
},
logout: {
url: "/access/logout"
},
refresh_jwt: {
url: "/access/refresh_jwt"
},
user: {
url: "/access/user"
},
reset_password: {
url: "/access/user/password"
}
}
var websocket = null;
var apikey = null;
var auth_token = null;
var refresh_token = window.localStorage.getItem('refresh_token');
var paused = false;
var klippy_ready = false;
var api_type = 'http';
@@ -859,6 +882,17 @@ function run_request(url, method, callback=null)
let settings = {
url: url,
method: method,
statusCode: {
401: function() {
if (refresh_token != null) {
refresh_json_web_token(run_request, url, method, callback);
}
else {
auth_token = null;
$("#do_login").click();
}
}
},
success: (resp, status) => {
console.log(resp);
if (callback != null)
@@ -872,7 +906,9 @@ function run_request(url, method, callback=null)
settings.contentType = false,
settings.processData = false
}
if (apikey != null)
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
$.ajax(settings);
}
@@ -894,9 +930,9 @@ function form_delete_request(api_url, query_string="", callback=null) {
function form_download_request(uri) {
let dl_url = origin + uri;
if (apikey != null) {
form_get_request(api.oneshot_token.url,
callback=(resp) => {
if (apikey != null || auth_token != null) {
form_get_request(api.oneshot_token.url, "",
(resp) => {
let token = resp.result;
dl_url += "?token=" + token;
do_download(dl_url);
@@ -961,7 +997,9 @@ function jstree_populate_children(node, callback) {
if (api_type == "http") {
let qs = `?path=${node.id}`;
let settings = {url: origin + api.directory.url + qs};
if (apikey != null)
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
$.get(settings, (resp, status) => {
callback(generate_children(resp.result, node));
@@ -1130,6 +1168,7 @@ class KlippyWebsocket {
this.onmessage = null;
this.onopen = null;
this.id = null;
this.reconnect = true
this.connect();
}
@@ -1138,14 +1177,15 @@ class KlippyWebsocket {
// to reconnect if its closed. This is nice as it allows the
// client to easily recover from Klippy restarts without user
// intervention
if (apikey != null) {
if (apikey != null || auth_token != null) {
// Fetch a oneshot token to pass websocket authorization
let token_settings = {
url: origin + api.oneshot_token.url,
headers: {
"X-Api-Key": apikey
}
}
if (auth_token != null)
token_settings.headers = {"Authorization": `Bearer ${auth_token}`};
else
token_settings.headers = {"X-Api-Key": apikey};
$.get(token_settings, (data, status) => {
let token = data.result;
let url = this.base_address + "/websocket?token=" + token;
@@ -1172,10 +1212,14 @@ class KlippyWebsocket {
klippy_ready = false;
this.connected = false;
this.id = null;
console.log("Websocket Closed, reconnecting in 1s: ", e.reason);
setTimeout(() => {
this.connect();
}, 1000);
// TODO: Need to cancel any pending JSON-RPC requests
if (this.reconnect) {
console.log("Websocket Closed, reconnecting in 1s: ", e.reason);
setTimeout(() => {
if (this.reconnect)
this.connect();
}, 1000);
}
};
this.ws.onerror = (err) => {
@@ -1202,7 +1246,7 @@ class KlippyWebsocket {
}
close() {
// TODO: Cancel the timeout
this.reconnect = false
this.ws.close();
}
@@ -1227,25 +1271,172 @@ function create_websocket(url) {
json_rpc.register_transport(websocket);
}
function login_jwt_user(user, pass, do_create) {
if (!user || !pass) {
alert("Invalid username/password")
return;
}
let close_btn_name = "#login_close"
if (do_create)
close_btn_name = "#signup_close"
let settings = {
url: origin + api.login.url,
data: JSON.stringify({username: user, password: pass}),
contentType: "application/json",
dataType: 'json'
}
if (do_create) {
settings.url = origin + api.user.url;
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
}
$.post(settings, (resp, status) => {
let res = resp.result;
console.log("Login Response:");
console.log(res);
auth_token = res.token;
refresh_token = res.refresh_token;
window.localStorage.setItem('refresh_token', refresh_token);
$('.req-login').prop('disabled', false);
$(close_btn_name).click();
check_authorization();
}).fail(() => {
console.log("Login Failed");
alert("Login Failed")
});
}
function logout_jwt_user() {
if (auth_token == null) {
console.log("No User Logged In")
return;
}
let settings = {
url: origin + api.logout.url,
contentType: "application/json",
dataType: 'json',
headers: {
"Authorization": `Bearer ${auth_token}`
}
}
$.post(settings, (resp, status) => {
let res = resp.result;
console.log("Logout Response:");
console.log(res);
auth_token = null;
refresh_token = null;
window.localStorage.removeItem('refresh_token');
$('.req-login').prop('disabled', true);
}).fail(() => {
console.log("Logout User Failed");
});
}
function delete_jwt_user(pass) {
if (!pass) {
alert("Invalid Password, Cannot Delete User");
return;
}
if (auth_token == null) {
console.log("No User Logged In")
return;
}
let settings = {
method: 'DELETE',
url: origin + api.user.url,
contentType: "application/json",
data: JSON.stringify({password: pass}),
dataType: 'json',
headers: {
"Authorization": `Bearer ${auth_token}`
},
success: (resp, status) => {
let res = resp.result;
console.log("Delete User Response:");
console.log(res);
auth_token = null;
refresh_token = null;
window.localStorage.removeItem('refresh_token');
$('.req-login').prop('disabled', true);
}
}
$.ajax(settings)
.fail(() => {
console.log("Delete User Failed");
});
}
function change_jwt_password(old_pass, new_pass) {
if (!old_pass || !new_pass) {
alert("Invalid input for change password")
return;
}
let settings = {
url: origin + api.reset_password.url,
data: JSON.stringify({password: old_pass, new_password: new_pass}),
contentType: "application/json",
dataType: 'json',
headers: {
"Authorization": `Bearer ${auth_token}`
}
}
$.post(settings, (resp, status) => {
let res = resp.result;
console.log("Change Password Response:");
console.log(res);
$("#changepass_close").click();
}).fail(() => {
console.log("Failed to change password");
alert("Password Reset Failed")
});
}
function refresh_json_web_token(callback, ...args) {
let settings = {
url: origin + api.refresh_jwt.url,
data: JSON.stringify({refresh_token: refresh_token}),
contentType: "application/json",
dataType: 'json',
}
$.post(settings, (resp, status) => {
let res = resp.result;
console.log("Refresh JWT Response:");
console.log(res);
auth_token = res.token;
$('.req-login').prop('disabled', false);
if (callback != null)
callback(...args);
}).fail(() => {
console.log("Refresh JWT Failed");
auth_token = null;
refresh_token = null;
window.localStorage.removeItem('refresh_token');
$('.req-login').prop('disabled', true);
$("#do_login").click();
});
}
function check_authorization() {
// send a HTTP "run gcode" command
let settings = {
url: origin + api.printer_info.url,
url: origin + api.server_info.url,
statusCode: {
401: function() {
// Show APIKey Popup
let result = window.prompt("Enter a valid API Key:", "");
if (result == null || result.length != 32) {
console.log("Invalid API Key: " + result);
apikey = null;
} else {
apikey = result;
}
check_authorization();
if (refresh_token != null) {
refresh_json_web_token(check_authorization);
} else {
$("#do_login").click();
}
}
}
}
if (apikey != null)
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
$.get(settings, (data, status) => {
// Create a websocket if /printer/info successfully returns
@@ -1261,11 +1452,9 @@ function do_download(url) {
window.onload = () => {
// Handle changes between the HTTP and Websocket API
$('.reqws').prop('disabled', true);
$('.req-login').prop('disabled', true);
$('input[type=radio][name=test_type]').on('change', function() {
api_type = $(this).val();
let disable_transfer = (!$('#cbxFileTransfer').is(":checked") && is_printing);
$('.toggleable').prop(
'disabled', (api_type == 'websocket' || disable_transfer));
$('.reqws').prop('disabled', (api_type == 'http'));
$('#apimethod').prop('hidden', (api_type == "websocket"));
$('#apiargs').prop('hidden', (api_type == "http"));
@@ -1467,7 +1656,9 @@ window.onload = () => {
let sendtype = $("input[type=radio][name=api_cmd_type]:checked").val();
let url = $('#apirequest').val();
let settings = {url: url}
if (apikey != null)
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
if (sendtype == "get") {
console.log("Sending GET " + url);
@@ -1553,7 +1744,9 @@ window.onload = () => {
return false;
}
};
if (apikey != null)
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
$.ajax(settings);
$('#upload-file').val('');
@@ -1645,11 +1838,13 @@ window.onload = () => {
$('#btntestmesh').click(() => {
if (api_type == 'http') {
let settings = {url: origin + api.object_status.url + "?bed_mesh"};
if (apikey != null)
if (auth_token != null)
settings.headers = {"Authorization": `Bearer ${auth_token}`};
else if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
$.get(settings, (resp, status) => {
process_mesh(resp.result)
return false;
process_mesh(resp.result)
return false;
});
} else {
get_mesh();
@@ -1726,5 +1921,108 @@ window.onload = () => {
form_download_request(api.moonraker_log.url);
});
$('#btnloginuser').click(() => {
$("#do_login").click();
});
$('#btncreateuser').click(() => {
$("#do_signup").click();
});
$('#btnlogout').click(() => {
logout_jwt_user();
});
$('#btndeluser').click(() => {
let password = window.prompt("Verify your password:")
delete_jwt_user(password);
});
$('#btnchangepass').click(() => {
$("#do_changepass").click();
});
$('#btnsetapikey').click(() => {
let defkey = apikey;
if (!defkey)
defkey = ""
let new_key = window.prompt("Enter your API Key", defkey);
if (!new_key)
apikey = null;
else
apikey = new_key;
check_authorization();
});
$("#do_login").leanModal({
top : 200,
overlay : 0.4,
closeButton: "#login_close"
});
$("#do_signup").leanModal({
top : 200,
overlay : 0.4,
closeButton: "#signup_close"
});
$("#do_changepass").leanModal({
top : 200,
overlay : 0.4,
closeButton: "#changepass_close"
});
$("#login_close").click(() => {
//$("#login_username").val("");
$("#login_password").val("");
$("#nav_home").click();
});
$("#signup_close").click(() => {
$("#signup_username").val("");
$("#signup_password").val("");
$("#signup_verify_pass").val("");
$("#nav_home").click();
});
$("#changepass_close").click(() => {
$("#changepass_oldpass").val("");
$("#changepass_newpass").val("");
$("#changepass_verify_pass").val("");
$("#nav_home").click();
});
$("#login_form").submit((evt)=> {
let user = $("#login_username").val()
let pass = $("#login_password").val()
if (user != "" && pass != "")
login_jwt_user(user, pass, false);
else
alert("Invalid username/password");
return false;
});
$("#signup_form").submit((evt)=> {
let user = $("#signup_username").val()
let pass = $("#signup_password").val()
let verify_pass = $("#signup_verify_pass").val()
if (user != "" && pass != "" && pass == verify_pass)
login_jwt_user(user, pass, true);
else
alert("Invalid username/password");
return false;
});
$("#changepass_form").submit((evt)=> {
let old_pass = $("#changepass_oldpass").val()
let new_pass = $("#changepass_newpass").val()
let verify_pass = $("#changepass_verify_pass").val()
if (old_pass != "" && new_pass != "" && new_pass == verify_pass)
change_jwt_password(old_pass, new_pass)
else
alert("All fields are required to change password");
return false;
});
check_authorization();
};