Refactor main host setup
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
import type {
|
||||
BUN_SQLITE_WGUI_CLIENTS,
|
||||
BUN_SQLITE_WGUI_CLIENT_RULES,
|
||||
BUN_SQLITE_WGUI_HOSTS,
|
||||
} from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { TableType, User } from "@/src/types";
|
||||
import manageWireguardHost from "./manage-wireguard-host";
|
||||
import grabHostDirnames from "./grab-host-dir-names";
|
||||
import grabClientDirnames from "./grab-client-dir-names";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
type Params = {
|
||||
host_id: number;
|
||||
user: User;
|
||||
};
|
||||
|
||||
export default async function deleteWireguardHost({
|
||||
host_id,
|
||||
user,
|
||||
}: Params): Promise<APIResponseObject> {
|
||||
try {
|
||||
const host_clients_res = await BunSQLite.select<
|
||||
BUN_SQLITE_WGUI_CLIENTS,
|
||||
TableType
|
||||
>({
|
||||
table: "clients",
|
||||
query: {
|
||||
query: {
|
||||
host_id: { value: String(host_id) },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const clients = host_clients_res.payload || [];
|
||||
|
||||
for (let i = 0; i < clients.length; i++) {
|
||||
const client = clients[i];
|
||||
if (!client?.id) continue;
|
||||
|
||||
await BunSQLite.delete<BUN_SQLITE_WGUI_CLIENT_RULES, TableType>({
|
||||
table: "client_rules",
|
||||
query: {
|
||||
query: {
|
||||
client_id: { value: String(client.id) },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { CLIENT_DIR } = grabClientDirnames({
|
||||
client,
|
||||
host_id,
|
||||
});
|
||||
|
||||
try {
|
||||
execSync(`rm -rf ${CLIENT_DIR}`, { encoding: "utf-8" });
|
||||
} catch {}
|
||||
|
||||
await BunSQLite.delete<BUN_SQLITE_WGUI_CLIENTS, TableType>({
|
||||
table: "clients",
|
||||
targetId: client.id,
|
||||
});
|
||||
}
|
||||
|
||||
const { HOST_CONFIG_DIR, INTERFACE_NAME } = grabHostDirnames({
|
||||
host: { id: host_id },
|
||||
});
|
||||
|
||||
try {
|
||||
manageWireguardHost({
|
||||
action: "down",
|
||||
host_id,
|
||||
});
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
execSync(`rm -rf ${HOST_CONFIG_DIR}`, { encoding: "utf-8" });
|
||||
} catch {}
|
||||
|
||||
const del_host = await BunSQLite.sql({
|
||||
sql: `DELETE FROM HOSTS WHERE id=?`,
|
||||
values: [host_id],
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: `Host ${host_id} deleted`,
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user