migrate src/actions.ts to withAuthV2

This commit is contained in:
bkellam 2025-09-22 16:57:58 -07:00
parent 66c9ec044e
commit 6abe7a40a5
7 changed files with 560 additions and 720 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,138 +0,0 @@
'use client';
import { updateOrgDomain } from "@/actions";
import { useToast } from "@/components/hooks/use-toast";
import { AlertDialog, AlertDialogFooter, AlertDialogHeader, AlertDialogContent, AlertDialogAction, AlertDialogCancel, AlertDialogDescription, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { useDomain } from "@/hooks/useDomain";
import { orgDomainSchema } from "@/lib/schemas";
import { isServiceError } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { OrgRole } from "@sourcebot/db";
import { Loader2, TriangleAlert } from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
const formSchema = z.object({
domain: orgDomainSchema,
})
interface ChangeOrgDomainCardProps {
currentUserRole: OrgRole,
orgDomain: string,
rootDomain: string,
}
export function ChangeOrgDomainCard({ orgDomain, currentUserRole, rootDomain }: ChangeOrgDomainCardProps) {
const domain = useDomain()
const { toast } = useToast()
const captureEvent = useCaptureEvent();
const router = useRouter();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
domain: orgDomain,
},
})
const { isSubmitting } = form.formState;
const onSubmit = useCallback(async (data: z.infer<typeof formSchema>) => {
const result = await updateOrgDomain(data.domain, domain);
if (isServiceError(result)) {
toast({
description: `❌ Failed to update organization url. Reason: ${result.message}`,
})
captureEvent('wa_org_domain_updated_fail', {
error: result.errorCode,
});
} else {
toast({
description: "✅ Organization url updated successfully",
});
captureEvent('wa_org_domain_updated_success', {});
router.replace(`/${data.domain}/settings`);
}
}, [domain, router, toast, captureEvent]);
return (
<>
<Card className="w-full">
<CardHeader className="flex flex-col gap-4">
<CardTitle className="flex items-center gap-2">
Organization URL
</CardTitle>
<CardDescription>{`Your organization's URL namespace. This is where your organization's Sourcebot instance will be accessible.`}</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="domain"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="flex items-center w-full">
<div className="flex-shrink-0 text-sm text-muted-foreground bg-backgroundSecondary rounded-md rounded-r-none border border-r-0 px-3 py-[9px]">{rootDomain}/</div>
<Input
placeholder={orgDomain}
{...field}
disabled={currentUserRole !== OrgRole.OWNER}
title={currentUserRole !== OrgRole.OWNER ? "Only organization owners can change the organization url" : undefined}
className="flex-1 rounded-l-none max-w-xs"
/>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end">
<AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<AlertDialogTrigger asChild>
<Button
disabled={isSubmitting || currentUserRole !== OrgRole.OWNER}
title={currentUserRole !== OrgRole.OWNER ? "Only organization owners can change the organization url" : undefined}
>
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2"><TriangleAlert className="h-4 w-4 text-destructive" /> Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
Any links pointing to the current organization URL will <strong>no longer work</strong>.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
form.handleSubmit(onSubmit)(e);
setIsDialogOpen(false);
}}
>
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</form>
</Form>
</CardContent>
</Card>
</>
)
}

View file

