ProxmoxAAS-API/src/utils.js

74 lines
2.4 KiB
JavaScript
Raw Normal View History

import { getUsedResources, requestPVE } from "./pve.js";
import { db } from "./db.js";
2023-06-29 21:35:19 +00:00
export async function checkAuth (cookies, res, vmpath = null) {
let auth = false;
if (db.getUserConfig(cookies.username) === null) {
auth = false;
2023-06-29 21:35:19 +00:00
res.status(401).send({ auth, path: vmpath ? `${vmpath}/config` : "/version", error: `User ${cookies.username} not found in localdb.` });
res.end();
return false;
}
if (vmpath) {
2023-06-29 21:35:19 +00:00
const result = await requestPVE(`/${vmpath}/config`, "GET", cookies);
auth = result.status === 200;
2023-06-29 22:09:57 +00:00
}
else { // if no path is specified, then do a simple authentication
2023-06-29 21:35:19 +00:00
const result = await requestPVE("/version", "GET", cookies);
auth = result.status === 200;
}
if (!auth) {
2023-06-29 21:35:19 +00:00
res.status(401).send({ auth, path: vmpath ? `${vmpath}/config` : "/version", error: "User token did not pass authentication check." });
res.end();
}
return auth;
}
2023-06-29 21:35:19 +00:00
export async function getUserResources (req, username) {
const dbResources = db.getGlobalConfig().resources;
2023-06-29 21:35:19 +00:00
const used = await getUsedResources(req, dbResources);
const max = db.getUserConfig(username).resources.max;
const avail = {};
Object.keys(max).forEach((k) => {
if (dbResources[k] && dbResources[k].type === "list") {
avail[k] = structuredClone(max[k]);
used[k].forEach((usedDeviceName) => {
2023-06-29 21:35:19 +00:00
const index = avail[k].findIndex((maxElement) => usedDeviceName.includes(maxElement));
avail[k].splice(index, 1);
});
2023-06-29 22:09:57 +00:00
}
else {
avail[k] = max[k] - used[k];
}
});
2023-06-29 21:35:19 +00:00
return { used, max, avail, resources: dbResources };
}
2023-06-29 21:35:19 +00:00
export async function approveResources (req, username, request) {
const user = await getUserResources(req, username);
const avail = user.avail;
const resources = user.resources;
let approved = true;
Object.keys(request).forEach((key) => {
if (!(key in avail)) { // if requested resource is not in avail, block
approved = false;
2023-06-29 22:09:57 +00:00
}
else if (resources[key].type === "list") {
2023-06-29 21:35:19 +00:00
const inAvail = avail[key].some(availElem => request[key].includes(availElem));
if (inAvail !== resources[key].whitelist) {
approved = false;
}
2023-06-29 22:09:57 +00:00
}
else if (isNaN(avail[key]) || isNaN(request[key])) { // if either the requested or avail resource is NaN, block
approved = false;
2023-06-29 22:09:57 +00:00
}
else if (avail[key] - request[key] < 0) { // if the avail resources is less than the requested resources, block
approved = false;
2023-06-09 02:05:26 +00:00
}
});
return approved; // if all requested resources pass, allow
2023-06-29 21:35:19 +00:00
}