fix api crash on username missing from lcoaldb

This commit is contained in:
Arthur Lu 2023-05-23 00:11:48 +00:00
parent c8c42d3b95
commit 7e7f9b2b55
4 changed files with 35 additions and 21 deletions

7
db.js
View File

@ -24,5 +24,10 @@ export function getResourceConfig() {
}
export function getUserConfig(username) {
return db.users[username];
if (db.users[username]) {
return db.users[username];
}
else {
return null;
}
}

View File

@ -6,8 +6,8 @@ import morgan from "morgan";
import api from "./package.json" assert {type: "json"};
import { pveAPIToken, listenPort, hostname, domain } from "./vars.js";
import { checkAuth, requestPVE, handleResponse, getDiskInfo } from "./pve.js";
import { getAllocatedResources, approveResources } from "./utils.js";
import { requestPVE, handleResponse, getDiskInfo } from "./pve.js";
import { checkAuth, getAllocatedResources, approveResources } from "./utils.js";
import { getUserConfig } from "./db.js";
const app = express();

17
pve.js
View File

@ -1,23 +1,6 @@
import axios from 'axios';
import { pveAPI, pveAPIToken } from "./vars.js";
export async function checkAuth(cookies, res, vmpath = null) {
let auth = false;
if (vmpath) {
let result = await requestPVE(`/${vmpath}/config`, "GET", cookies);
auth = result.status === 200;
}
else { // if no path is specified, then do a simple authentication
let result = await requestPVE("/version", "GET", cookies);
auth = result.status === 200;
}
if (!auth) {
res.status(401).send({ auth: auth, path: vmpath ? `${vmpath}/config` : "/version" });
res.end();
}
return auth;
}
export async function requestPVE(path, method, cookies, body = null, token = null) {
let url = `${pveAPI}${path}`;
let content = {

View File

@ -1,6 +1,32 @@
import { getUsedResources } from "./pve.js";
import { getUsedResources, requestPVE } from "./pve.js";
import { getUserConfig, getResourceConfig } from "./db.js";
export async function checkAuth(cookies, res, vmpath = null) {
let auth = false;
if (getUserConfig(cookies.username) === null) {
auth = false;
res.status(401).send({ auth: auth, path: vmpath ? `${vmpath}/config` : "/version", error: `user ${cookies.username} not found in localdb` });
res.end();
return false;
}
if (vmpath) {
let result = await requestPVE(`/${vmpath}/config`, "GET", cookies);
auth = result.status === 200;
}
else { // if no path is specified, then do a simple authentication
let result = await requestPVE("/version", "GET", cookies);
auth = result.status === 200;
}
if (!auth) {
res.status(401).send({ auth: auth, path: vmpath ? `${vmpath}/config` : "/version", error: `user token did not pass authentication check` });
res.end();
}
return auth;
}
export async function getAllocatedResources(req, username) {
let dbResources = getResourceConfig();
let used = await getUsedResources(req, dbResources);