Merge pull request #2506 from divaltor/multiple-admins

feat(permissions): Add multiple admins capability
This commit is contained in:
Mauricio Siu
2025-12-07 03:11:23 -06:00
committed by GitHub
17 changed files with 528 additions and 127 deletions
@@ -158,6 +158,7 @@ export const AddInvitation = () => {
</FormControl> </FormControl>
<SelectContent> <SelectContent>
<SelectItem value="member">Member</SelectItem> <SelectItem value="member">Member</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<FormDescription> <FormDescription>
@@ -0,0 +1,159 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { AlertBlock } from "@/components/shared/alert-block";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { api } from "@/utils/api";
const changeRoleSchema = z.object({
role: z.enum(["admin", "member"]),
});
type ChangeRoleSchema = z.infer<typeof changeRoleSchema>;
interface Props {
memberId: string;
currentRole: "admin" | "member";
userEmail: string;
}
export const ChangeRole = ({ memberId, currentRole, userEmail }: Props) => {
const [isOpen, setIsOpen] = useState(false);
const utils = api.useUtils();
const { mutateAsync, isError, error, isLoading } =
api.organization.updateMemberRole.useMutation();
const form = useForm<ChangeRoleSchema>({
defaultValues: {
role: currentRole,
},
resolver: zodResolver(changeRoleSchema),
});
useEffect(() => {
if (isOpen) {
form.reset({
role: currentRole,
});
}
}, [form, currentRole, isOpen]);
const onSubmit = async (data: ChangeRoleSchema) => {
await mutateAsync({
memberId,
role: data.role,
})
.then(async () => {
toast.success("Role updated successfully");
await utils.user.all.invalidate();
setIsOpen(false);
})
.catch((error) => {
toast.error(error?.message || "Error updating role");
});
};
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger className="" asChild>
<DropdownMenuItem
className="w-full cursor-pointer"
onSelect={(e) => e.preventDefault()}
>
Change Role
</DropdownMenuItem>
</DialogTrigger>
<DialogContent className="max-h-[85vh] sm:max-w-lg">
<DialogHeader>
<DialogTitle>Change User Role</DialogTitle>
<DialogDescription>
Change the role for <strong>{userEmail}</strong>
</DialogDescription>
</DialogHeader>
{isError && <AlertBlock type="error">{error?.message}</AlertBlock>}
<Form {...form}>
<form
id="hook-form-change-role"
onSubmit={form.handleSubmit(onSubmit)}
className="w-full space-y-4"
>
<FormField
control={form.control}
name="role"
render={({ field }) => (
<FormItem>
<FormLabel>Role</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a role" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="member">Member</SelectItem>
</SelectContent>
</Select>
<FormDescription>
<strong>Admin:</strong> Can manage users and settings.
<br />
<strong>Member:</strong> Limited permissions, can be
customized.
<br />
<em className="text-muted-foreground text-xs">
Note: Owner role is intransferible.
</em>
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
<DialogFooter>
<Button
isLoading={isLoading}
form="hook-form-change-role"
type="submit"
>
Update Role
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -29,12 +29,15 @@ import {
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { api } from "@/utils/api"; import { api } from "@/utils/api";
import { AddUserPermissions } from "./add-permissions"; import { AddUserPermissions } from "./add-permissions";
import { ChangeRole } from "./change-role";
export const ShowUsers = () => { export const ShowUsers = () => {
const { data: isCloud } = api.settings.isCloud.useQuery(); const { data: isCloud } = api.settings.isCloud.useQuery();
const { data, isLoading, refetch } = api.user.all.useQuery(); const { data, isLoading, refetch } = api.user.all.useQuery();
const { mutateAsync } = api.user.remove.useMutation(); const { mutateAsync } = api.user.remove.useMutation();
const utils = api.useUtils(); const utils = api.useUtils();
const { data: session } = authClient.useSession();
return ( return (
<div className="w-full"> <div className="w-full">
@@ -81,6 +84,52 @@ export const ShowUsers = () => {
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{data?.map((member) => { {data?.map((member) => {
const currentUserRole = data?.find(
(m) => m.user.id === session?.user?.id,
)?.role;
// Owner never has "Edit Permissions" (they're absolute owner)
// Other users can edit permissions if target is not themselves and target is a member
const canEditPermissions =
member.role !== "owner" &&
member.role === "member" &&
member.user.id !== session?.user?.id;
// Can change role based on hierarchy:
// - Owner: Can change anyone's role (except themselves and other owners)
// - Admin: Can only change member roles (not other admins or owners)
// - Owner role is intransferible
const canChangeRole =
member.role !== "owner" &&
member.user.id !== session?.user?.id &&
(currentUserRole === "owner" ||
(currentUserRole === "admin" &&
member.role === "member"));
// Delete/Unlink follow same hierarchy as role changes
// - Owner: Can delete/unlink anyone (except themselves and owner can't be deleted)
// - Admin: Can only delete/unlink members (not other admins or owner)
const canDelete =
member.role !== "owner" &&
!isCloud &&
member.user.id !== session?.user?.id &&
(currentUserRole === "owner" ||
(currentUserRole === "admin" &&
member.role === "member"));
const canUnlink =
member.role !== "owner" &&
member.user.id !== session?.user?.id &&
(currentUserRole === "owner" ||
(currentUserRole === "admin" &&
member.role === "member"));
const hasAnyAction =
canEditPermissions ||
canChangeRole ||
canDelete ||
canUnlink;
return ( return (
<TableRow key={member.id}> <TableRow key={member.id}>
<TableCell className="w-[100px]"> <TableCell className="w-[100px]">
@@ -109,7 +158,7 @@ export const ShowUsers = () => {
</TableCell> </TableCell>
<TableCell className="text-right flex justify-end"> <TableCell className="text-right flex justify-end">
{member.role !== "owner" && ( {hasAnyAction ? (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button <Button
@@ -127,11 +176,23 @@ export const ShowUsers = () => {
Actions Actions
</DropdownMenuLabel> </DropdownMenuLabel>
<AddUserPermissions {canChangeRole && (
userId={member.user.id} <ChangeRole
/> memberId={member.id}
currentRole={
member.role as "admin" | "member"
}
userEmail={member.user.email}
/>
)}
{!isCloud && ( {canEditPermissions && (
<AddUserPermissions
userId={member.user.id}
/>
)}
{canDelete && (
<DialogAction <DialogAction
title="Delete User" title="Delete User"
description="Are you sure you want to delete this user?" description="Are you sure you want to delete this user?"
@@ -146,9 +207,10 @@ export const ShowUsers = () => {
); );
refetch(); refetch();
}) })
.catch(() => { .catch((err) => {
toast.error( toast.error(
"Error deleting destination", err?.message ||
"Error deleting user",
); );
}); });
}} }}
@@ -162,66 +224,79 @@ export const ShowUsers = () => {
</DialogAction> </DialogAction>
)} )}
<DialogAction {canUnlink && (
title="Unlink User" <DialogAction
description="Are you sure you want to unlink this user?" title="Unlink User"
type="destructive" description="Are you sure you want to unlink this user?"
onClick={async () => { type="destructive"
if (!isCloud) { onClick={async () => {
const orgCount = if (!isCloud) {
await utils.user.checkUserOrganizations.fetch( const orgCount =
{ await utils.user.checkUserOrganizations.fetch(
{
userId: member.user.id,
},
);
if (orgCount === 1) {
await mutateAsync({
userId: member.user.id, userId: member.user.id,
})
.then(() => {
toast.success(
"User deleted successfully",
);
refetch();
})
.catch(() => {
toast.error(
"Error deleting user",
);
});
return;
}
}
const { error } =
await authClient.organization.removeMember(
{
memberIdOrEmail: member.id,
}, },
); );
console.log(orgCount); if (!error) {
toast.success(
if (orgCount === 1) { "User unlinked successfully",
await mutateAsync({ );
userId: member.user.id, refetch();
}) } else {
.then(() => { toast.error(
toast.success( "Error unlinking user",
"User deleted successfully", );
);
refetch();
})
.catch(() => {
toast.error(
"Error deleting user",
);
});
return;
} }
} }}
const { error } =
await authClient.organization.removeMember(
{
memberIdOrEmail: member.id,
},
);
if (!error) {
toast.success(
"User unlinked successfully",
);
refetch();
} else {
toast.error("Error unlinking user");
}
}}
>
<DropdownMenuItem
className="w-full cursor-pointer text-red-500 hover:!text-red-600"
onSelect={(e) => e.preventDefault()}
> >
Unlink User <DropdownMenuItem
</DropdownMenuItem> className="w-full cursor-pointer text-red-500 hover:!text-red-600"
</DialogAction> onSelect={(e) => e.preventDefault()}
>
Unlink User
</DropdownMenuItem>
</DialogAction>
)}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
) : (
<Button
variant="ghost"
className="h-8 w-8 p-0"
disabled
>
<span className="sr-only">
No actions available
</span>
<MoreHorizontal className="h-4 w-4 text-muted-foreground" />
</Button>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
+55 -18
View File
@@ -158,7 +158,8 @@ const MENU: Menu = {
url: "/dashboard/schedules", url: "/dashboard/schedules",
icon: Clock, icon: Clock,
// Only enabled in non-cloud environments // Only enabled in non-cloud environments
isEnabled: ({ isCloud, auth }) => !isCloud && auth?.role === "owner", isEnabled: ({ isCloud, auth }) =>
!isCloud && (auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -168,7 +169,9 @@ const MENU: Menu = {
// Only enabled for admins and users with access to Traefik files in non-cloud environments // Only enabled for admins and users with access to Traefik files in non-cloud environments
isEnabled: ({ auth, isCloud }) => isEnabled: ({ auth, isCloud }) =>
!!( !!(
(auth?.role === "owner" || auth?.canAccessToTraefikFiles) && (auth?.role === "owner" ||
auth?.role === "admin" ||
auth?.canAccessToTraefikFiles) &&
!isCloud !isCloud
), ),
}, },
@@ -179,7 +182,12 @@ const MENU: Menu = {
icon: BlocksIcon, icon: BlocksIcon,
// Only enabled for admins and users with access to Docker in non-cloud environments // Only enabled for admins and users with access to Docker in non-cloud environments
isEnabled: ({ auth, isCloud }) => isEnabled: ({ auth, isCloud }) =>
!!((auth?.role === "owner" || auth?.canAccessToDocker) && !isCloud), !!(
(auth?.role === "owner" ||
auth?.role === "admin" ||
auth?.canAccessToDocker) &&
!isCloud
),
}, },
{ {
isSingle: true, isSingle: true,
@@ -188,7 +196,12 @@ const MENU: Menu = {
icon: PieChart, icon: PieChart,
// Only enabled for admins and users with access to Docker in non-cloud environments // Only enabled for admins and users with access to Docker in non-cloud environments
isEnabled: ({ auth, isCloud }) => isEnabled: ({ auth, isCloud }) =>
!!((auth?.role === "owner" || auth?.canAccessToDocker) && !isCloud), !!(
(auth?.role === "owner" ||
auth?.role === "admin" ||
auth?.canAccessToDocker) &&
!isCloud
),
}, },
{ {
isSingle: true, isSingle: true,
@@ -197,7 +210,12 @@ const MENU: Menu = {
icon: Forward, icon: Forward,
// Only enabled for admins and users with access to Docker in non-cloud environments // Only enabled for admins and users with access to Docker in non-cloud environments
isEnabled: ({ auth, isCloud }) => isEnabled: ({ auth, isCloud }) =>
!!((auth?.role === "owner" || auth?.canAccessToDocker) && !isCloud), !!(
(auth?.role === "owner" ||
auth?.role === "admin" ||
auth?.canAccessToDocker) &&
!isCloud
),
}, },
// Legacy unused menu, adjusted to the new structure // Legacy unused menu, adjusted to the new structure
@@ -264,7 +282,8 @@ const MENU: Menu = {
url: "/dashboard/settings/server", url: "/dashboard/settings/server",
icon: Activity, icon: Activity,
// Only enabled for admins in non-cloud environments // Only enabled for admins in non-cloud environments
isEnabled: ({ auth, isCloud }) => !!(auth?.role === "owner" && !isCloud), isEnabled: ({ auth, isCloud }) =>
!!((auth?.role === "owner" || auth?.role === "admin") && !isCloud),
}, },
{ {
isSingle: true, isSingle: true,
@@ -278,7 +297,8 @@ const MENU: Menu = {
url: "/dashboard/settings/servers", url: "/dashboard/settings/servers",
icon: Server, icon: Server,
// Only enabled for admins // Only enabled for admins
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -286,7 +306,8 @@ const MENU: Menu = {
icon: Users, icon: Users,
url: "/dashboard/settings/users", url: "/dashboard/settings/users",
// Only enabled for admins // Only enabled for admins
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -295,14 +316,19 @@ const MENU: Menu = {
url: "/dashboard/settings/ssh-keys", url: "/dashboard/settings/ssh-keys",
// Only enabled for admins and users with access to SSH keys // Only enabled for admins and users with access to SSH keys
isEnabled: ({ auth }) => isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.canAccessToSSHKeys), !!(
auth?.role === "owner" ||
auth?.canAccessToSSHKeys ||
auth?.role === "admin"
),
}, },
{ {
title: "AI", title: "AI",
icon: BotIcon, icon: BotIcon,
url: "/dashboard/settings/ai", url: "/dashboard/settings/ai",
isSingle: true, isSingle: true,
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -311,7 +337,11 @@ const MENU: Menu = {
icon: GitBranch, icon: GitBranch,
// Only enabled for admins and users with access to Git providers // Only enabled for admins and users with access to Git providers
isEnabled: ({ auth }) => isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.canAccessToGitProviders), !!(
auth?.role === "owner" ||
auth?.canAccessToGitProviders ||
auth?.role === "admin"
),
}, },
{ {
isSingle: true, isSingle: true,
@@ -319,7 +349,8 @@ const MENU: Menu = {
url: "/dashboard/settings/registry", url: "/dashboard/settings/registry",
icon: Package, icon: Package,
// Only enabled for admins // Only enabled for admins
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -327,7 +358,8 @@ const MENU: Menu = {
url: "/dashboard/settings/destinations", url: "/dashboard/settings/destinations",
icon: Database, icon: Database,
// Only enabled for admins // Only enabled for admins
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
@@ -336,7 +368,8 @@ const MENU: Menu = {
url: "/dashboard/settings/certificates", url: "/dashboard/settings/certificates",
icon: ShieldCheck, icon: ShieldCheck,
// Only enabled for admins // Only enabled for admins
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -344,7 +377,8 @@ const MENU: Menu = {
url: "/dashboard/settings/cluster", url: "/dashboard/settings/cluster",
icon: Boxes, icon: Boxes,
// Only enabled for admins in non-cloud environments // Only enabled for admins in non-cloud environments
isEnabled: ({ auth, isCloud }) => !!(auth?.role === "owner" && !isCloud), isEnabled: ({ auth, isCloud }) =>
!!((auth?.role === "owner" || auth?.role === "admin") && !isCloud),
}, },
{ {
isSingle: true, isSingle: true,
@@ -352,7 +386,8 @@ const MENU: Menu = {
url: "/dashboard/settings/notifications", url: "/dashboard/settings/notifications",
icon: Bell, icon: Bell,
// Only enabled for admins // Only enabled for admins
isEnabled: ({ auth }) => !!(auth?.role === "owner"), isEnabled: ({ auth }) =>
!!(auth?.role === "owner" || auth?.role === "admin"),
}, },
{ {
isSingle: true, isSingle: true,
@@ -718,7 +753,9 @@ function SidebarLogo() {
</div> </div>
); );
})} })}
{(user?.role === "owner" || isCloud) && ( {(user?.role === "owner" ||
user?.role === "admin" ||
isCloud) && (
<> <>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<AddOrganization /> <AddOrganization />
@@ -1082,7 +1119,7 @@ export default function Page({ children }: Props) {
</SidebarContent> </SidebarContent>
<SidebarFooter> <SidebarFooter>
<SidebarMenu className="flex flex-col gap-2"> <SidebarMenu className="flex flex-col gap-2">
{!isCloud && auth?.role === "owner" && ( {!isCloud && (auth?.role === "owner" || auth?.role === "admin") && (
<SidebarMenuItem> <SidebarMenuItem>
<UpdateServerButton /> <UpdateServerButton />
</SidebarMenuItem> </SidebarMenuItem>
+7 -3
View File
@@ -102,7 +102,9 @@ export const UserNav = () => {
> >
Monitoring Monitoring
</DropdownMenuItem> </DropdownMenuItem>
{(data?.role === "owner" || data?.canAccessToTraefikFiles) && ( {(data?.role === "owner" ||
data?.role === "admin" ||
data?.canAccessToTraefikFiles) && (
<DropdownMenuItem <DropdownMenuItem
className="cursor-pointer" className="cursor-pointer"
onClick={() => { onClick={() => {
@@ -112,7 +114,9 @@ export const UserNav = () => {
Traefik Traefik
</DropdownMenuItem> </DropdownMenuItem>
)} )}
{(data?.role === "owner" || data?.canAccessToDocker) && ( {(data?.role === "owner" ||
data?.role === "admin" ||
data?.canAccessToDocker) && (
<DropdownMenuItem <DropdownMenuItem
className="cursor-pointer" className="cursor-pointer"
onClick={() => { onClick={() => {
@@ -126,7 +130,7 @@ export const UserNav = () => {
)} )}
</> </>
) : ( ) : (
data?.role === "owner" && ( (data?.role === "owner" || data?.role === "admin") && (
<DropdownMenuItem <DropdownMenuItem
className="cursor-pointer" className="cursor-pointer"
onClick={() => { onClick={() => {
+1 -1
View File
@@ -40,7 +40,7 @@ export async function getServerSideProps(
}; };
} }
const { user } = await validateRequest(ctx.req); const { user } = await validateRequest(ctx.req);
if (!user || user.role !== "owner") { if (!user || (user.role !== "owner" && user.role !== "admin")) {
return { return {
redirect: { redirect: {
permanent: true, permanent: true,
@@ -30,7 +30,7 @@ export async function getServerSideProps(
} }
const { req, res } = ctx; const { req, res } = ctx;
const { user, session } = await validateRequest(req); const { user, session } = await validateRequest(req);
if (!user || user.role === "member") { if (!user || user.role !== "owner") {
return { return {
redirect: { redirect: {
permanent: true, permanent: true,
@@ -18,7 +18,9 @@ const Page = () => {
<div className="w-full"> <div className="w-full">
<div className="h-full rounded-xl max-w-5xl mx-auto flex flex-col gap-4"> <div className="h-full rounded-xl max-w-5xl mx-auto flex flex-col gap-4">
<ProfileForm /> <ProfileForm />
{(data?.canAccessToAPI || data?.role === "owner") && <ShowApiKeys />} {(data?.canAccessToAPI ||
data?.role === "owner" ||
data?.role === "admin") && <ShowApiKeys />}
{/* {isCloud && <RemoveSelfAccount />} */} {/* {isCloud && <RemoveSelfAccount />} */}
</div> </div>
+2 -2
View File
@@ -1,11 +1,11 @@
import { findAdmin } from "@dokploy/server"; import { findOwner } from "@dokploy/server";
import { db } from "@dokploy/server/db"; import { db } from "@dokploy/server/db";
import { user } from "@dokploy/server/db/schema"; import { user } from "@dokploy/server/db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
(async () => { (async () => {
try { try {
const result = await findAdmin(); const result = await findOwner();
const update = await db const update = await db
.update(user) .update(user)
+2 -2
View File
@@ -1,4 +1,4 @@
import { findAdmin, generateRandomPassword } from "@dokploy/server"; import { findOwner, generateRandomPassword } from "@dokploy/server";
import { db } from "@dokploy/server/db"; import { db } from "@dokploy/server/db";
import { account } from "@dokploy/server/db/schema"; import { account } from "@dokploy/server/db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
@@ -7,7 +7,7 @@ import { eq } from "drizzle-orm";
try { try {
const randomPassword = await generateRandomPassword(); const randomPassword = await generateRandomPassword();
const result = await findAdmin(); const result = await findOwner();
const update = await db const update = await db
.update(account) .update(account)
@@ -15,7 +15,7 @@ export const organizationRouter = createTRPCRouter({
}), }),
) )
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
if (ctx.user.role !== "owner" && !IS_CLOUD) { if (ctx.user.role !== "owner" && ctx.user.role !== "admin" && !IS_CLOUD) {
throw new TRPCError({ throw new TRPCError({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Only the organization owner can create an organization", message: "Only the organization owner can create an organization",
@@ -96,7 +96,7 @@ export const organizationRouter = createTRPCRouter({
}), }),
) )
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
if (ctx.user.role !== "owner" && !IS_CLOUD) { if (ctx.user.role !== "owner" && ctx.user.role !== "admin" && !IS_CLOUD) {
throw new TRPCError({ throw new TRPCError({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Only the organization owner can update it", message: "Only the organization owner can update it",
@@ -119,7 +119,7 @@ export const organizationRouter = createTRPCRouter({
}), }),
) )
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
if (ctx.user.role !== "owner" && !IS_CLOUD) { if (ctx.user.role !== "owner" && ctx.user.role !== "admin" && !IS_CLOUD) {
throw new TRPCError({ throw new TRPCError({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Only the organization owner can delete it", message: "Only the organization owner can delete it",
@@ -194,6 +194,65 @@ export const organizationRouter = createTRPCRouter({
.delete(invitation) .delete(invitation)
.where(eq(invitation.id, input.invitationId)); .where(eq(invitation.id, input.invitationId));
}), }),
updateMemberRole: adminProcedure
.input(
z.object({
memberId: z.string(),
role: z.enum(["admin", "member"]),
}),
)
.mutation(async ({ ctx, input }) => {
// Fetch the target member
const target = await db.query.member.findFirst({
where: eq(member.id, input.memberId),
with: { user: true },
});
if (!target) {
throw new TRPCError({ code: "NOT_FOUND", message: "Member not found" });
}
if (target.organizationId !== ctx.session.activeOrganizationId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You are not allowed to update this member's role",
});
}
// Prevent users from changing their own role
if (target.userId === ctx.user.id) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You cannot change your own role",
});
}
// Owner role is intransferible - cannot change to or from owner
if (target.role === "owner") {
throw new TRPCError({
code: "FORBIDDEN",
message: "The owner role is intransferible",
});
}
// Only owners can change admin roles
// Admins can only change member roles
if (ctx.user.role === "admin" && target.role === "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Only the organization owner can change admin roles. Admins can only modify member roles.",
});
}
// Update the target member's role
await db
.update(member)
.set({ role: input.role })
.where(eq(member.id, input.memberId));
return true;
}),
setDefault: protectedProcedure setDefault: protectedProcedure
.input( .input(
z.object({ z.object({
+10 -10
View File
@@ -1,13 +1,13 @@
import { import {
canAccessToTraefikFiles, canAccessToTraefikFiles,
checkGPUStatus, checkGPUStatus,
cleanupContainers,
cleanupBuilders,
cleanupSystem,
cleanupImages,
cleanupVolumes,
cleanupAll,
checkPortInUse, checkPortInUse,
cleanupAll,
cleanupBuilders,
cleanupContainers,
cleanupImages,
cleanupSystem,
cleanupVolumes,
DEFAULT_UPDATE_DATA, DEFAULT_UPDATE_DATA,
execAsync, execAsync,
findServerById, findServerById,
@@ -211,7 +211,7 @@ export const settingsRouter = createTRPCRouter({
if (IS_CLOUD) { if (IS_CLOUD) {
return true; return true;
} }
await updateUser(ctx.user.id, { await updateUser(ctx.user.ownerId, {
sshPrivateKey: input.sshPrivateKey, sshPrivateKey: input.sshPrivateKey,
}); });
@@ -223,7 +223,7 @@ export const settingsRouter = createTRPCRouter({
if (IS_CLOUD) { if (IS_CLOUD) {
return true; return true;
} }
const user = await updateUser(ctx.user.id, { const user = await updateUser(ctx.user.ownerId, {
host: input.host, host: input.host,
...(input.letsEncryptEmail && { ...(input.letsEncryptEmail && {
letsEncryptEmail: input.letsEncryptEmail, letsEncryptEmail: input.letsEncryptEmail,
@@ -250,7 +250,7 @@ export const settingsRouter = createTRPCRouter({
if (IS_CLOUD) { if (IS_CLOUD) {
return true; return true;
} }
await updateUser(ctx.user.id, { await updateUser(ctx.user.ownerId, {
sshPrivateKey: null, sshPrivateKey: null,
}); });
return true; return true;
@@ -310,7 +310,7 @@ export const settingsRouter = createTRPCRouter({
} }
} }
} else if (!IS_CLOUD) { } else if (!IS_CLOUD) {
const userUpdated = await updateUser(ctx.user.id, { const userUpdated = await updateUser(ctx.user.ownerId, {
enableDockerCleanup: input.enableDockerCleanup, enableDockerCleanup: input.enableDockerCleanup,
}); });
+9 -7
View File
@@ -56,15 +56,16 @@ export const stripeRouter = createTRPCRouter({
}); });
const items = getStripeItems(input.serverQuantity, input.isAnnual); const items = getStripeItems(input.serverQuantity, input.isAnnual);
const user = await findUserById(ctx.user.id); // Always operate on the organization owner's Stripe customer
const owner = await findUserById(ctx.user.ownerId);
let stripeCustomerId = user.stripeCustomerId; let stripeCustomerId = owner.stripeCustomerId;
if (stripeCustomerId) { if (stripeCustomerId) {
const customer = await stripe.customers.retrieve(stripeCustomerId); const customer = await stripe.customers.retrieve(stripeCustomerId);
if (customer.deleted) { if (customer.deleted) {
await updateUser(user.id, { await updateUser(owner.id, {
stripeCustomerId: null, stripeCustomerId: null,
}); });
stripeCustomerId = null; stripeCustomerId = null;
@@ -78,7 +79,7 @@ export const stripeRouter = createTRPCRouter({
customer: stripeCustomerId, customer: stripeCustomerId,
}), }),
metadata: { metadata: {
adminId: user.id, adminId: owner.id,
}, },
allow_promotion_codes: true, allow_promotion_codes: true,
success_url: `${WEBSITE_URL}/dashboard/settings/servers?success=true`, success_url: `${WEBSITE_URL}/dashboard/settings/servers?success=true`,
@@ -88,15 +89,16 @@ export const stripeRouter = createTRPCRouter({
return { sessionId: session.id }; return { sessionId: session.id };
}), }),
createCustomerPortalSession: adminProcedure.mutation(async ({ ctx }) => { createCustomerPortalSession: adminProcedure.mutation(async ({ ctx }) => {
const user = await findUserById(ctx.user.id); // Use the organization's owner account for billing portal
const owner = await findUserById(ctx.user.ownerId);
if (!user.stripeCustomerId) { if (!owner.stripeCustomerId) {
throw new TRPCError({ throw new TRPCError({
code: "BAD_REQUEST", code: "BAD_REQUEST",
message: "Stripe Customer ID not found", message: "Stripe Customer ID not found",
}); });
} }
const stripeCustomerId = user.stripeCustomerId; const stripeCustomerId = owner.stripeCustomerId;
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2024-09-30.acacia", apiVersion: "2024-09-30.acacia",
+57 -3
View File
@@ -1,6 +1,5 @@
import { import {
createApiKey, createApiKey,
findAdmin,
findNotificationById, findNotificationById,
findOrganizationById, findOrganizationById,
findUserById, findUserById,
@@ -87,7 +86,11 @@ export const userRouter = createTRPCRouter({
// Allow access if: // Allow access if:
// 1. User is requesting their own information // 1. User is requesting their own information
// 2. User has owner role (admin permissions) AND user is in the same organization // 2. User has owner role (admin permissions) AND user is in the same organization
if (memberResult.userId !== ctx.user.id && ctx.user.role !== "owner") { if (
memberResult.userId !== ctx.user.id &&
ctx.user.role !== "owner" &&
ctx.user.role !== "admin"
) {
throw new TRPCError({ throw new TRPCError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "You are not authorized to access this user", message: "You are not authorized to access this user",
@@ -223,10 +226,61 @@ export const userRouter = createTRPCRouter({
userId: z.string(), userId: z.string(),
}), }),
) )
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
if (IS_CLOUD) { if (IS_CLOUD) {
return true; return true;
} }
// Ensure the acting user has admin privileges in the active organization
if (ctx.user.role !== "owner" && ctx.user.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only owners or admins can delete users",
});
}
// Fetch target member within the active organization
const targetMember = await db.query.member.findFirst({
where: and(
eq(member.userId, input.userId),
eq(member.organizationId, ctx.session?.activeOrganizationId || ""),
),
});
if (!targetMember) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Target user is not a member of this organization",
});
}
// Never allow deleting the organization owner via this endpoint
if (targetMember.role === "owner") {
throw new TRPCError({
code: "FORBIDDEN",
message: "You cannot delete the organization owner",
});
}
// Admin self-protection: an admin cannot delete themselves
if (targetMember.role === "admin" && input.userId === ctx.user.id) {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Admins cannot delete themselves. Ask the owner or another admin.",
});
}
// Only owners can delete admins
// Admins can only delete members
if (ctx.user.role === "admin" && targetMember.role === "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Only the organization owner can delete admins. Admins can only delete members.",
});
}
return await removeUserById(input.userId); return await removeUserById(input.userId);
}), }),
assignPermissions: adminProcedure assignPermissions: adminProcedure
+10 -2
View File
@@ -183,7 +183,11 @@ export const uploadProcedure = async (opts: any) => {
}; };
export const cliProcedure = t.procedure.use(({ ctx, next }) => { export const cliProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.session || !ctx.user || ctx.user.role !== "owner") { if (
!ctx.session ||
!ctx.user ||
(ctx.user.role !== "owner" && ctx.user.role !== "admin")
) {
throw new TRPCError({ code: "UNAUTHORIZED" }); throw new TRPCError({ code: "UNAUTHORIZED" });
} }
return next({ return next({
@@ -197,7 +201,11 @@ export const cliProcedure = t.procedure.use(({ ctx, next }) => {
}); });
export const adminProcedure = t.procedure.use(({ ctx, next }) => { export const adminProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.session || !ctx.user || ctx.user.role !== "owner") { if (
!ctx.session ||
!ctx.user ||
(ctx.user.role !== "owner" && ctx.user.role !== "admin")
) {
throw new TRPCError({ code: "UNAUTHORIZED" }); throw new TRPCError({ code: "UNAUTHORIZED" });
} }
return next({ return next({
+6 -6
View File
@@ -46,7 +46,7 @@ export const isAdminPresent = async () => {
return true; return true;
}; };
export const findAdmin = async () => { export const findOwner = async () => {
const admin = await db.query.member.findFirst({ const admin = await db.query.member.findFirst({
where: eq(member.role, "owner"), where: eq(member.role, "owner"),
with: { with: {
@@ -107,11 +107,11 @@ export const getDokployUrl = async () => {
if (IS_CLOUD) { if (IS_CLOUD) {
return "https://app.dokploy.com"; return "https://app.dokploy.com";
} }
const admin = await findAdmin(); const owner = await findOwner();
if (admin.user.host) { if (owner.user.host) {
const protocol = admin.user.https ? "https" : "http"; const protocol = owner.user.https ? "https" : "http";
return `${protocol}://${admin.user.host}`; return `${protocol}://${owner.user.host}`;
} }
return `http://${admin.user.serverIp}:${process.env.PORT}`; return `http://${owner.user.serverIp}:${process.env.PORT}`;
}; };
@@ -1,5 +1,5 @@
import { paths } from "@dokploy/server/constants"; import { paths } from "@dokploy/server/constants";
import { findAdmin } from "@dokploy/server/services/admin"; import { findOwner } from "@dokploy/server/services/admin";
import { updateUser } from "@dokploy/server/services/user"; import { updateUser } from "@dokploy/server/services/user";
import { scheduledJobs, scheduleJob } from "node-schedule"; import { scheduledJobs, scheduleJob } from "node-schedule";
import { execAsync } from "../process/execAsync"; import { execAsync } from "../process/execAsync";
@@ -29,9 +29,9 @@ export const startLogCleanup = async (
} }
}); });
const admin = await findAdmin(); const owner = await findOwner();
if (admin) { if (owner) {
await updateUser(admin.user.id, { await updateUser(owner.user.id, {
logCleanupCron: cronExpression, logCleanupCron: cronExpression,
}); });
} }
@@ -51,9 +51,9 @@ export const stopLogCleanup = async (): Promise<boolean> => {
} }
// Update database // Update database
const admin = await findAdmin(); const owner = await findOwner();
if (admin) { if (owner) {
await updateUser(admin.user.id, { await updateUser(owner.user.id, {
logCleanupCron: null, logCleanupCron: null,
}); });
} }
@@ -69,8 +69,8 @@ export const getLogCleanupStatus = async (): Promise<{
enabled: boolean; enabled: boolean;
cronExpression: string | null; cronExpression: string | null;
}> => { }> => {
const admin = await findAdmin(); const owner = await findOwner();
const cronExpression = admin?.user.logCleanupCron ?? null; const cronExpression = owner?.user.logCleanupCron ?? null;
return { return {
enabled: cronExpression !== null, enabled: cronExpression !== null,
cronExpression, cronExpression,