wg-dashboard/app/peers/page.tsx
Matheus Sampaio Queiroga e6cab72032
Init pages and two routers
Signed-off-by: Matheus Sampaio Queiroga <srherobrine20@gmail.com>
2024-02-03 21:12:51 -03:00

96 lines
3.0 KiB
TypeScript

import { Peer, wgPeer } from "@db/peers";
import { wgServer } from "@db/server";
import { Users } from "@db/users";
import { Download } from "@mui/icons-material";
import { extendNet } from "@sirherobrine23/extends";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { key } from "wireguard-tools.js";
function PeerComponent(props: Peer) {
return (<div>
<hr />
<div>
<div>Owner: {props.owner}</div>
<div>interface owner: {props.interfaceOwner}</div>
<div>Private key: {props.privateKey}</div>
{props.presharedKey && <div>Preshared key: {props.presharedKey}</div>}
<div>IPv4: {props.IPv4}</div>
<div>IPv6: {props.IPv6}</div>
<a href={`peers/${props.id}/config/api?type=quick`} download>
<Download />
<span>Download quick config file</span>
</a>
</div>
</div>);
}
function NukePeers() {
"use client";
async function Nuke() {
"use server";
await wgPeer.destroy({ where: {} });
redirect("/peers");
}
return <form action={Nuke}>
<input type="submit" value="Nuke peers" />
</form>
}
export default async function Home() {
const peers = (await wgPeer.findAll()).map(s => s.toJSON());
const servers = (await wgServer.findAll({ attributes: [ "id", "name" ] })).map(s => s.toJSON());
const owners = (await Users.findAll({ attributes: [ "username", "userID" ] })).map(s => s.toJSON());
async function createPeer(form: FormData) {
"use server";
const owner = parseInt(form.get("owner") as any), interfaceOwner = parseInt(form.get("interfaceOwner") as any), presharedKeyGen = Boolean(form.get("presharedKeyGen"));
const interfaceInfo = await wgServer.findOne({ where: { id: interfaceOwner } });
const base: Partial<Peer> = {
owner,
interfaceOwner,
privateKey: await key.privateKey(),
presharedKey: presharedKeyGen ? await key.presharedKey() : null,
};
do {
base.IPv4 = await extendNet.randomIp(interfaceInfo.IPv4);
} while (await wgPeer.findOne({ where: { IPv4: base.IPv4 } }));
base.IPv6 = extendNet.toString(extendNet.toInt(base.IPv4), true);
await wgPeer.create(base);
revalidatePath("/peers");
}
return <div>
<div>
<h1>Wireguard peers</h1>
</div>
<div>
<form action={createPeer}>
<div>
<span>Select peer owner: </span>
<select name="owner">
{owners.map(s => <option value={s.userID}>{s.username}</option>)}
</select>
</div>
<div>
<span>Interface peer target: </span>
<select name="interfaceOwner">
{servers.map(s => <option value={s.id}>{s.name}</option>)}
</select>
</div>
<div>
<span>Generate preshared key?</span>
<input type="checkbox" defaultChecked name="presharedKeyGen" />
</div>
<div>
<input type="submit" value="Create peer" />
</div>
</form>
</div>
<NukePeers />
<div>
{peers.map(s => PeerComponent(s))}
</div>
</div>;
}