From 73860cbb2ca9c17ccef499ce1451f746ceb06c9a Mon Sep 17 00:00:00 2001 From: Arthur Lu Date: Fri, 20 Jan 2023 06:40:21 +0000 Subject: [PATCH] sample code for interfacing with proxmox api --- index.js | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 4226651..90526d4 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ const cookieParser = require("cookie-parser") const cors = require("cors"); const helmet = require("helmet"); const morgan = require("morgan"); +const https = require("https"); var package = require("./package.json"); const app = express(); @@ -19,9 +20,58 @@ app.get("/api/version", (req, res) => { }); app.get("/api/echo", (req, res) => { - res.send({recieved: {body: req.body, cookies: req.cookies}}); + res.send({body: req.body, cookies: req.cookies}); }); +app.get("/api/auth", (req, res) => { + checkAuth(req.cookies, (result) => { + res.send(result); + }); +}); + +function checkAuth (cookies, callback, vmpath = null) { + if (vmpath) {} + else { // if no path is specified, then do a simple authentication + requestPVE("/version", "GET", cookies, (result) => { + callback(result); + }); + } +} + +function requestPVE (path, method, cookies, callback, body = null, auth = true) { + let prms = new URLSearchParams(body); + let content = { + hostname: "pve.tronnet.net", + port: 443, + path: `/api2/json${path}`, + method: method, + mode: "cors", + credentials: "include", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Cookie: `PVEAuthCookie=${cookies.PVEAuthCookie}; CSRFPreventionToken=${cookies.CSRFPreventionToken}` + } + } + if (method === "POST") { + content.body = prms.toString(); + content.headers.CSRFPreventionToken = cookies.CSRFPreventionToken; + } + https.request(content, (res) => { + let data = ""; + res.on("data", (d) => { + data += d.toString(); + }); + res.on("end", () => { + try{ + callback(JSON.parse(data)); + } + catch (e) { + callback(e); + } + }); + }).on("error", (e) => {callback(e)}).end(); +} + app.listen(80, () => { console.log("listening on port 80"); }); \ No newline at end of file