Update documentation

This commit is contained in:
Donald Zou 2024-08-15 16:55:34 -04:00
parent ee0a287112
commit 1a70acc6f2
2 changed files with 148 additions and 20 deletions

View file

@ -13,14 +13,152 @@
1. To request an API Key, simply login to your WGDashboard, go to **Settings**, scroll to the very bottom. Click the **switch** on the right to enable API Key. 1. To request an API Key, simply login to your WGDashboard, go to **Settings**, scroll to the very bottom. Click the **switch** on the right to enable API Key.
2. Click the blur **Create** button, set an **expiry date** you want or **never expire**, then click **Done**. 2. Click the blur **Create** button, set an **expiry date** you want or **never expire**, then click **Done**.
### Use API Key in `fetch()` ### Use API Key
- Simply add `wg-dashboard-apikey` with the value of your API key into the HTTP Header.
```javascript ```javascript
fetch('http://server:10086', { fetch('http://server:10086/api/handshake', {
headers: { headers: {
'content-type': 'application/json', 'content-type': 'application/json',
'wg-dashboard-apikey': 'insert your api key here' 'wg-dashboard-apikey': 'insert your api key here'
} },
method: "GET"
}) })
``` ```
To use API Key, simply insert `wg-dashboard-apikey` with the value of your API key into the `header` in your http request.
## API Endpoints
### Handshake to Server
This endpoint is designed for a simple handshake when using API key to connect. If `status` is `true` that means
#### Request
`GET /api/handshake`
#### Response
`200 - OK`
```json
{
"data": null,
"message": null,
"status": true
}
```
`401 - UNAUTHORIZED`
```json
{
"data": null,
"message": "Unauthorized access.",
"status": false
}
```
> Notice: this `401` response will return at all endpoint if your API Key or session is invalid.
### Validate Authentication
This endpoint if needed for non-cross-server access. This will check if the cookie on the client side is still valid on the server side.
#### Request
`GET /api/validateAuthentication`
#### Response
`200 - OK`
Session is still valid
```json
{
"data": null,
"message": null,
"status": true
}
```
Session is invalid
```json
{
"data": null,
"message": "Invalid authentication.",
"status": false
}
```
### Authenticate
This endpoint is dedicated for non-cross-server access. It is used to authenticate user's username, password and TOTP
#### Request
`POST /api/authenticate`
##### Body Parameters
```json
{
"username": "admin",
"password": "admin",
"totp": "123456"
}
```
**`username`** string
**`password`** string
**`totp`** string
#### Response
`200 - OK`
If username, password and TOTP matched
```json
{
"data": null,
"message": null,
"status": true
}
```
If username, password or TOTP is not match
```json
{
"data": null,
"message": "Sorry, your username, password or OTP is incorrect.",
"status": false
}
```
=============
### Endpoint
Description
#### Request
`GET`
#### Response
`200 - OK`
```json
```

View file

@ -1083,6 +1083,9 @@ class DashboardConfig:
}, },
"Other": { "Other": {
"welcome_session": "true" "welcome_session": "true"
},
"Database":{
"type": "sqlite"
} }
} }
@ -1422,7 +1425,7 @@ def API_ValidateAPIKey():
def API_ValidateAuthentication(): def API_ValidateAuthentication():
token = request.cookies.get("authToken") + "" token = request.cookies.get("authToken") + ""
if token == "" or "username" not in session or session["username"] != token: if token == "" or "username" not in session or session["username"] != token:
return ResponseObject(False, "Invalid authentication") return ResponseObject(False, "Invalid authentication.")
return ResponseObject(True) return ResponseObject(True)
@ -1434,17 +1437,13 @@ def API_AuthenticateLogin():
authToken = hashlib.sha256(f"{request.headers.get('wg-dashboard-apikey')}{datetime.now()}".encode()).hexdigest() authToken = hashlib.sha256(f"{request.headers.get('wg-dashboard-apikey')}{datetime.now()}".encode()).hexdigest()
session['username'] = authToken session['username'] = authToken
resp = ResponseObject(True, DashboardConfig.GetConfig("Other", "welcome_session")[1]) resp = ResponseObject(True, DashboardConfig.GetConfig("Other", "welcome_session")[1])
print(data['host']) resp.set_cookie("authToken", authToken)
resp.set_cookie("authToken", authToken, domain=data['host'])
session.permanent = True session.permanent = True
return resp return resp
valid = bcrypt.checkpw(data['password'].encode("utf-8"), valid = bcrypt.checkpw(data['password'].encode("utf-8"),
DashboardConfig.GetConfig("Account", "password")[1].encode("utf-8")) DashboardConfig.GetConfig("Account", "password")[1].encode("utf-8"))
totpEnabled = DashboardConfig.GetConfig("Account", "enable_totp")[1] totpEnabled = DashboardConfig.GetConfig("Account", "enable_totp")[1]
totpValid = False totpValid = False
if totpEnabled: if totpEnabled:
totpValid = pyotp.TOTP(DashboardConfig.GetConfig("Account", "totp_key")[1]).now() == data['totp'] totpValid = pyotp.TOTP(DashboardConfig.GetConfig("Account", "totp_key")[1]).now() == data['totp']
@ -1459,7 +1458,6 @@ def API_AuthenticateLogin():
session.permanent = True session.permanent = True
DashboardLogger.log(str(request.url), str(request.remote_addr), Message=f"Login success: {data['username']}") DashboardLogger.log(str(request.url), str(request.remote_addr), Message=f"Login success: {data['username']}")
return resp return resp
DashboardLogger.log(str(request.url), str(request.remote_addr), Message=f"Login failed: {data['username']}") DashboardLogger.log(str(request.url), str(request.remote_addr), Message=f"Login failed: {data['username']}")
if totpEnabled: if totpEnabled:
return ResponseObject(False, "Sorry, your username, password or OTP is incorrect.") return ResponseObject(False, "Sorry, your username, password or OTP is incorrect.")
@ -1467,7 +1465,7 @@ def API_AuthenticateLogin():
return ResponseObject(False, "Sorry, your username or password is incorrect.") return ResponseObject(False, "Sorry, your username or password is incorrect.")
@app.route(f'{APP_PREFIX}/api/signout') @app.get(f'{APP_PREFIX}/api/signout')
def API_SignOut(): def API_SignOut():
resp = ResponseObject(True, "") resp = ResponseObject(True, "")
resp.delete_cookie("authToken") resp.delete_cookie("authToken")
@ -2090,19 +2088,11 @@ def peerJobScheduleBackgroundThread():
AllPeerJobs.runJob() AllPeerJobs.runJob()
time.sleep(180) time.sleep(180)
def gunicornConfig(): def gunicornConfig():
_, app_ip = DashboardConfig.GetConfig("Server", "app_ip") _, app_ip = DashboardConfig.GetConfig("Server", "app_ip")
_, app_port = DashboardConfig.GetConfig("Server", "app_port") _, app_port = DashboardConfig.GetConfig("Server", "app_port")
return app_ip, app_port return app_ip, app_port
import sys
if sys.version_info < (3, 10):
from typing_extensions import ParamSpec
else:
from typing import ParamSpec
AllPeerShareLinks: PeerShareLinks = PeerShareLinks() AllPeerShareLinks: PeerShareLinks = PeerShareLinks()
AllPeerJobs: PeerJobs = PeerJobs() AllPeerJobs: PeerJobs = PeerJobs()