@ -7,7 +7,6 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { useDomain } from "@/hooks/useDomain";
import { orgNameSchema } from "@/lib/schemas";
import { isServiceError } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
@ -28,7 +27,6 @@ interface ChangeOrgNameCardProps {
}
export function ChangeOrgNameCard({ orgName, currentUserRole }: ChangeOrgNameCardProps) {
const domain = useDomain()
const { toast } = useToast()
const captureEvent = useCaptureEvent();
const router = useRouter();
@ -42,7 +40,7 @@ export function ChangeOrgNameCard({ orgName, currentUserRole }: ChangeOrgNameCar
const { isSubmitting } = form.formState;
const onSubmit = useCallback(async (data: z.infer<typeof formSchema>) => {
const result = await updateOrgName(data.name, domain);
const result = await updateOrgName(data.name);
if (isServiceError(result)) {
toast({
description: `❌ Failed to update organization name. Reason: ${result.message}`,
@ -57,7 +55,7 @@ export function ChangeOrgNameCard({ orgName, currentUserRole }: ChangeOrgNameCar
captureEvent('wa_org_name_updated_success', {});
router.refresh();
}
}, [domain, router, toast, captureEvent]);
}, [router, toast, captureEvent]);
return (
<Card>

View file

@ -2,10 +2,8 @@ import { ChangeOrgNameCard } from "./components/changeOrgNameCard";
import { isServiceError } from "@/lib/utils";
import { getCurrentUserRole } from "@/actions";
import { getOrgFromDomain } from "@/data/org";
import { ChangeOrgDomainCard } from "./components/changeOrgDomainCard";
import { ServiceErrorException } from "@/lib/serviceError";
import { ErrorCode } from "@/lib/errorCodes";
import { headers } from "next/headers";
interface GeneralSettingsPageProps {
params: Promise<{
@ -34,8 +32,6 @@ export default async function GeneralSettingsPage(props: GeneralSettingsPageProp
});
}
const host = (await headers()).get('host') ?? '';
return (
<div className="flex flex-col gap-6">
<div>
@ -46,12 +42,6 @@ export default async function GeneralSettingsPage(props: GeneralSettingsPageProp
orgName={org.name}
currentUserRole={currentUserRole}
/>
<ChangeOrgDomainCard
orgDomain={org.domain}
currentUserRole={currentUserRole}
rootDomain={host}
/>
</div>
)
}

View file

@ -169,33 +169,3 @@ const getVerifiedApiObject = async (apiKeyString: string): Promise<ApiKey | unde
return apiKey;
}
export const withMinimumOrgRole = async <T>(
userRole: OrgRole,
minRequiredRole: OrgRole = OrgRole.MEMBER,
fn: () => Promise<T>,
) => {
const getAuthorizationPrecedence = (role: OrgRole): number => {
switch (role) {
case OrgRole.GUEST:
return 0;
case OrgRole.MEMBER:
return 1;
case OrgRole.OWNER:
return 2;
}
};
if (
getAuthorizationPrecedence(userRole) < getAuthorizationPrecedence(minRequiredRole)
) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: "You do not have sufficient permissions to perform this action.",
} satisfies ServiceError;
}
return fn();
}

View file

@ -0,0 +1,71 @@
import { expect, test, vi, describe } from 'vitest';
import { StatusCodes } from 'http-status-codes';
import { OrgRole } from '@sourcebot/db';
import { withMinimumOrgRole } from './withMinimumOrgRole';
import { ErrorCode } from './lib/errorCodes';
describe('withMinimumOrgRole', () => {
test('should execute function when user has sufficient permissions', async () => {
const mockFn = vi.fn().mockResolvedValue('success');
const result = await withMinimumOrgRole(
OrgRole.OWNER,
OrgRole.MEMBER,
mockFn
);
expect(mockFn).toHaveBeenCalledOnce();
expect(result).toBe('success');
});
test('should return forbidden error when user has insufficient permissions', async () => {
const mockFn = vi.fn().mockResolvedValue('success');
const result = await withMinimumOrgRole(
OrgRole.MEMBER,
OrgRole.OWNER,
mockFn
);
expect(mockFn).not.toHaveBeenCalled();
expect(result).toEqual({
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: "You do not have sufficient permissions to perform this action.",
});
});
test('should respect role hierarchy: OWNER > MEMBER > GUEST', async () => {
const mockFn = vi.fn().mockResolvedValue('success');
// Test OWNER can access MEMBER-required functions
const ownerResult = await withMinimumOrgRole(
OrgRole.OWNER,
OrgRole.MEMBER,
mockFn
);
expect(ownerResult).toBe('success');
// Test MEMBER can access MEMBER-required functions
const memberResult = await withMinimumOrgRole(
OrgRole.MEMBER,
OrgRole.MEMBER,
mockFn
);
expect(memberResult).toBe('success');
// Test GUEST cannot access MEMBER-required functions
const guestResult = await withMinimumOrgRole(
OrgRole.GUEST,
OrgRole.MEMBER,
mockFn
);
expect(guestResult).toEqual({
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: "You do not have sufficient permissions to perform this action.",
});
expect(mockFn).toHaveBeenCalledTimes(2); // Only successful calls
});
});

View file

@ -0,0 +1,34 @@
import { StatusCodes } from "http-status-codes";
import { OrgRole } from "@sourcebot/db";
import { ErrorCode } from "./lib/errorCodes";
import { ServiceError } from "./lib/serviceError";
export const withMinimumOrgRole = async <T>(
userRole: OrgRole,
minRequiredRole: OrgRole = OrgRole.MEMBER,
fn: () => Promise<T>,
) => {
const getAuthorizationPrecedence = (role: OrgRole): number => {
switch (role) {
case OrgRole.GUEST:
return 0;
case OrgRole.MEMBER:
return 1;
case OrgRole.OWNER:
return 2;
}
};
if (
getAuthorizationPrecedence(userRole) < getAuthorizationPrecedence(minRequiredRole)
) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: "You do not have sufficient permissions to perform this action.",
} satisfies ServiceError;
}
return fn();
}