Skip to content

Commit

Permalink
Integrate PyUdisk as a placeholder feature
Browse files Browse the repository at this point in the history
  • Loading branch information
dormant-user committed Nov 25, 2024
1 parent 6511926 commit 9c16d1b
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 20 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
venv/
__pycache__/

dist/
build/
PyNinja.egg-info/

Expand Down
2 changes: 1 addition & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2434,7 +2434,7 @@ <h1>PyNinja - Monitor<a class="headerlink" href="#pyninja-monitor" title="Permal

<dl class="py function">
<dt class="sig sig-object py" id="pyninja.monitor.routes.monitor_endpoint">
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pyninja.monitor.routes.</span></span><span class="sig-name descname"><span class="pre">monitor_endpoint</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">request</span></span><span class="p"><span class="pre">:</span></span><span class="w"> </span><span class="n"><span class="pre">Request</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">session_token</span></span><span class="p"><span class="pre">:</span></span><span class="w"> </span><span class="n"><span class="pre">str</span></span><span class="w"> </span><span class="o"><span class="pre">=</span></span><span class="w"> </span><span class="default_value"><span class="pre">Cookie(None)</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyninja.monitor.routes.monitor_endpoint" title="Permalink to this definition"></a></dt>
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pyninja.monitor.routes.</span></span><span class="sig-name descname"><span class="pre">monitor_endpoint</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">request</span></span><span class="p"><span class="pre">:</span></span><span class="w"> </span><span class="n"><span class="pre">Request</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">session_token</span></span><span class="p"><span class="pre">:</span></span><span class="w"> </span><span class="n"><span class="pre">str</span></span><span class="w"> </span><span class="o"><span class="pre">=</span></span><span class="w"> </span><span class="default_value"><span class="pre">Cookie(None)</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">render</span></span><span class="p"><span class="pre">:</span></span><span class="w"> </span><span class="n"><span class="pre">str</span></span><span class="w"> </span><span class="o"><span class="pre">=</span></span><span class="w"> </span><span class="default_value"><span class="pre">Cookie(None)</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pyninja.monitor.routes.monitor_endpoint" title="Permalink to this definition"></a></dt>
<dd><p>Renders the UI for monitoring page.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
Expand Down
2 changes: 1 addition & 1 deletion pyninja/monitor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from fastapi import Depends
from fastapi.routing import APIRoute, APIWebSocketRoute

from . import authenticator, config, resources, routes # noqa: F401
from . import authenticator, config, drive, resources, routes # noqa: F401


def get_all_monitor_routes(
Expand Down
16 changes: 16 additions & 0 deletions pyninja/monitor/drive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import os

from fastapi.responses import HTMLResponse


def report():
"""Generated disk utility report and returns an HTMLResponse."""
try:
import pyudisk

report_file = os.path.join(os.getcwd(), "disk-report.html")
return HTMLResponse(
content=pyudisk.generate_report(filepath=report_file, raw=True)
)
except Exception:
return None
44 changes: 29 additions & 15 deletions pyninja/monitor/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,13 @@ async def login_endpoint(
status_code=HTTPStatus.OK,
)
response.set_cookie(**await monitor.authenticator.generate_cookie(auth_payload))
response.set_cookie(key="render", value=request.headers.get("Content-Type"))
return response


async def monitor_endpoint(request: Request, session_token: str = Cookie(None)):
async def monitor_endpoint(
request: Request, session_token: str = Cookie(None), render: str = Cookie(None)
):
"""Renders the UI for monitoring page.
Args:
Expand Down Expand Up @@ -119,20 +122,31 @@ async def monitor_endpoint(request: Request, session_token: str = Cookie(None)):
return await monitor.config.clear_session(
await monitor.authenticator.session_error(request, error)
)
ctx = monitor.resources.landing_page()
ctx["request"] = request
ctx["version"] = version.__version__
LOGGER.info("Rendering initial context for monitoring page!")
return monitor.config.templates.TemplateResponse(name="main.html", context=ctx)
else:
return monitor.config.templates.TemplateResponse(
name="index.html",
context={
"request": request,
"signin": "/login",
"version": f"v{version.__version__}",
},
)
if render == "monitor":
ctx = monitor.resources.landing_page()
ctx["request"] = request
ctx["version"] = version.__version__
LOGGER.info("Rendering initial context for monitoring page!")
return monitor.config.templates.TemplateResponse(
name="main.html", context=ctx
)
elif render == "drive":
LOGGER.info("Rendering disk report!")
response = monitor.drive.report()
# If drive option is chosen during login page, the cookie is deleted once logged in!
response.delete_cookie(key="render")
return response
# todo: Implement a better way to handle this
# Currently if the drive option is selected, the only way to logout is refreshing the page
# Add drive attributes in websocket handler is OS is Linux
return monitor.config.templates.TemplateResponse(
name="index.html",
context={
"request": request,
"signin": "/login",
"version": f"v{version.__version__}",
},
)


async def websocket_endpoint(websocket: WebSocket, session_token: str = Cookie(None)):
Expand Down
14 changes: 11 additions & 3 deletions pyninja/monitor/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,10 @@ <h2 style="margin-top:5%">This page requires JavaScript
<input type="password" id="password" name="password" required>
<i class="fa-regular fa-eye" id="eye"></i>
</div>
<button type="submit" onclick="submitToAPI(event)">Sign In</button>
<button type="submit" onclick="submitToAPI(event, 'monitor')">Sign In</button>
<br>
<!-- todo: this option should ONLY be available for Linux servers -->
<button type="submit" onclick="submitToAPI(event, 'drive')">Disk Report</button>
</form>
</div>
</div>
Expand All @@ -165,14 +168,18 @@ <h2 style="margin-top:5%">This page requires JavaScript
</script>
<!-- handle authentication from login page -->
<script>
async function submitToAPI(event) {
async function submitToAPI(event, render) {
event.preventDefault();
const username = $("#username").val();
const password = $("#password").val();
if (username === "" || password === "") {
alert("ERROR: Username and password are required to authenticate your request!");
return false;
}
// todo: Implement a better way to handle this
if (render === "drive") {
alert("Endpoint does not have a logout option. So refresh the page to terminate the session.");
}

async function ConvertStringToHex(str) {
let arr = [];
Expand Down Expand Up @@ -210,7 +217,8 @@ <h2 style="margin-top:5%">This page requires JavaScript
url: origin.concat("{{ signin }}"),
headers: {
'accept': 'application/json',
'Authorization': `Bearer ${btoa(authHeaderValue)}`
'Authorization': `Bearer ${btoa(authHeaderValue)}`,
'Content-Type': render
},
crossDomain: "true",
contentType: "application/json; charset=utf-8",
Expand Down
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ dependencies = { file = ["requirements.txt"] }

[project.optional-dependencies]
dev = ["sphinx==5.1.1", "pre-commit", "recommonmark", "gitverse"]
extra = [
# "windows-only; sys_platform == 'win32'",
"PyUdisk>=0.0.2; sys_platform == 'linux'",
# "macos-only; sys_platform == 'darwin'"
]

[project.scripts]
# sends all the args to commandline function, where the arbitary commands as processed accordingly
Expand Down

0 comments on commit 9c16d1b

Please sign in to comment.