mirror of
https://github.com/sourcebot-dev/sourcebot.git
synced 2025-12-11 20:05:25 +00:00
migrate src/actions.ts to withAuthV2
This commit is contained in:
parent
66c9ec044e
commit
6abe7a40a5
7 changed files with 560 additions and 720 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -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>
|
|
||||||
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -7,7 +7,6 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||||
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
|
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import useCaptureEvent from "@/hooks/useCaptureEvent";
|
import useCaptureEvent from "@/hooks/useCaptureEvent";
|
||||||
import { useDomain } from "@/hooks/useDomain";
|
|
||||||
import { orgNameSchema } from "@/lib/schemas";
|
import { orgNameSchema } from "@/lib/schemas";
|
||||||
import { isServiceError } from "@/lib/utils";
|
import { isServiceError } from "@/lib/utils";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
|
@ -28,7 +27,6 @@ interface ChangeOrgNameCardProps {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ChangeOrgNameCard({ orgName, currentUserRole }: ChangeOrgNameCardProps) {
|
export function ChangeOrgNameCard({ orgName, currentUserRole }: ChangeOrgNameCardProps) {
|
||||||
const domain = useDomain()
|
|
||||||
const { toast } = useToast()
|
const { toast } = useToast()
|
||||||
const captureEvent = useCaptureEvent();
|
const captureEvent = useCaptureEvent();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
@ -42,7 +40,7 @@ export function ChangeOrgNameCard({ orgName, currentUserRole }: ChangeOrgNameCar
|
||||||
const { isSubmitting } = form.formState;
|
const { isSubmitting } = form.formState;
|
||||||
|
|
||||||
const onSubmit = useCallback(async (data: z.infer<typeof formSchema>) => {
|
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)) {
|
if (isServiceError(result)) {
|
||||||
toast({
|
toast({
|
||||||
description: `❌ Failed to update organization name. Reason: ${result.message}`,
|
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', {});
|
captureEvent('wa_org_name_updated_success', {});
|
||||||
router.refresh();
|
router.refresh();
|
||||||
}
|
}
|
||||||
}, [domain, router, toast, captureEvent]);
|
}, [router, toast, captureEvent]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,8 @@ import { ChangeOrgNameCard } from "./components/changeOrgNameCard";
|
||||||
import { isServiceError } from "@/lib/utils";
|
import { isServiceError } from "@/lib/utils";
|
||||||
import { getCurrentUserRole } from "@/actions";
|
import { getCurrentUserRole } from "@/actions";
|
||||||
import { getOrgFromDomain } from "@/data/org";
|
import { getOrgFromDomain } from "@/data/org";
|
||||||
import { ChangeOrgDomainCard } from "./components/changeOrgDomainCard";
|
|
||||||
import { ServiceErrorException } from "@/lib/serviceError";
|
import { ServiceErrorException } from "@/lib/serviceError";
|
||||||
import { ErrorCode } from "@/lib/errorCodes";
|
import { ErrorCode } from "@/lib/errorCodes";
|
||||||
import { headers } from "next/headers";
|
|
||||||
|
|
||||||
interface GeneralSettingsPageProps {
|
interface GeneralSettingsPageProps {
|
||||||
params: Promise<{
|
params: Promise<{
|
||||||
|
|
@ -34,8 +32,6 @@ export default async function GeneralSettingsPage(props: GeneralSettingsPageProp
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const host = (await headers()).get('host') ?? '';
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -46,12 +42,6 @@ export default async function GeneralSettingsPage(props: GeneralSettingsPageProp
|
||||||
orgName={org.name}
|
orgName={org.name}
|
||||||
currentUserRole={currentUserRole}
|
currentUserRole={currentUserRole}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ChangeOrgDomainCard
|
|
||||||
orgDomain={org.domain}
|
|
||||||
currentUserRole={currentUserRole}
|
|
||||||
rootDomain={host}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -169,33 +169,3 @@ const getVerifiedApiObject = async (apiKeyString: string): Promise<ApiKey | unde
|
||||||
|
|
||||||
return apiKey;
|
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();
|
|
||||||
}
|
|
||||||
|
|
|
||||||
71
packages/web/src/withMinimumOrgRole.test.ts
Normal file
71
packages/web/src/withMinimumOrgRole.test.ts
Normal 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
|
||||||
|
});
|
||||||
|
});
|
||||||
34
packages/web/src/withMinimumOrgRole.ts
Normal file
34
packages/web/src/withMinimumOrgRole.ts
Normal 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();
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue