mirror of
https://github.com/fosrl/pangolin.git
synced 2026-03-05 02:06:41 +00:00
clean up naming and add /settings/ to path
This commit is contained in:
147
src/app/[orgId]/settings/components/Header.tsx
Normal file
147
src/app/[orgId]/settings/components/Header.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
"use client";
|
||||
|
||||
import api from "@app/api";
|
||||
import { Avatar, AvatarFallback } from "@app/components/ui/avatar";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@app/components/ui/dropdown-menu";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@app/components/ui/select";
|
||||
import { useToast } from "@app/hooks/use-toast";
|
||||
import { ListOrgsResponse } from "@server/routers/org";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
type HeaderProps = {
|
||||
name?: string;
|
||||
email: string;
|
||||
orgName: string;
|
||||
orgs: ListOrgsResponse["orgs"];
|
||||
};
|
||||
|
||||
export default function Header({ email, orgName, name, orgs }: HeaderProps) {
|
||||
const { toast } = useToast();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
function getInitials() {
|
||||
if (name) {
|
||||
const [firstName, lastName] = name.split(" ");
|
||||
return `${firstName[0]}${lastName[0]}`;
|
||||
}
|
||||
return email.substring(0, 2).toUpperCase();
|
||||
}
|
||||
|
||||
function logout() {
|
||||
api.post("/auth/logout")
|
||||
.catch((e) => {
|
||||
console.error("Error logging out", e);
|
||||
toast({
|
||||
title: "Error logging out",
|
||||
});
|
||||
})
|
||||
.then(() => {
|
||||
router.push("/auth/login");
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="relative h-10 w-10 rounded-full"
|
||||
>
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarFallback>
|
||||
{getInitials()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-56"
|
||||
align="start"
|
||||
forceMount
|
||||
>
|
||||
<DropdownMenuLabel className="font-normal">
|
||||
<div className="flex flex-col space-y-1">
|
||||
{name && (
|
||||
<p className="text-sm font-medium leading-none truncate">
|
||||
{name}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs leading-none text-muted-foreground truncate">
|
||||
{email}
|
||||
</p>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={logout}>
|
||||
Log out
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<span className="truncate max-w-[150px] md:max-w-none font-medium">
|
||||
{name || email}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<div className="hidden md:block">
|
||||
<div className="flex items-center gap-4 mr-4">
|
||||
<Link
|
||||
href="/docs"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Documentation
|
||||
</Link>
|
||||
<Link
|
||||
href="/support"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Support
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Select defaultValue={orgName}>
|
||||
<SelectTrigger className="w-[100px] md:w-[180px]">
|
||||
<SelectValue placeholder="Select an org" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{orgs.map((org) => (
|
||||
<SelectItem
|
||||
value={org.name}
|
||||
key={org.orgId}
|
||||
>
|
||||
{org.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
62
src/app/[orgId]/settings/components/TopbarNav.tsx
Normal file
62
src/app/[orgId]/settings/components/TopbarNav.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface TopbarNavProps extends React.HTMLAttributes<HTMLElement> {
|
||||
items: {
|
||||
href: string;
|
||||
title: string;
|
||||
icon: React.ReactNode;
|
||||
}[];
|
||||
disabled?: boolean;
|
||||
orgId: string;
|
||||
}
|
||||
|
||||
export function TopbarNav({
|
||||
className,
|
||||
items,
|
||||
disabled = false,
|
||||
orgId,
|
||||
...props
|
||||
}: TopbarNavProps) {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<nav
|
||||
className={cn(
|
||||
"flex overflow-x-auto space-x-4 lg:space-x-6",
|
||||
disabled && "opacity-50 pointer-events-none",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href.replace("{orgId}", orgId)}
|
||||
className={cn(
|
||||
"px-2 py-3 text-md",
|
||||
pathname.startsWith(item.href.replace("{orgId}", orgId))
|
||||
? "border-b-2 border-primary text-primary font-medium"
|
||||
: "hover:text-primary text-muted-foreground font-medium",
|
||||
"whitespace-nowrap",
|
||||
disabled && "cursor-not-allowed",
|
||||
)}
|
||||
onClick={disabled ? (e) => e.preventDefault() : undefined}
|
||||
tabIndex={disabled ? -1 : undefined}
|
||||
aria-disabled={disabled}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{item.icon && (
|
||||
<div className="hidden md:block">{item.icon}</div>
|
||||
)}
|
||||
{item.title}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
96
src/app/[orgId]/settings/layout.tsx
Normal file
96
src/app/[orgId]/settings/layout.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { Metadata } from "next";
|
||||
import { TopbarNav } from "./components/TopbarNav";
|
||||
import { Cog, Combine, Users, Waypoints } from "lucide-react";
|
||||
import Header from "./components/Header";
|
||||
import { verifySession } from "@app/lib/auth/verifySession";
|
||||
import { redirect } from "next/navigation";
|
||||
import { internal } from "@app/api";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { GetOrgResponse, ListOrgsResponse } from "@server/routers/org";
|
||||
import { authCookieHeader } from "@app/api/cookies";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: `Settings - Pangolin`,
|
||||
description: "",
|
||||
};
|
||||
|
||||
const topNavItems = [
|
||||
{
|
||||
title: "Sites",
|
||||
href: "/{orgId}/settings/sites",
|
||||
icon: <Combine className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
title: "Resources",
|
||||
href: "/{orgId}/settings/resources",
|
||||
icon: <Waypoints className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
title: "Users",
|
||||
href: "/{orgId}/settings/users",
|
||||
icon: <Users className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
title: "General",
|
||||
href: "/{orgId}/settings/general",
|
||||
icon: <Cog className="h-5 w-5" />,
|
||||
},
|
||||
];
|
||||
|
||||
interface SettingsLayoutProps {
|
||||
children: React.ReactNode;
|
||||
params: Promise<{ orgId: string }>;
|
||||
}
|
||||
|
||||
export default async function SettingsLayout(props: SettingsLayoutProps) {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
const user = await verifySession();
|
||||
|
||||
if (!user) {
|
||||
redirect("/auth/login");
|
||||
}
|
||||
|
||||
const cookie = await authCookieHeader();
|
||||
|
||||
try {
|
||||
await internal.get<AxiosResponse<GetOrgResponse>>(
|
||||
`/org/${params.orgId}`,
|
||||
cookie
|
||||
);
|
||||
} catch {
|
||||
redirect(`/`);
|
||||
}
|
||||
|
||||
let orgs: ListOrgsResponse["orgs"] = [];
|
||||
try {
|
||||
const res = await internal.get<AxiosResponse<ListOrgsResponse>>(
|
||||
`/orgs`,
|
||||
cookie
|
||||
);
|
||||
if (res && res.data.data.orgs) {
|
||||
orgs = res.data.data.orgs;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error fetching orgs", e);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full bg-muted mb-6 select-none sm:px-0 px-3 pt-3">
|
||||
<div className="container mx-auto flex flex-col content-between gap-4 ">
|
||||
<Header
|
||||
email={user.email}
|
||||
orgName={params.orgId}
|
||||
orgs={orgs}
|
||||
/>
|
||||
<TopbarNav items={topNavItems} orgId={params.orgId} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="container mx-auto sm:px-0 px-3">{children}</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
12
src/app/[orgId]/settings/page.tsx
Normal file
12
src/app/[orgId]/settings/page.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
type OrgPageProps = {
|
||||
params: Promise<{ orgId: string }>;
|
||||
};
|
||||
|
||||
export default async function SettingsPage(props: OrgPageProps) {
|
||||
const params = await props.params;
|
||||
redirect(`/${params.orgId}/settings/sites`);
|
||||
|
||||
return <></>;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
51
src/app/[orgId]/settings/resources/[resourceId]/layout.tsx
Normal file
51
src/app/[orgId]/settings/resources/[resourceId]/layout.tsx
Normal 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
29
src/app/[orgId]/settings/resources/[resourceId]/page.tsx
Normal file
29
src/app/[orgId]/settings/resources/[resourceId]/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
272
src/app/[orgId]/settings/resources/[resourceId]/targets/page.tsx
Normal file
272
src/app/[orgId]/settings/resources/[resourceId]/targets/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getPaginationRowModel,
|
||||
SortingState,
|
||||
getSortedRowModel,
|
||||
ColumnFiltersState,
|
||||
getFilteredRowModel,
|
||||
} from "@tanstack/react-table";
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { DataTablePagination } from "@app/components/DataTablePagination";
|
||||
import { Plus } from "lucide-react";
|
||||
|
||||
interface ResourcesDataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[];
|
||||
data: TData[];
|
||||
addResource?: () => void;
|
||||
}
|
||||
|
||||
export function ResourcesDataTable<TData, TValue>({
|
||||
addResource,
|
||||
columns,
|
||||
data,
|
||||
}: ResourcesDataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
onSortingChange: setSorting,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
state: {
|
||||
sorting,
|
||||
columnFilters,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between pb-4">
|
||||
<Input
|
||||
placeholder="Search your resources"
|
||||
value={
|
||||
(table.getColumn("name")?.getFilterValue() as string) ??
|
||||
""
|
||||
}
|
||||
onChange={(event) =>
|
||||
table
|
||||
.getColumn("name")
|
||||
?.setFilterValue(event.target.value)
|
||||
}
|
||||
className="max-w-sm mr-2"
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (addResource) {
|
||||
addResource();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" /> Add Resource
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef
|
||||
.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={
|
||||
row.getIsSelected() && "selected"
|
||||
}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="h-24 text-center"
|
||||
>
|
||||
No resources. Create one to get started.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<DataTablePagination table={table} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
127
src/app/[orgId]/settings/resources/components/ResourcesTable.tsx
Normal file
127
src/app/[orgId]/settings/resources/components/ResourcesTable.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { ResourcesDataTable } from "./ResourcesDataTable";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@app/components/ui/dropdown-menu";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import api from "@app/api";
|
||||
|
||||
export type ResourceRow = {
|
||||
id: number;
|
||||
name: string;
|
||||
orgId: string;
|
||||
domain: string;
|
||||
site: string;
|
||||
};
|
||||
|
||||
export const columns: ColumnDef<ResourceRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
column.toggleSorting(column.getIsSorted() === "asc")
|
||||
}
|
||||
>
|
||||
Name
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "site",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
column.toggleSorting(column.getIsSorted() === "asc")
|
||||
}
|
||||
>
|
||||
Site
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "domain",
|
||||
header: "Domain",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => {
|
||||
const router = useRouter();
|
||||
|
||||
const resourceRow = row.original;
|
||||
|
||||
const deleteResource = (resourceId: number) => {
|
||||
api.delete(`/resource/${resourceId}`)
|
||||
.catch((e) => {
|
||||
console.error("Error deleting resource", e);
|
||||
})
|
||||
.then(() => {
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Open menu</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<Link
|
||||
href={`/${resourceRow.orgId}/settings/resources/${resourceRow.id}`}
|
||||
>
|
||||
View settings
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<button
|
||||
onClick={() => deleteResource(resourceRow.id)}
|
||||
className="text-red-600 hover:text-red-800 hover:underline cursor-pointer"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
type ResourcesTableProps = {
|
||||
resources: ResourceRow[];
|
||||
orgId: string;
|
||||
};
|
||||
|
||||
export default function SitesTable({ resources, orgId }: ResourcesTableProps) {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<ResourcesDataTable
|
||||
columns={columns}
|
||||
data={resources}
|
||||
addResource={() => {
|
||||
router.push(`/${orgId}/settings/resources/create`);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
48
src/app/[orgId]/settings/resources/page.tsx
Normal file
48
src/app/[orgId]/settings/resources/page.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { internal } from "@app/api";
|
||||
import { authCookieHeader } from "@app/api/cookies";
|
||||
import ResourcesTable, { ResourceRow } from "./components/ResourcesTable";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { ListResourcesResponse } from "@server/routers/resource";
|
||||
|
||||
type ResourcesPageProps = {
|
||||
params: Promise<{ orgId: string }>;
|
||||
};
|
||||
|
||||
export default async function ResourcesPage(props: ResourcesPageProps) {
|
||||
const params = await props.params;
|
||||
let resources: ListResourcesResponse["resources"] = [];
|
||||
try {
|
||||
const res = await internal.get<AxiosResponse<ListResourcesResponse>>(
|
||||
`/org/${params.orgId}/resources`,
|
||||
await authCookieHeader()
|
||||
);
|
||||
resources = res.data.data.resources;
|
||||
} catch (e) {
|
||||
console.error("Error fetching resources", e);
|
||||
}
|
||||
|
||||
const resourceRows: ResourceRow[] = resources.map((resource) => {
|
||||
return {
|
||||
id: resource.resourceId,
|
||||
name: resource.name,
|
||||
orgId: params.orgId,
|
||||
domain: resource.subdomain || "",
|
||||
site: resource.siteName || "None",
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-0.5 select-none mb-6">
|
||||
<h2 className="text-2xl font-bold tracking-tight">
|
||||
Manage Resources
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Create secure proxies to your private applications.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ResourcesTable resources={resourceRows} orgId={params.orgId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { SidebarNav } from "@app/components/sidebar-nav";
|
||||
import { useSiteContext } from "@app/hooks/useSiteContext";
|
||||
|
||||
const sidebarNavItems = [
|
||||
{
|
||||
title: "General",
|
||||
href: "/{orgId}/settings/sites/{niceId}",
|
||||
},
|
||||
];
|
||||
|
||||
export function ClientLayout({ isCreate, children }: { isCreate: boolean; children: React.ReactNode }) {
|
||||
const { site } = useSiteContext();
|
||||
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 Site"
|
||||
: site?.name + " Settings"}
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{isCreate
|
||||
? "Create a new site"
|
||||
: "Configure the settings on your site: " +
|
||||
site?.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>);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { ChevronDownIcon } 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, buttonVariants } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { generateKeypair } from "./wireguardConfig";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { api } from "@/api";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import { PickSiteDefaultsResponse } from "@server/routers/site";
|
||||
|
||||
const method = [
|
||||
{ label: "Wireguard", value: "wg" },
|
||||
{ label: "Newt", value: "newt" },
|
||||
] as const;
|
||||
|
||||
const accountFormSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(2, {
|
||||
message: "Name must be at least 2 characters.",
|
||||
})
|
||||
.max(30, {
|
||||
message: "Name must not be longer than 30 characters.",
|
||||
}),
|
||||
method: z.enum(["wg", "newt"]),
|
||||
});
|
||||
|
||||
type AccountFormValues = z.infer<typeof accountFormSchema>;
|
||||
|
||||
const defaultValues: Partial<AccountFormValues> = {
|
||||
name: "",
|
||||
method: "wg",
|
||||
};
|
||||
|
||||
export function CreateSiteForm() {
|
||||
const params = useParams();
|
||||
const orgId = params.orgId;
|
||||
const router = useRouter();
|
||||
|
||||
const [keypair, setKeypair] = useState<{
|
||||
publicKey: string;
|
||||
privateKey: string;
|
||||
} | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isChecked, setIsChecked] = useState(false);
|
||||
const [siteDefaults, setSiteDefaults] =
|
||||
useState<PickSiteDefaultsResponse | null>(null);
|
||||
|
||||
const handleCheckboxChange = (checked: boolean) => {
|
||||
setIsChecked(checked);
|
||||
};
|
||||
|
||||
const form = useForm<AccountFormValues>({
|
||||
resolver: zodResolver(accountFormSchema),
|
||||
defaultValues,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
const generatedKeypair = generateKeypair();
|
||||
setKeypair(generatedKeypair);
|
||||
setIsLoading(false);
|
||||
|
||||
api.get(`/org/${orgId}/pickSiteDefaults`)
|
||||
.catch((e) => {
|
||||
toast({
|
||||
title: "Error creating site...",
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
if (res && res.status === 200) {
|
||||
setSiteDefaults(res.data.data);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function onSubmit(data: AccountFormValues) {
|
||||
const res = await api
|
||||
.put(`/org/${orgId}/site/`, {
|
||||
name: data.name,
|
||||
subnet: siteDefaults?.subnet,
|
||||
exitNodeId: siteDefaults?.exitNodeId,
|
||||
pubKey: keypair?.publicKey,
|
||||
})
|
||||
.catch((e) => {
|
||||
toast({
|
||||
title: "Error creating site...",
|
||||
});
|
||||
});
|
||||
|
||||
if (res && res.status === 201) {
|
||||
const niceId = res.data.data.niceId;
|
||||
// navigate to the site page
|
||||
router.push(`/${orgId}/settings/sites/${niceId}`);
|
||||
}
|
||||
}
|
||||
|
||||
const wgConfig =
|
||||
keypair && siteDefaults
|
||||
? `[Interface]
|
||||
Address = ${siteDefaults.subnet}
|
||||
ListenPort = 51820
|
||||
PrivateKey = ${keypair.privateKey}
|
||||
|
||||
[Peer]
|
||||
PublicKey = ${siteDefaults.publicKey}
|
||||
AllowedIPs = ${siteDefaults.address.split("/")[0]}/32
|
||||
Endpoint = ${siteDefaults.endpoint}:${siteDefaults.listenPort}
|
||||
PersistentKeepalive = 5`
|
||||
: "";
|
||||
|
||||
const newtConfig = `curl -fsSL https://get.docker.com -o get-docker.sh
|
||||
sh get-docker.sh`;
|
||||
|
||||
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 site.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="method"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Method</FormLabel>
|
||||
<div className="relative w-max">
|
||||
<FormControl>
|
||||
<select
|
||||
className={cn(
|
||||
buttonVariants({
|
||||
variant: "outline",
|
||||
}),
|
||||
"w-[200px] appearance-none font-normal"
|
||||
)}
|
||||
{...field}
|
||||
>
|
||||
<option value="wg">
|
||||
WireGuard
|
||||
</option>
|
||||
<option value="newt">Newt</option>
|
||||
</select>
|
||||
</FormControl>
|
||||
<ChevronDownIcon className="absolute right-3 top-2.5 h-4 w-4 opacity-50" />
|
||||
</div>
|
||||
<FormDescription>
|
||||
This is how you will connect your site to
|
||||
Fossorial.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{form.watch("method") === "wg" && !isLoading ? (
|
||||
<pre className="mt-2 w-full rounded-md bg-muted p-4 overflow-x-auto">
|
||||
<code className="whitespace-pre-wrap font-mono">
|
||||
{wgConfig}
|
||||
</code>
|
||||
</pre>
|
||||
) : form.watch("method") === "wg" && isLoading ? (
|
||||
<p>Loading WireGuard configuration...</p>
|
||||
) : (
|
||||
<pre className="mt-2 w-full rounded-md bg-muted p-4 overflow-x-auto">
|
||||
<code className="whitespace-pre-wrap">
|
||||
{newtConfig}
|
||||
</code>
|
||||
</pre>
|
||||
)}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="terms"
|
||||
checked={isChecked}
|
||||
onCheckedChange={handleCheckboxChange}
|
||||
/>
|
||||
<label
|
||||
htmlFor="terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
I have copied the config
|
||||
</label>
|
||||
</div>
|
||||
<Button type="submit" disabled={!isChecked}>
|
||||
Create Site
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
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 { useSiteContext } from "@app/hooks/useSiteContext";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
const GeneralFormSchema = z.object({
|
||||
name: z.string(),
|
||||
});
|
||||
|
||||
type GeneralFormValues = z.infer<typeof GeneralFormSchema>;
|
||||
|
||||
export function GeneralForm() {
|
||||
const { site, updateSite } = useSiteContext();
|
||||
|
||||
const form = useForm<GeneralFormValues>({
|
||||
resolver: zodResolver(GeneralFormSchema),
|
||||
defaultValues: {
|
||||
name: site?.name,
|
||||
},
|
||||
mode: "onChange",
|
||||
});
|
||||
|
||||
async function onSubmit(data: GeneralFormValues) {
|
||||
await updateSite({ name: data.name });
|
||||
}
|
||||
|
||||
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 site.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit">Update Site</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
export function NewtConfig() {
|
||||
const config = `curl -fsSL https://get.docker.com -o get-docker.sh
|
||||
sh get-docker.sh`;
|
||||
|
||||
return (
|
||||
<pre className="mt-2 w-full rounded-md bg-slate-950 p-4 overflow-x-auto">
|
||||
<code className="text-white whitespace-pre-wrap">{config}</code>
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/*! SPDX-License-Identifier: GPL-2.0
|
||||
*
|
||||
* Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
|
||||
*/
|
||||
|
||||
function gf(init: number[] | undefined = undefined) {
|
||||
var r = new Float64Array(16);
|
||||
if (init) {
|
||||
for (var i = 0; i < init.length; ++i)
|
||||
r[i] = init[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
function pack(o: Uint8Array, n: Float64Array) {
|
||||
var b, m = gf(), t = gf();
|
||||
for (var i = 0; i < 16; ++i)
|
||||
t[i] = n[i];
|
||||
carry(t);
|
||||
carry(t);
|
||||
carry(t);
|
||||
for (var j = 0; j < 2; ++j) {
|
||||
m[0] = t[0] - 0xffed;
|
||||
for (var i = 1; i < 15; ++i) {
|
||||
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
|
||||
m[i - 1] &= 0xffff;
|
||||
}
|
||||
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
|
||||
b = (m[15] >> 16) & 1;
|
||||
m[14] &= 0xffff;
|
||||
cswap(t, m, 1 - b);
|
||||
}
|
||||
for (var i = 0; i < 16; ++i) {
|
||||
o[2 * i] = t[i] & 0xff;
|
||||
o[2 * i + 1] = t[i] >> 8;
|
||||
}
|
||||
}
|
||||
|
||||
function carry(o: Float64Array) {
|
||||
var c;
|
||||
for (var i = 0; i < 16; ++i) {
|
||||
o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
|
||||
o[i] &= 0xffff;
|
||||
}
|
||||
}
|
||||
|
||||
function cswap(p: Float64Array, q: Float64Array, b: number) {
|
||||
var t, c = ~(b - 1);
|
||||
for (var i = 0; i < 16; ++i) {
|
||||
t = c & (p[i] ^ q[i]);
|
||||
p[i] ^= t;
|
||||
q[i] ^= t;
|
||||
}
|
||||
}
|
||||
|
||||
function add(o: Float64Array, a: Float64Array, b: Float64Array) {
|
||||
for (var i = 0; i < 16; ++i)
|
||||
o[i] = (a[i] + b[i]) | 0;
|
||||
}
|
||||
|
||||
function subtract(o: Float64Array, a: Float64Array, b: Float64Array) {
|
||||
for (var i = 0; i < 16; ++i)
|
||||
o[i] = (a[i] - b[i]) | 0;
|
||||
}
|
||||
|
||||
function multmod(o: Float64Array, a: Float64Array, b: Float64Array) {
|
||||
var t = new Float64Array(31);
|
||||
for (var i = 0; i < 16; ++i) {
|
||||
for (var j = 0; j < 16; ++j)
|
||||
t[i + j] += a[i] * b[j];
|
||||
}
|
||||
for (var i = 0; i < 15; ++i)
|
||||
t[i] += 38 * t[i + 16];
|
||||
for (var i = 0; i < 16; ++i)
|
||||
o[i] = t[i];
|
||||
carry(o);
|
||||
carry(o);
|
||||
}
|
||||
|
||||
function invert(o: Float64Array, i: Float64Array) {
|
||||
var c = gf();
|
||||
for (var a = 0; a < 16; ++a)
|
||||
c[a] = i[a];
|
||||
for (var a = 253; a >= 0; --a) {
|
||||
multmod(c, c, c);
|
||||
if (a !== 2 && a !== 4)
|
||||
multmod(c, c, i);
|
||||
}
|
||||
for (var a = 0; a < 16; ++a)
|
||||
o[a] = c[a];
|
||||
}
|
||||
|
||||
function clamp(z: Uint8Array) {
|
||||
z[31] = (z[31] & 127) | 64;
|
||||
z[0] &= 248;
|
||||
}
|
||||
|
||||
function generatePublicKey(privateKey: Uint8Array) {
|
||||
var r, z = new Uint8Array(32);
|
||||
var a = gf([1]),
|
||||
b = gf([9]),
|
||||
c = gf(),
|
||||
d = gf([1]),
|
||||
e = gf(),
|
||||
f = gf(),
|
||||
_121665 = gf([0xdb41, 1]),
|
||||
_9 = gf([9]);
|
||||
for (var i = 0; i < 32; ++i)
|
||||
z[i] = privateKey[i];
|
||||
clamp(z);
|
||||
for (var i = 254; i >= 0; --i) {
|
||||
r = (z[i >>> 3] >>> (i & 7)) & 1;
|
||||
cswap(a, b, r);
|
||||
cswap(c, d, r);
|
||||
add(e, a, c);
|
||||
subtract(a, a, c);
|
||||
add(c, b, d);
|
||||
subtract(b, b, d);
|
||||
multmod(d, e, e);
|
||||
multmod(f, a, a);
|
||||
multmod(a, c, a);
|
||||
multmod(c, b, e);
|
||||
add(e, a, c);
|
||||
subtract(a, a, c);
|
||||
multmod(b, a, a);
|
||||
subtract(c, d, f);
|
||||
multmod(a, c, _121665);
|
||||
add(a, a, d);
|
||||
multmod(c, c, a);
|
||||
multmod(a, d, f);
|
||||
multmod(d, b, _9);
|
||||
multmod(b, e, e);
|
||||
cswap(a, b, r);
|
||||
cswap(c, d, r);
|
||||
}
|
||||
invert(c, c);
|
||||
multmod(a, a, c);
|
||||
pack(z, a);
|
||||
return z;
|
||||
}
|
||||
|
||||
function generatePresharedKey() {
|
||||
var privateKey = new Uint8Array(32);
|
||||
crypto.getRandomValues(privateKey);
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
function generatePrivateKey() {
|
||||
var privateKey = generatePresharedKey();
|
||||
clamp(privateKey);
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
function encodeBase64(dest: Uint8Array, src: Uint8Array) {
|
||||
var input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]);
|
||||
for (var i = 0; i < 4; ++i)
|
||||
dest[i] = input[i] + 65 +
|
||||
(((25 - input[i]) >> 8) & 6) -
|
||||
(((51 - input[i]) >> 8) & 75) -
|
||||
(((61 - input[i]) >> 8) & 15) +
|
||||
(((62 - input[i]) >> 8) & 3);
|
||||
}
|
||||
|
||||
function keyToBase64(key: Uint8Array) {
|
||||
var i, base64 = new Uint8Array(44);
|
||||
for (i = 0; i < 32 / 3; ++i)
|
||||
encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
|
||||
encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
|
||||
base64[43] = 61;
|
||||
return String.fromCharCode.apply(null, base64 as any);
|
||||
}
|
||||
|
||||
export function generateKeypair() {
|
||||
var privateKey = generatePrivateKey();
|
||||
var publicKey = generatePublicKey(privateKey);
|
||||
return {
|
||||
publicKey: keyToBase64(publicKey),
|
||||
privateKey: keyToBase64(privateKey)
|
||||
};
|
||||
}
|
||||
50
src/app/[orgId]/settings/sites/[niceId]/layout.tsx
Normal file
50
src/app/[orgId]/settings/sites/[niceId]/layout.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import SiteProvider from "@app/providers/SiteProvider";
|
||||
import { internal } from "@app/api";
|
||||
import { GetSiteResponse } from "@server/routers/site";
|
||||
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 SettingsLayoutProps {
|
||||
children: React.ReactNode;
|
||||
params: Promise<{ niceId: string; orgId: string }>;
|
||||
}
|
||||
|
||||
export default async function SettingsLayout(props: SettingsLayoutProps) {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
let site = null;
|
||||
|
||||
if (params.niceId !== "create") {
|
||||
try {
|
||||
const res = await internal.get<AxiosResponse<GetSiteResponse>>(
|
||||
`/org/${params.orgId}/site/${params.niceId}`,
|
||||
await authCookieHeader()
|
||||
);
|
||||
site = res.data.data;
|
||||
} catch {
|
||||
redirect(`/${params.orgId}/settings/sites`);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<Link
|
||||
href={`/${params.orgId}/settings/sites`}
|
||||
className="text-primary font-medium"
|
||||
></Link>
|
||||
</div>
|
||||
|
||||
<SiteProvider site={site}>
|
||||
<ClientLayout isCreate={params.niceId === "create"}>
|
||||
{children}
|
||||
</ClientLayout>
|
||||
</SiteProvider>
|
||||
</>
|
||||
);
|
||||
}
|
||||
29
src/app/[orgId]/settings/sites/[niceId]/page.tsx
Normal file
29
src/app/[orgId]/settings/sites/[niceId]/page.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import React from "react";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { CreateSiteForm } from "./components/CreateSite";
|
||||
import { GeneralForm } from "./components/GeneralForm";
|
||||
|
||||
export default async function SitePage(props: {
|
||||
params: Promise<{ niceId: string }>;
|
||||
}) {
|
||||
const params = await props.params;
|
||||
const isCreate = params.niceId === "create";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">
|
||||
{isCreate ? "Create Site" : "General"}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isCreate
|
||||
? "Create a new site"
|
||||
: "Edit basic site settings"}
|
||||
</p>
|
||||
</div>
|
||||
<Separator />
|
||||
|
||||
{isCreate ? <CreateSiteForm /> : <GeneralForm />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
142
src/app/[orgId]/settings/sites/components/SitesDataTable.tsx
Normal file
142
src/app/[orgId]/settings/sites/components/SitesDataTable.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getPaginationRowModel,
|
||||
SortingState,
|
||||
getSortedRowModel,
|
||||
ColumnFiltersState,
|
||||
getFilteredRowModel,
|
||||
} from "@tanstack/react-table";
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { DataTablePagination } from "../../../../../components/DataTablePagination";
|
||||
import { Plus } from "lucide-react";
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[];
|
||||
data: TData[];
|
||||
addSite?: () => void;
|
||||
}
|
||||
|
||||
export function SitesDataTable<TData, TValue>({
|
||||
addSite,
|
||||
columns,
|
||||
data,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
onSortingChange: setSorting,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
state: {
|
||||
sorting,
|
||||
columnFilters,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between pb-4">
|
||||
<Input
|
||||
placeholder="Search your sites"
|
||||
value={
|
||||
(table.getColumn("name")?.getFilterValue() as string) ??
|
||||
""
|
||||
}
|
||||
onChange={(event) =>
|
||||
table
|
||||
.getColumn("name")
|
||||
?.setFilterValue(event.target.value)
|
||||
}
|
||||
className="max-w-sm mr-2"
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (addSite) {
|
||||
addSite();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" /> Add Site
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef
|
||||
.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={
|
||||
row.getIsSelected() && "selected"
|
||||
}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext(),
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="h-24 text-center"
|
||||
>
|
||||
No sites. Create one to get started.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<DataTablePagination table={table} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
127
src/app/[orgId]/settings/sites/components/SitesTable.tsx
Normal file
127
src/app/[orgId]/settings/sites/components/SitesTable.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { SitesDataTable } from "./SitesDataTable";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@app/components/ui/dropdown-menu";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import api from "@app/api";
|
||||
|
||||
export type SiteRow = {
|
||||
id: number;
|
||||
nice: string;
|
||||
name: string;
|
||||
mbIn: number;
|
||||
mbOut: number;
|
||||
orgId: string;
|
||||
};
|
||||
|
||||
export const columns: ColumnDef<SiteRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
column.toggleSorting(column.getIsSorted() === "asc")
|
||||
}
|
||||
>
|
||||
Name
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "nice",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
column.toggleSorting(column.getIsSorted() === "asc")
|
||||
}
|
||||
>
|
||||
Site
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "mbIn",
|
||||
header: "MB In",
|
||||
},
|
||||
{
|
||||
accessorKey: "mbOut",
|
||||
header: "MB Out",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => {
|
||||
const router = useRouter();
|
||||
|
||||
const siteRow = row.original;
|
||||
|
||||
const deleteSite = (siteId: number) => {
|
||||
api.delete(`/site/${siteId}`)
|
||||
.catch((e) => {
|
||||
console.error("Error deleting site", e);
|
||||
})
|
||||
.then(() => {
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Open menu</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<Link
|
||||
href={`/${siteRow.orgId}/settings/sites/${siteRow.id}`}
|
||||
>
|
||||
View settings
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<button onClick={() => deleteSite(siteRow.id)} className="text-red-600 hover:text-red-800 hover:underline cursor-pointer">Delete</button>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
type SitesTableProps = {
|
||||
sites: SiteRow[];
|
||||
orgId: string;
|
||||
};
|
||||
|
||||
export default function SitesTable({ sites, orgId }: SitesTableProps) {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<SitesDataTable
|
||||
columns={columns}
|
||||
data={sites}
|
||||
addSite={() => {
|
||||
router.push(`/${orgId}/settings/sites/create`);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
49
src/app/[orgId]/settings/sites/page.tsx
Normal file
49
src/app/[orgId]/settings/sites/page.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { internal } from "@app/api";
|
||||
import { authCookieHeader } from "@app/api/cookies";
|
||||
import { ListSitesResponse } from "@server/routers/site";
|
||||
import { AxiosResponse } from "axios";
|
||||
import SitesTable, { SiteRow } from "./components/SitesTable";
|
||||
|
||||
type SitesPageProps = {
|
||||
params: Promise<{ orgId: string }>;
|
||||
};
|
||||
|
||||
export default async function SitesPage(props: SitesPageProps) {
|
||||
const params = await props.params;
|
||||
let sites: ListSitesResponse["sites"] = [];
|
||||
try {
|
||||
const res = await internal.get<AxiosResponse<ListSitesResponse>>(
|
||||
`/org/${params.orgId}/sites`,
|
||||
await authCookieHeader()
|
||||
);
|
||||
sites = res.data.data.sites;
|
||||
} catch (e) {
|
||||
console.error("Error fetching sites", e);
|
||||
}
|
||||
|
||||
const siteRows: SiteRow[] = sites.map((site) => {
|
||||
return {
|
||||
name: site.name,
|
||||
id: site.siteId,
|
||||
nice: site.niceId.toString(),
|
||||
mbIn: site.megabytesIn || 0,
|
||||
mbOut: site.megabytesOut || 0,
|
||||
orgId: params.orgId,
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-0.5 select-none mb-6">
|
||||
<h2 className="text-2xl font-bold tracking-tight">
|
||||
Manage Sites
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Manage your existing sites here or create a new one.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<SitesTable sites={siteRows} orgId={params.orgId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user