This commit is contained in:
Milo Schwartz 2024-10-14 23:10:08 -04:00
commit 84e118d1fa
No known key found for this signature in database
17 changed files with 1849 additions and 441 deletions

11
bruno/Sites/Get Site.bru Normal file
View file

@ -0,0 +1,11 @@
meta {
name: Get Site
type: http
seq: 2
}
get {
url: http://localhost:3000/api/v1/org/theorg/sites/mexican-mole-lizard-windy
body: none
auth: none
}

File diff suppressed because it is too large Load diff

37
server/db/names.ts Normal file
View file

@ -0,0 +1,37 @@
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { readFileSync } from 'fs';
import { db } from '@server/db';
import { sites } from './schema';
import { eq, and } from 'drizzle-orm';
// Get the directory name of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load the names from the names.json file
const file = join(__dirname, 'names.json');
export const names = JSON.parse(readFileSync(file, 'utf-8'));
export async function getUniqueName(orgId: string): Promise<string> {
let loops = 0;
while (true) {
if (loops > 100) {
throw new Error('Could not generate a unique name');
}
const name = generateName();
const count = await db.select({ niceId: sites.niceId, orgId: sites.orgId }).from(sites).where(and(eq(sites.niceId, name), eq(sites.orgId, orgId)));
if (count.length === 0) {
return name;
}
loops++;
}
}
export function generateName(): string {
return (
names.descriptors[Math.floor(Math.random() * names.descriptors.length)] + "-" +
names.animals[Math.floor(Math.random() * names.animals.length)]
).toLowerCase().replace(/\s/g, '-');
}

View file

@ -12,6 +12,7 @@ export const sites = sqliteTable("sites", {
orgId: text("orgId").references(() => orgs.orgId, { orgId: text("orgId").references(() => orgs.orgId, {
onDelete: "cascade", onDelete: "cascade",
}), }),
niceId: text("niceId"),
exitNode: integer("exitNode").references(() => exitNodes.exitNodeId, { exitNode: integer("exitNode").references(() => exitNodes.exitNodeId, {
onDelete: "set null", onDelete: "set null",
}), }),

View file

@ -44,10 +44,12 @@ authenticated.delete("/org/:orgId", verifyOrgAccess, org.deleteOrg);
authenticated.put("/org/:orgId/site", verifyOrgAccess, site.createSite); authenticated.put("/org/:orgId/site", verifyOrgAccess, site.createSite);
authenticated.get("/org/:orgId/sites", verifyOrgAccess, site.listSites); authenticated.get("/org/:orgId/sites", verifyOrgAccess, site.listSites);
authenticated.get("/site/:siteId", verifySiteAccess, site.getSite); authenticated.get("/org/:orgId/site/:niceId", verifyOrgAccess, site.getSite);
authenticated.get("/site/:siteId/roles", verifySiteAccess, site.listSiteRoles);
authenticated.post("/site/:siteId", verifySiteAccess, site.updateSite); authenticated.get("/site/siteId/:siteId", verifySiteAccess, site.getSite);
authenticated.delete("/site/:siteId", verifySiteAccess, site.deleteSite); authenticated.get("/site/siteId/:siteId/roles", verifySiteAccess, site.listSiteRoles);
authenticated.post("/site/siteId/:siteId", verifySiteAccess, site.updateSite);
authenticated.delete("/site/siteId/:siteId", verifySiteAccess, site.deleteSite);
authenticated.put( authenticated.put(
"/org/:orgId/site/:siteId/resource", "/org/:orgId/site/:siteId/resource",

View file

@ -9,6 +9,7 @@ import fetch from 'node-fetch';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions'; import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger'; import logger from '@server/logger';
import { eq, and } from 'drizzle-orm'; import { eq, and } from 'drizzle-orm';
import { getUniqueName } from '@server/db/names';
const API_BASE_URL = "http://localhost:3000"; const API_BASE_URL = "http://localhost:3000";
@ -24,6 +25,16 @@ const createSiteSchema = z.object({
subnet: z.string().optional(), subnet: z.string().optional(),
}); });
export type GetSiteResponse = {
name: string;
siteId: number;
orgId: string;
niceId: string;
// niceId: string;
// subdomain: string;
// subnet: string;
};
export async function createSite(req: Request, res: Response, next: NextFunction): Promise<any> { export async function createSite(req: Request, res: Response, next: NextFunction): Promise<any> {
try { try {
// Validate request body // Validate request body
@ -62,11 +73,15 @@ export async function createSite(req: Request, res: Response, next: NextFunction
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have a role')); return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have a role'));
} }
const niceId = await getUniqueName(orgId);
// TODO: pick a subnet
// Create new site in the database // Create new site in the database
const newSite = await db.insert(sites).values({ const [newSite] = await db.insert(sites).values({
orgId, orgId,
name, name,
subdomain, niceId,
pubKey, pubKey,
subnet, subnet,
}).returning(); }).returning();
@ -87,26 +102,33 @@ export async function createSite(req: Request, res: Response, next: NextFunction
await db.insert(roleSites).values({ await db.insert(roleSites).values({
roleId: superuserRole[0].roleId, roleId: superuserRole[0].roleId,
siteId: newSite[0].siteId, siteId: newSite.siteId,
}); });
if (req.userOrgRoleId != superuserRole[0].roleId) { if (req.userOrgRoleId != superuserRole[0].roleId) {
// make sure the user can access the site // make sure the user can access the site
db.insert(userSites).values({ db.insert(userSites).values({
userId: req.user?.userId!, userId: req.user?.userId!,
siteId: newSite[0].siteId, siteId: newSite.siteId,
}); });
} }
return response(res, { return response(res, {
data: newSite[0], data: {
name: newSite.name,
niceId: newSite.niceId,
siteId: newSite.siteId,
orgId: newSite.orgId,
// subdomain: newSite.subdomain,
// subnet: newSite.subnet,
},
success: true, success: true,
error: false, error: false,
message: "Site created successfully", message: "Site created successfully",
status: HttpCode.CREATED, status: HttpCode.CREATED,
}); });
} catch (error) { } catch (error) {
logger.error(error); throw error;
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred...")); return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
} }
} }

View file

@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from 'express';
import { z } from 'zod'; import { z } from 'zod';
import { db } from '@server/db'; import { db } from '@server/db';
import { sites } from '@server/db/schema'; import { sites } from '@server/db/schema';
import { eq } from 'drizzle-orm'; import { eq, and } from 'drizzle-orm';
import response from "@server/utils/response"; import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode'; import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors'; import createHttpError from 'http-errors';
@ -11,7 +11,9 @@ import logger from '@server/logger';
// Define Zod schema for request parameters validation // Define Zod schema for request parameters validation
const getSiteSchema = z.object({ const getSiteSchema = z.object({
siteId: z.string().transform(Number).pipe(z.number().int().positive()) siteId: z.string().transform(Number).pipe(z.number().int().positive()).optional(),
niceId: z.string().optional(),
orgId: z.string().optional(),
}); });
export type GetSiteResponse = { export type GetSiteResponse = {
@ -34,7 +36,7 @@ export async function getSite(req: Request, res: Response, next: NextFunction):
); );
} }
const { siteId } = parsedParams.data; const { siteId, niceId, orgId } = parsedParams.data;
// Check if the user has permission to list sites // Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.updateSite, req); const hasPermission = await checkUserActionPermission(ActionsEnum.updateSite, req);
@ -42,11 +44,23 @@ export async function getSite(req: Request, res: Response, next: NextFunction):
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action')); return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
} }
let site;
// Fetch the site from the database // Fetch the site from the database
const site = await db.select() if (siteId) {
.from(sites) site = await db.select()
.where(eq(sites.siteId, siteId)) .from(sites)
.limit(1); .where(eq(sites.siteId, siteId))
.limit(1);
} else if (niceId && orgId) {
site = await db.select()
.from(sites)
.where(and(eq(sites.niceId, niceId), eq(sites.orgId, orgId)))
.limit(1);
}
if (!site) {
return next(createHttpError(HttpCode.NOT_FOUND, 'Site not found'));
}
if (site.length === 0) { if (site.length === 0) {
return next( return next(
@ -60,8 +74,8 @@ export async function getSite(req: Request, res: Response, next: NextFunction):
return response(res, { return response(res, {
data: { data: {
siteId: site[0].siteId, siteId: site[0].siteId,
niceId: site[0].niceId,
name: site[0].name, name: site[0].name,
subdomain: site[0].subdomain,
subnet: site[0].subnet, subnet: site[0].subnet,
}, },
success: true, success: true,
@ -70,7 +84,7 @@ export async function getSite(req: Request, res: Response, next: NextFunction):
status: HttpCode.OK, status: HttpCode.OK,
}); });
} catch (error) { } catch (error) {
logger.error(error); logger.error("Error from getSite: ", error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred...")); return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
} }
} }

View file

@ -32,6 +32,7 @@ function querySites(orgId: string, accessibleSiteIds: number[]) {
return db return db
.select({ .select({
siteId: sites.siteId, siteId: sites.siteId,
niceId: sites.niceId,
name: sites.name, name: sites.name,
pubKey: sites.pubKey, pubKey: sites.pubKey,
subnet: sites.subnet, subnet: sites.subnet,

View file

@ -8,14 +8,6 @@ import { z } from "zod"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { toast } from "@/hooks/use-toast" import { toast } from "@/hooks/use-toast"
import { Button, buttonVariants } from "@/components/ui/button" import { Button, buttonVariants } from "@/components/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import { import {
Form, Form,
FormControl, FormControl,
@ -26,15 +18,9 @@ import {
FormMessage, FormMessage,
} from "@/components/ui/form" } from "@/components/ui/form"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { generateKeypair } from "./wireguard-config"; import { generateKeypair } from "./wireguard-config";
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { api } from "@/api"; import { api } from "@/api";
import { AxiosResponse } from "axios"
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Checkbox } from "@app/components/ui/checkbox" import { Checkbox } from "@app/components/ui/checkbox"
@ -53,16 +39,6 @@ const accountFormSchema = z.object({
.max(30, { .max(30, {
message: "Name must not be longer than 30 characters.", message: "Name must not be longer than 30 characters.",
}), }),
subdomain: z
.string()
// cant be too long and cant have spaces or special characters
.regex(/^[a-zA-Z0-9-]+$/)
.min(2, {
message: "Subdomain must be at least 2 characters.",
})
.max(30, {
message: "Subdomain must not be longer than 30 characters.",
}),
method: z.enum(["wg", "newt"]), method: z.enum(["wg", "newt"]),
}); });
@ -99,17 +75,11 @@ export function CreateSiteForm() {
} }
}, []); }, []);
const name = form.watch("name");
useEffect(() => {
const subdomain = name.toLowerCase().replace(/\s+/g, "-");
form.setValue("subdomain", subdomain, { shouldValidate: true });
}, [name, form]);
async function onSubmit(data: AccountFormValues) { async function onSubmit(data: AccountFormValues) {
const res = await api const res = await api
.put(`/org/${orgId}/site/`, { .put(`/org/${orgId}/site/`, {
name: data.name, name: data.name,
subdomain: data.subdomain, // subdomain: data.subdomain,
pubKey: keypair?.publicKey, pubKey: keypair?.publicKey,
}) })
.catch((e) => { .catch((e) => {
@ -119,9 +89,9 @@ export function CreateSiteForm() {
}); });
if (res && res.status === 201) { if (res && res.status === 201) {
const siteId = res.data.data.siteId; const niceId = res.data.data.niceId;
// navigate to the site page // navigate to the site page
router.push(`/${orgId}/sites/${siteId}`); router.push(`/${orgId}/sites/${niceId}`);
} }
} }
@ -161,7 +131,7 @@ sh get-docker.sh`;
</FormItem> </FormItem>
)} )}
/> />
<FormField {/* <FormField
control={form.control} control={form.control}
name="subdomain" name="subdomain"
render={({ field }) => ( render={({ field }) => (
@ -176,7 +146,7 @@ sh get-docker.sh`;
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> /> */}
<FormField <FormField
control={form.control} control={form.control}
name="method" name="method"

