Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(rbac): owners can transfer project to new owner (#473)

Diwakar Kashyapa3a52681c818
diff --git a/src/features/projects/components/DeleteProjectButton.tsx b/src/features/projects/components/DeleteProjectButton.tsx
index 2ec2049d91..5ed0eb0c90 100644
--- a/src/features/projects/components/DeleteProjectButton.tsx
+++ b/src/features/projects/components/DeleteProjectButton.tsx
@@ -77,8 +77,6 @@ export function DeleteProjectButton(props: { projectId: string }) {
});
};
- if (!hasAccess) return null;
-
return (
<div>
<h2 className="mb-6 text-base font-semibold leading-6 text-gray-900">
@@ -86,7 +84,9 @@ export function DeleteProjectButton(props: { projectId: string }) {
</h2>
<Dialog>
<DialogTrigger asChild>
- <Button variant="destructive">Delete Project</Button>
+ <Button variant="destructive" disabled={!hasAccess}>
+ Delete Project
+ </Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
diff --git a/src/features/projects/components/TransferOwnershipButton.tsx b/src/features/projects/components/TransferOwnershipButton.tsx
new file mode 100644
index 0000000000..955f9219b2
--- /dev/null
+++ b/src/features/projects/components/TransferOwnershipButton.tsx
@@ -0,0 +1,130 @@
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import { api } from "@/src/utils/api";
+import { usePostHog } from "posthog-js/react";
+import { useRouter } from "next/router";
+import * as z from "zod";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useSession } from "next-auth/react";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+
+const formSchema = z.object({
+ newOwnerEmail: z.string().email(),
+});
+export function TransferOwnershipButton(props: { projectId: string }) {
+ const utils = api.useContext();
+ const router = useRouter();
+ const posthog = usePostHog();
+
+ const session = useSession();
+ const project = session?.data?.user?.projects?.find(
+ (project) => project.id == props.projectId,
+ );
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "project:transfer",
+ });
+
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ newOwnerEmail: "",
+ },
+ });
+
+ const transferProject = api.projects.transfer.useMutation({
+ onSuccess: () => utils.projects.invalidate(),
+ onError: (error) =>
+ form.setError("newOwnerEmail", { message: error.message }),
+ });
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ form.clearErrors();
+ transferProject
+ .mutateAsync({
+ projectId: props.projectId,
+ newOwnerEmail: values.newOwnerEmail,
+ })
+ .then(() => {
+ posthog.capture("project_settings:project_transfer");
+ void router.push("/");
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }
+
+ return (
+ <div>
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button variant="destructive" disabled={!hasAccess}>
+ Transfer Ownership
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle className="text-lg font-semibold">
+ Transfer project{project?.name ? ` (${project.name})` : ""}
+ </DialogTitle>
+ <DialogDescription>
+ You will lose ownership of this project and will become an admin.
+ You cannot undo this action.
+ </DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-8"
+ data-testid="new-project-form"
+ >
+ <FormField
+ control={form.control}
+ name="newOwnerEmail"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>New owner</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="[email protected]"
+ {...field}
+ data-testid="new-project-name-input"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button
+ type="submit"
+ variant="destructive"
+ loading={transferProject.isLoading}
+ className="w-full"
+ >
+ Transfer project
+ </Button>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/src/features/projects/server/projectsRouter.ts b/src/features/projects/server/projectsRouter.ts
index edf89017bf..016d5be42a 100644
--- a/src/features/projects/server/projectsRouter.ts
+++ b/src/features/projects/server/projectsRouter.ts
@@ -67,4 +67,61 @@ export const projectsRouter = createTRPCRouter({
return true;
}),
+
+ transfer: protectedProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ newOwnerEmail: z.string().email(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "project:transfer",
+ });
+
+ // Check if new owner exists
+ const newOwner = await ctx.prisma.user.findUnique({
+ where: {
+ email: input.newOwnerEmail.toLowerCase(),
+ },
+ });
+ if (!newOwner) throw new Error("User not found");
+ if (newOwner.id === ctx.session.user.id)
+ throw new Error("You cannot transfer project to yourself");
+
+ return ctx.prisma.$transaction([
+ // Add new owner, upsert to update role if already exists
+ ctx.prisma.membership.upsert({
+ where: {
+ projectId_userId: {
+ projectId: input.projectId,
+ userId: newOwner.id,
+ },
+ },
+ update: {
+ role: "OWNER",
+ },
+ create: {
+ userId: newOwner.id,
+ projectId: input.projectId,
+ role: "OWNER",
+ },
+ }),
+ // Update old owner to admin
+ ctx.prisma.membership.update({
+ where: {
+ projectId_userId: {
+ projectId: input.projectId,
+ userId: ctx.session.user.id,
+ },
+ },
+ data: {
+ role: "ADMIN",
+ },
+ }),
+ ]);
+ }),
});
diff --git a/src/features/rbac/constants/roleAccessRights.ts b/src/features/rbac/constants/roleAccessRights.ts
index a1169aebf7..7f28200af9 100644
--- a/src/features/rbac/constants/roleAccessRights.ts
+++ b/src/features/rbac/constants/roleAccessRights.ts
@@ -15,6 +15,7 @@ const scopes = [
"scores:CUD",
"project:delete",
+ "project:transfer",
"datasets:CUD",
] as const;
@@ -34,6 +35,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"traces:delete",
"scores:CUD",
"project:delete",
+ "project:transfer",
"datasets:CUD",
],
ADMIN: [
diff --git a/src/features/rbac/utils/checkAccess.ts b/src/features/rbac/utils/checkAccess.ts
index efc3f07eee..159b3f1605 100644
--- a/src/features/rbac/utils/checkAccess.ts
+++ b/src/features/rbac/utils/checkAccess.ts
@@ -34,13 +34,13 @@ function hasAccess(p: HasAccessParams): boolean {
? // MembershipRole
p.role
: "data" in p.session
- ? // SessionContextValue
- p.session.data?.user?.projects.find(
- (project) => project.id === p.projectId,
- )?.role
- : // Session
- p.session.user?.projects.find((project) => project.id === p.projectId)
- ?.role;
+ ? // SessionContextValue
+ p.session.data?.user?.projects.find(
+ (project) => project.id === p.projectId,
+ )?.role
+ : // Session
+ p.session.user?.projects.find((project) => project.id === p.projectId)
+ ?.role;
if (role === undefined) return false;
return roleAccessRights[role].includes(p.scope);
diff --git a/src/pages/project/[projectId]/settings.tsx b/src/pages/project/[projectId]/settings.tsx
index f1cbeaf49a..b54cf71709 100644
--- a/src/pages/project/[projectId]/settings.tsx
+++ b/src/pages/project/[projectId]/settings.tsx
@@ -8,6 +8,7 @@ import { Code, Bird, GraduationCap } from "lucide-react";
import { ProjectMembersTable } from "@/src/features/rbac/components/ProjectMembersTable";
import { DeleteProjectButton } from "@/src/features/projects/components/DeleteProjectButton";
import { ProjectUsageChart } from "@/src/features/usage-metering/ProjectUsageChart";
+import { TransferOwnershipButton } from "@/src/features/projects/components/TransferOwnershipButton";
export default function SettingsPage() {
const router = useRouter();
@@ -20,7 +21,10 @@ export default function SettingsPage() {
<ApiKeyList projectId={projectId} />
<ProjectUsageChart projectId={projectId} />
<Instructions />
- <DeleteProjectButton projectId={projectId} />
+ <div className="space-y-3">
+ <DeleteProjectButton projectId={projectId} />
+ <TransferOwnershipButton projectId={projectId} />
+ </div>
</div>
</div>
);