dockge/backend/util-server.ts

98 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-11-11 15:18:37 +01:00
import { Socket } from "socket.io";
import { Terminal } from "./terminal";
import { randomBytes } from "crypto";
import { log } from "./log";
2023-12-19 18:48:20 +01:00
import { ERROR_TYPE_VALIDATION } from "../common/util-common";
2023-11-11 15:18:37 +01:00
import { R } from "redbean-node";
import { verifyPassword } from "./password-hash";
import fs from "fs";
2023-12-20 16:29:24 +01:00
import { AgentManager } from "./agent-manager";
2023-11-11 15:18:37 +01:00
export interface JWTDecoded {
username : string;
h? : string;
}
2023-11-11 15:18:37 +01:00
export interface DockgeSocket extends Socket {
userID: number;
consoleTerminal? : Terminal;
2023-12-20 16:29:24 +01:00
instanceManager : AgentManager;
2023-12-19 18:48:20 +01:00
endpoint : string;
emitAgent : (eventName : string, ...args : unknown[]) => void;
2023-11-11 15:18:37 +01:00
}
// For command line arguments, so they are nullable
export interface Arguments {
sslKey? : string;
sslCert? : string;
sslKeyPassphrase? : string;
port? : number;
hostname? : string;
dataDir? : string;
stacksDir? : string;
}
// Some config values are required
export interface Config extends Arguments {
dataDir : string;
stacksDir : string;
}
export function checkLogin(socket : DockgeSocket) {
if (!socket.userID) {
throw new Error("You are not logged in.");
}
}
export class ValidationError extends Error {
constructor(message : string) {
super(message);
}
}
export function callbackError(error : unknown, callback : unknown) {
if (typeof(callback) !== "function") {
log.error("console", "Callback is not a function");
return;
}
if (error instanceof Error) {
callback({
ok: false,
msg: error.message,
2023-12-24 15:01:17 +01:00
msgi18n: true,
2023-11-11 15:18:37 +01:00
});
} else if (error instanceof ValidationError) {
callback({
ok: false,
type: ERROR_TYPE_VALIDATION,
msg: error.message,
2023-12-24 15:01:17 +01:00
msgi18n: true,
2023-11-11 15:18:37 +01:00
});
} else {
log.debug("console", "Unknown error: " + error);
}
}
export async function doubleCheckPassword(socket : DockgeSocket, currentPassword : unknown) {
if (typeof currentPassword !== "string") {
throw new Error("Wrong data type?");
}
let user = await R.findOne("user", " id = ? AND active = 1 ", [
socket.userID,
]);
if (!user || !verifyPassword(currentPassword, user.password)) {
throw new Error("Incorrect current password");
}
return user;
}
export function fileExists(file : string) {
return fs.promises.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
}