View file

@ -20,25 +20,25 @@ export const metadata: Metadata = {
const sidebarNavItems = [ const sidebarNavItems = [
{ {
title: "Profile", title: "Profile",
href: "/{orgId}/sites/{siteId}", href: "/{orgId}/sites/{niceId}",
}, },
{ {
title: "Appearance", title: "Appearance",
href: "/{orgId}/sites/{siteId}/appearance", href: "/{orgId}/sites/{niceId}/appearance",
}, },
{ {
title: "Notifications", title: "Notifications",
href: "/{orgId}/sites/{siteId}/notifications", href: "/{orgId}/sites/{niceId}/notifications",
}, },
{ {
title: "Display", title: "Display",
href: "/{orgId}/sites/{siteId}/display", href: "/{orgId}/sites/{niceId}/display",
}, },
]; ];
interface SettingsLayoutProps { interface SettingsLayoutProps {
children: React.ReactNode; children: React.ReactNode;
params: { siteId: string; orgId: string }; params: { niceId: string; orgId: string };
} }
export default async function SettingsLayout({ export default async function SettingsLayout({
@ -46,10 +46,10 @@ export default async function SettingsLayout({
params, params,
}: SettingsLayoutProps) { }: SettingsLayoutProps) {
let site = null; let site = null;
if (params.siteId !== "create") { if (params.niceId !== "create") {
try { try {
const res = await internal.get<AxiosResponse<GetSiteResponse>>( const res = await internal.get<AxiosResponse<GetSiteResponse>>(
`/site/${params.siteId}`, `/org/${params.orgId}/site/${params.niceId}`,
authCookieHeader(), authCookieHeader(),
); );
site = res.data.data; site = res.data.data;
@ -78,27 +78,26 @@ export default async function SettingsLayout({
</div> </div>
<div className="mb-4"> <div className="mb-4">
<Link <Link
href={`/${params.orgId}/sites`} href={`/${params.orgId}/sites`}
className="text-primary font-medium" className="text-primary font-medium"
> >
<div className="flex items-center gap-0.5 hover:underline"> <div className="flex items-center gap-0.5 hover:underline">
<ChevronLeft /> <ChevronLeft />
<span>View all sites</span> <span>View all sites</span>
</div> </div>
</Link> </Link>
</div> </div>
<div className="hidden space-y-6 0 pb-16 md:block"> <div className="hidden space-y-6 0 pb-16 md:block">
<div className="space-y-0.5"> <div className="space-y-0.5">
<h2 className="text-2xl font-bold tracking-tight"> <h2 className="text-2xl font-bold tracking-tight">
{params.siteId == "create" {params.niceId == "create"
? "New Site" ? "New Site"
: site?.name + " Settings" || "Site Settings" : site?.name + " Settings" || "Site Settings"}
}
</h2> </h2>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
{params.siteId == "create" {params.niceId == "create"
? "Create a new site" ? "Create a new site"
: "Configure the settings on your site: " + : "Configure the settings on your site: " +
site?.name || ""} site?.name || ""}
@ -109,7 +108,7 @@ export default async function SettingsLayout({
<aside className="-mx-4 lg:w-1/5"> <aside className="-mx-4 lg:w-1/5">
<SidebarNav <SidebarNav
items={sidebarNavItems} items={sidebarNavItems}
disabled={params.siteId == "create"} disabled={params.niceId == "create"}
/> />
</aside> </aside>
<div className="flex-1 lg:max-w-2xl"> <div className="flex-1 lg:max-w-2xl">

View file

@ -6,9 +6,9 @@ import { CreateSiteForm } from "./components/create-site";
export default function SettingsProfilePage({ export default function SettingsProfilePage({
params, params,
}: { }: {
params: { siteId: string }; params: { niceId: string };
}) { }) {
const isCreateForm = params.siteId === "create"; const isCreateForm = params.niceId === "create";
return ( return (
<div className="space-y-6"> <div className="space-y-6">

View file

@ -17,7 +17,7 @@ export function SidebarNav({ className, items, disabled = false, ...props }: Sid
const pathname = usePathname(); const pathname = usePathname();
const params = useParams(); const params = useParams();
const orgId = params.orgId as string; const orgId = params.orgId as string;
const siteId = params.siteId as string; const niceId = params.niceId as string;
const resourceId = params.resourceId as string; const resourceId = params.resourceId as string;
return ( return (
@ -31,11 +31,11 @@ export function SidebarNav({ className, items, disabled = false, ...props }: Sid
> >
{items.map((item) => ( {items.map((item) => (
<Link <Link
key={item.href.replace("{orgId}", orgId).replace("{siteId}", siteId).replace("{resourceId}", resourceId)} key={item.href.replace("{orgId}", orgId).replace("{niceId}", niceId).replace("{resourceId}", resourceId)}
href={item.href.replace("{orgId}", orgId).replace("{siteId}", siteId).replace("{resourceId}", resourceId)} href={item.href.replace("{orgId}", orgId).replace("{niceId}", niceId).replace("{resourceId}", resourceId)}
className={cn( className={cn(
buttonVariants({ variant: "ghost" }), buttonVariants({ variant: "ghost" }),
pathname === item.href.replace("{orgId}", orgId).replace("{siteId}", siteId).replace("{resourceId}", resourceId) pathname === item.href.replace("{orgId}", orgId).replace("{niceId}", niceId).replace("{resourceId}", resourceId)
? "bg-muted hover:bg-muted" ? "bg-muted hover:bg-muted"
: "hover:bg-transparent hover:underline", : "hover:bg-transparent hover:underline",
"justify-start", "justify-start",