clean up naming and add /settings/ to path

This commit is contained in:
Milo Schwartz
2024-11-02 15:44:48 -04:00
parent c05342dd25
commit 54ba205fc0
34 changed files with 523 additions and 784 deletions

View File

@@ -0,0 +1,47 @@
"use client";
import { SidebarNav } from "@app/components/sidebar-nav";
import { useResourceContext } from "@app/hooks/useResourceContext";
const sidebarNavItems = [
{
title: "General",
href: "/{orgId}/settings/resources/{resourceId}",
},
{
title: "Targets",
href: "/{orgId}/settings/resources/{resourceId}/targets",
},
];
export function ClientLayout({
isCreate,
children,
}: {
isCreate: boolean;
children: React.ReactNode;
}) {
const { resource } = useResourceContext();
return (
<div className="hidden space-y-6 0 pb-16 md:block">
<div className="space-y-0.5">
<h2 className="text-2xl font-bold tracking-tight">
{isCreate ? "New Resource" : resource?.name + " Settings"}
</h2>
<p className="text-muted-foreground">
{isCreate
? "Create a new resource"
: "Configure the settings on your resource: " +
resource?.name || ""}
.
</p>
</div>
<div className="flex flex-col space-y-6 lg:flex-row lg:space-x-12 lg:space-y-0">
<aside className="-mx-4 lg:w-1/5">
<SidebarNav items={sidebarNavItems} disabled={isCreate} />
</aside>
<div className="flex-1 lg:max-w-2xl">{children}</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,241 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import {
CaretSortIcon,
CheckIcon,
} from "@radix-ui/react-icons";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { cn } from "@/lib/utils";
import { toast } from "@/hooks/use-toast";
import { Button} from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import React, { useState, useEffect } from "react";
import { api } from "@/api";
import { useParams } from "next/navigation";
import { useRouter } from "next/navigation";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { ListSitesResponse } from "@server/routers/site";
import { AxiosResponse } from "axios";
import CustomDomainInput from "./CustomDomainInput";
const method = [
{ label: "Wireguard", value: "wg" },
{ label: "Newt", value: "newt" },
] as const;
const accountFormSchema = z.object({
subdomain: z
.string()
.min(2, {
message: "Name must be at least 2 characters.",
})
.max(30, {
message: "Name must not be longer than 30 characters.",
}),
name: z.string(),
siteId: z.number(),
});
type AccountFormValues = z.infer<typeof accountFormSchema>;
const defaultValues: Partial<AccountFormValues> = {
subdomain: "someanimalherefromapi",
name: "My Resource",
};
export function CreateResourceForm() {
const params = useParams();
const orgId = params.orgId;
const router = useRouter();
const [sites, setSites] = useState<ListSitesResponse["sites"]>([]);
const [domainSuffix, setDomainSuffix] = useState<string>(".example.com");
const form = useForm<AccountFormValues>({
resolver: zodResolver(accountFormSchema),
defaultValues,
});
useEffect(() => {
if (typeof window !== "undefined") {
const fetchSites = async () => {
const res = await api.get<AxiosResponse<ListSitesResponse>>(
`/org/${orgId}/sites/`
);
setSites(res.data.data.sites);
};
fetchSites();
}
}, []);
async function onSubmit(data: AccountFormValues) {
console.log(data);
const res = await api
.put(`/org/${orgId}/site/${data.siteId}/resource/`, {
name: data.name,
subdomain: data.subdomain,
// subdomain: data.subdomain,
})
.catch((e) => {
toast({
title: "Error creating resource...",
});
});
if (res && res.status === 201) {
const niceId = res.data.data.niceId;
// navigate to the resource page
router.push(`/${orgId}/settings/resources/${niceId}`);
}
}
return (
<>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8"
>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is the name that will be displayed for
this resource.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="subdomain"
render={({ field }) => (
<FormItem>
<FormLabel>Subdomain</FormLabel>
<FormControl>
{/* <Input placeholder="Your name" {...field} /> */}
<CustomDomainInput
{...field}
domainSuffix={domainSuffix}
placeholder="Enter subdomain"
/>
</FormControl>
<FormDescription>
This is the fully qualified domain name that
will be used to access the resource.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="siteId"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Site</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
role="combobox"
className={cn(
"w-[350px] justify-between",
!field.value &&
"text-muted-foreground"
)}
>
{field.value
? sites.find(
(site) =>
site.siteId ===
field.value
)?.name
: "Select site"}
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-[350px] p-0">
<Command>
<CommandInput placeholder="Search site..." />
<CommandList>
<CommandEmpty>
No site found.
</CommandEmpty>
<CommandGroup>
{sites.map((site) => (
<CommandItem
value={site.name}
key={site.siteId}
onSelect={() => {
form.setValue(
"siteId",
site.siteId
);
}}
>
<CheckIcon
className={cn(
"mr-2 h-4 w-4",
site.siteId ===
field.value
? "opacity-100"
: "opacity-0"
)}
/>
{site.name}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
<FormDescription>
This is the site that will be used in the
dashboard.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Create Resource</Button>
</form>
</Form>
</>
);
}

View File

@@ -0,0 +1,47 @@
"use client";
import * as React from "react";
import { Input } from "@/components/ui/input";
interface CustomDomainInputProps {
domainSuffix: string;
placeholder?: string;
onChange?: (value: string) => void;
}
export default function CustomDomainInput(
{
domainSuffix,
placeholder = "Enter subdomain",
onChange,
}: CustomDomainInputProps = {
domainSuffix: ".example.com",
}
) {
const [value, setValue] = React.useState("");
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
setValue(newValue);
if (onChange) {
onChange(newValue);
}
};
return (
<div className="relative w-full max-w-sm">
<div className="flex">
<Input
type="text"
placeholder={placeholder}
value={value}
onChange={handleChange}
className="rounded-r-none flex-grow"
/>
<div className="inline-flex items-center px-3 rounded-r-md border border-l-0 border-input bg-muted text-muted-foreground">
<span className="text-sm">{domainSuffix}</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,174 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { CaretSortIcon, CheckIcon } from "@radix-ui/react-icons";
import { Input } from "@/components/ui/input";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useResourceContext } from "@app/hooks/useResourceContext";
import { ListSitesResponse } from "@server/routers/site";
import { useEffect, useState } from "react";
import { AxiosResponse } from "axios";
import api from "@app/api";
import { useParams } from "next/navigation";
import { useForm } from "react-hook-form";
const GeneralFormSchema = z.object({
name: z.string(),
siteId: z.number(),
});
type GeneralFormValues = z.infer<typeof GeneralFormSchema>;
export function GeneralForm() {
const params = useParams();
const orgId = params.orgId;
const { resource, updateResource } = useResourceContext();
const [sites, setSites] = useState<ListSitesResponse["sites"]>([]);
const form = useForm<GeneralFormValues>({
resolver: zodResolver(GeneralFormSchema),
defaultValues: {
name: resource?.name,
siteId: resource?.siteId,
},
mode: "onChange",
});
useEffect(() => {
if (typeof window !== "undefined") {
const fetchSites = async () => {
const res = await api.get<AxiosResponse<ListSitesResponse>>(
`/org/${orgId}/sites/`
);
setSites(res.data.data.sites);
};
fetchSites();
}
}, []);
async function onSubmit(data: GeneralFormValues) {
await updateResource({ name: data.name, siteId: data.siteId });
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
This is the display name of the resource.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="siteId"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Site</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
role="combobox"
className={cn(
"w-[350px] justify-between",
!field.value &&
"text-muted-foreground"
)}
>
{field.value
? sites.find(
(site) =>
site.siteId ===
field.value
)?.name
: "Select site"}
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-[350px] p-0">
<Command>
<CommandInput placeholder="Search site..." />
<CommandList>
<CommandEmpty>
No site found.
</CommandEmpty>
<CommandGroup>
{sites.map((site) => (
<CommandItem
value={site.name}
key={site.siteId}
onSelect={() => {
form.setValue(
"siteId",
site.siteId
);
}}
>
<CheckIcon
className={cn(
"mr-2 h-4 w-4",
site.siteId ===
field.value
? "opacity-100"
: "opacity-0"
)}
/>
{site.name}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
<FormDescription>
This is the site that will be used in the
dashboard.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Update Resource</Button>
</form>
</Form>
);
}

View File

@@ -0,0 +1,51 @@
import Image from "next/image";
import ResourceProvider from "@app/providers/ResourceProvider";
import { internal } from "@app/api";
import { GetResourceResponse } from "@server/routers/resource";
import { AxiosResponse } from "axios";
import { redirect } from "next/navigation";
import { authCookieHeader } from "@app/api/cookies";
import Link from "next/link";
import { ClientLayout } from "./components/ClientLayout";
interface ResourceLayoutProps {
children: React.ReactNode;
params: Promise<{ resourceId: number | string; orgId: string }>;
}
export default async function ResourceLayout(props: ResourceLayoutProps) {
const params = await props.params;
const { children } = props;
let resource = null;
if (params.resourceId !== "create") {
try {
const res = await internal.get<AxiosResponse<GetResourceResponse>>(
`/resource/${params.resourceId}`,
await authCookieHeader()
);
resource = res.data.data;
} catch {
redirect(`/${params.orgId}/settings/resources`);
}
}
return (
<>
<div className="mb-4">
<Link
href={`/${params.orgId}/settings/resources`}
className="text-primary font-medium"
></Link>
</div>
<ResourceProvider resource={resource}>
<ClientLayout isCreate={params.resourceId === "create"}>
{children}
</ClientLayout>
</ResourceProvider>
</>
);
}

View File

@@ -0,0 +1,29 @@
import React from "react";
import { Separator } from "@/components/ui/separator";
import { CreateResourceForm } from "./components/CreateResource";
import { GeneralForm } from "./components/GeneralForm";
export default async function ResourcePage(props: {
params: Promise<{ resourceId: number | string }>;
}) {
const params = await props.params;
const isCreate = params.resourceId === "create";
return (
<div className="space-y-6">
<div>
<h3 className="text-lg font-medium">
{isCreate ? "Create Resource" : "General"}
</h3>
<p className="text-sm text-muted-foreground">
{isCreate
? "Create a new resource"
: "Edit basic resource settings"}
</p>
</div>
<Separator />
{isCreate ? <CreateResourceForm /> : <GeneralForm />}
</div>
);
}

View File

@@ -0,0 +1,272 @@
"use client";
import { useEffect, useState, use } from "react";
import { PlusCircle, Trash2, Server, Globe, Cpu } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import api from "@app/api";
import { AxiosResponse } from "axios";
import { ListTargetsResponse } from "@server/routers/target/listTargets";
const isValidIPAddress = (ip: string) => {
const ipv4Regex =
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return ipv4Regex.test(ip);
};
export default function ReverseProxyTargets(
props: {
params: Promise<{ resourceId: number }>;
}
) {
const params = use(props.params);
const [targets, setTargets] = useState<ListTargetsResponse["targets"]>([]);
const [nextId, setNextId] = useState(1);
const [ipError, setIpError] = useState("");
useEffect(() => {
if (typeof window !== "undefined") {
const fetchSites = async () => {
const res = await api.get<AxiosResponse<ListTargetsResponse>>(
`/resource/${params.resourceId}/targets`,
);
setTargets(res.data.data.targets);
};
fetchSites();
}
}, []);
const [newTarget, setNewTarget] = useState({
resourceId: params.resourceId,
ip: "",
method: "http",
port: 80,
protocol: "TCP",
});
const addTarget = () => {
if (!isValidIPAddress(newTarget.ip)) {
setIpError("Invalid IP address format");
return;
}
setIpError("");
api.put(`/resource/${params.resourceId}/target`, {
...newTarget,
resourceId: undefined,
})
.catch((err) => {
console.error(err);
})
.then((res) => {
// console.log(res)
setTargets([
...targets,
{ ...newTarget, targetId: nextId, enabled: true },
]);
setNextId(nextId + 1);
setNewTarget({
resourceId: params.resourceId,
ip: "",
method: "GET",
port: 80,
protocol: "http",
});
});
};
const removeTarget = (targetId: number) => {
api.delete(`/target/${targetId}`)
.catch((err) => {
console.error(err);
})
.then((res) => {
setTargets(
targets.filter((target) => target.targetId !== targetId),
);
});
};
const toggleTarget = (targetId: number) => {
setTargets(
targets.map((target) =>
target.targetId === targetId
? { ...target, enabled: !target.enabled }
: target,
),
);
api.post(`/target/${targetId}`, {
enabled: !targets.find((target) => target.targetId === targetId)
?.enabled,
}).catch((err) => {
console.error(err);
});
};
return (
<div className="space-y-6">
<form
onSubmit={(e) => {
e.preventDefault();
addTarget();
}}
className="space-y-4"
>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="ip">IP Address</Label>
<Input
id="ip"
value={newTarget.ip}
onChange={(e) => {
setNewTarget({
...newTarget,
ip: e.target.value,
});
setIpError("");
}}
required
/>
{ipError && (
<p className="text-red-500 text-sm">{ipError}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="method">Method</Label>
<Select
value={newTarget.method}
onValueChange={(value) =>
setNewTarget({ ...newTarget, method: value })
}
>
<SelectTrigger id="method">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
<SelectItem value="http">HTTP</SelectItem>
<SelectItem value="https">HTTPS</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="port">Port</Label>
<Input
id="port"
type="number"
value={newTarget.port}
onChange={(e) =>
setNewTarget({
...newTarget,
port: parseInt(e.target.value),
})
}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="protocol">Protocol</Label>
<Select
value={newTarget.protocol}
onValueChange={(value) =>
setNewTarget({ ...newTarget, protocol: value })
}
>
<SelectTrigger id="protocol">
<SelectValue placeholder="Select protocol" />
</SelectTrigger>
<SelectContent>
<SelectItem value="UDP">UDP</SelectItem>
<SelectItem value="TCP">TCP</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<Button type="submit">
<PlusCircle className="mr-2 h-4 w-4" /> Add Target
</Button>
</form>
<div className="space-y-4">
{targets.map((target, i) => (
<Card
key={i}
id={`target-${target.targetId}`}
className="w-full p-4"
>
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2 px-0 pt-0">
<CardTitle className="text-lg font-medium flex items-center">
<Server className="mr-2 h-5 w-5" />
Target {target.targetId}
</CardTitle>
<div className="flex flex-col items-end space-y-2">
<Switch
checked={target.enabled}
onCheckedChange={() =>
toggleTarget(target.targetId)
}
/>
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() =>
removeTarget(target.targetId)
}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardHeader>
<CardContent className="px-0 py-2">
<div className="grid gap-2 md:grid-cols-2 lg:grid-cols-3">
<div className="flex items-center">
<Globe className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="text-sm">
{target.ip}:{target.port}
</span>
</div>
<div className="flex items-center">
<Cpu className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="text-sm">
{target.resourceId}
</span>
</div>
<div className="flex items-center space-x-2">
<Badge
variant={
target.enabled
? "default"
: "secondary"
}
>
{target.method}
</Badge>
<Badge
variant={
target.enabled
? "default"
: "secondary"
}
>
{target.protocol?.toUpperCase()}
</Badge>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</div>
);
}