mirror of
https://github.com/Dokploy/dokploy
synced 2025-06-26 18:27:59 +00:00
Enhance impersonation functionality and user management
- Updated the ImpersonationBar component to fetch users dynamically and handle impersonation actions more efficiently. - Refactored the ProfileForm to set the allowImpersonation value directly, improving form handling. - Modified the DashboardLayout to conditionally render the ImpersonationBar based on user permissions and cloud settings. - Added a new role column to the user_temp table to support user role management. - Updated API routes to include checks for root access and improved user listing functionality.
This commit is contained in:
@@ -26,7 +26,6 @@ import {
|
|||||||
CommandInput,
|
CommandInput,
|
||||||
CommandItem,
|
CommandItem,
|
||||||
CommandList,
|
CommandList,
|
||||||
CommandSeparator,
|
|
||||||
} from "@/components/ui/command";
|
} from "@/components/ui/command";
|
||||||
import {
|
import {
|
||||||
Popover,
|
Popover,
|
||||||
@@ -46,26 +45,52 @@ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import copy from "copy-to-clipboard";
|
import copy from "copy-to-clipboard";
|
||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
import type { RouterOutputs } from "@/utils/api";
|
|
||||||
|
|
||||||
type User = RouterOutputs["user"]["listUsers"]["users"][number];
|
type User = typeof authClient.$Infer.Session.user;
|
||||||
|
|
||||||
export const ImpersonationBar = () => {
|
export const ImpersonationBar = () => {
|
||||||
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||||
const [isImpersonating, setIsImpersonating] = useState(false);
|
const [isImpersonating, setIsImpersonating] = useState(false);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [showBar, setShowBar] = useState(false);
|
const [showBar, setShowBar] = useState(false);
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
|
||||||
const [recentlyAccessed, setRecentlyAccessed] = useState<User[]>([]);
|
|
||||||
const { data } = api.user.get.useQuery();
|
const { data } = api.user.get.useQuery();
|
||||||
const { data: users, isLoading } = api.user.listUsers.useQuery(
|
|
||||||
{
|
const fetchUsers = async (search?: string) => {
|
||||||
search: searchTerm,
|
try {
|
||||||
},
|
const session = await authClient.getSession();
|
||||||
{
|
if (session?.data?.session?.impersonatedBy) {
|
||||||
enabled: open && !isImpersonating,
|
return;
|
||||||
},
|
}
|
||||||
);
|
setIsLoading(true);
|
||||||
|
const response = await authClient.admin.listUsers({
|
||||||
|
query: {
|
||||||
|
limit: 30,
|
||||||
|
...(search && {
|
||||||
|
searchField: "email",
|
||||||
|
searchOperator: "contains",
|
||||||
|
searchValue: search,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const filteredUsers = response.data?.users.filter(
|
||||||
|
// @ts-ignore
|
||||||
|
(user) => user.allowImpersonation && data?.user?.email !== user.email,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.error) {
|
||||||
|
// @ts-ignore
|
||||||
|
setUsers(filteredUsers || []);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching users:", error);
|
||||||
|
toast.error("Error loading users");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleImpersonate = async () => {
|
const handleImpersonate = async () => {
|
||||||
if (!selectedUser) return;
|
if (!selectedUser) return;
|
||||||
@@ -77,11 +102,6 @@ export const ImpersonationBar = () => {
|
|||||||
setIsImpersonating(true);
|
setIsImpersonating(true);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
|
|
||||||
setRecentlyAccessed((prev) => {
|
|
||||||
const filtered = prev.filter((u) => u.id !== selectedUser.id);
|
|
||||||
return [selectedUser, ...filtered].slice(0, 5);
|
|
||||||
});
|
|
||||||
|
|
||||||
toast.success("Successfully impersonating user", {
|
toast.success("Successfully impersonating user", {
|
||||||
description: `You are now viewing as ${selectedUser.name || selectedUser.email}`,
|
description: `You are now viewing as ${selectedUser.name || selectedUser.email}`,
|
||||||
});
|
});
|
||||||
@@ -121,7 +141,7 @@ export const ImpersonationBar = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
checkImpersonation();
|
checkImpersonation();
|
||||||
// fetchUsers();
|
fetchUsers();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -159,7 +179,7 @@ export const ImpersonationBar = () => {
|
|||||||
showBar ? "translate-y-0" : "translate-y-full",
|
showBar ? "translate-y-0" : "translate-y-full",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-4 px-20 w-full">
|
<div className="flex items-center gap-4 px-4 md:px-20 w-full">
|
||||||
<Logo className="w-10 h-10" />
|
<Logo className="w-10 h-10" />
|
||||||
{!isImpersonating ? (
|
{!isImpersonating ? (
|
||||||
<div className="flex items-center gap-2 w-full">
|
<div className="flex items-center gap-2 w-full">
|
||||||
@@ -196,7 +216,7 @@ export const ImpersonationBar = () => {
|
|||||||
<CommandInput
|
<CommandInput
|
||||||
placeholder="Search users by email or name..."
|
placeholder="Search users by email or name..."
|
||||||
onValueChange={(search) => {
|
onValueChange={(search) => {
|
||||||
setSearchTerm(search);
|
fetchUsers(search);
|
||||||
}}
|
}}
|
||||||
className="h-9"
|
className="h-9"
|
||||||
/>
|
/>
|
||||||
@@ -208,46 +228,8 @@ export const ImpersonationBar = () => {
|
|||||||
<>
|
<>
|
||||||
<CommandEmpty>No users found.</CommandEmpty>
|
<CommandEmpty>No users found.</CommandEmpty>
|
||||||
<CommandList>
|
<CommandList>
|
||||||
{recentlyAccessed.length > 0 && !searchTerm && (
|
|
||||||
<>
|
|
||||||
<CommandGroup heading="Recently Accessed">
|
|
||||||
{recentlyAccessed.map((user) => (
|
|
||||||
<CommandItem
|
|
||||||
key={user.id}
|
|
||||||
value={user.email}
|
|
||||||
onSelect={() => {
|
|
||||||
setSelectedUser(user);
|
|
||||||
setOpen(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span className="flex items-center gap-2 flex-1">
|
|
||||||
<UserIcon className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
|
||||||
<span className="flex flex-col items-start">
|
|
||||||
<span className="text-sm font-medium">
|
|
||||||
{user.name || ""}
|
|
||||||
</span>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{user.email} • {user.role}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<CheckIcon
|
|
||||||
className={cn(
|
|
||||||
"ml-auto h-4 w-4",
|
|
||||||
selectedUser?.id === user.id
|
|
||||||
? "opacity-100"
|
|
||||||
: "opacity-0",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</CommandItem>
|
|
||||||
))}
|
|
||||||
</CommandGroup>
|
|
||||||
<CommandSeparator />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<CommandGroup heading="All Users">
|
<CommandGroup heading="All Users">
|
||||||
{users?.users.map((user) => (
|
{users.map((user) => (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
key={user.id}
|
key={user.id}
|
||||||
value={user.email}
|
value={user.email}
|
||||||
@@ -295,8 +277,8 @@ export const ImpersonationBar = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex items-center gap-4 w-full">
|
<div className="flex items-center gap-4 w-full flex-wrap">
|
||||||
<div className="flex items-center gap-4 flex-1">
|
<div className="flex items-center gap-4 flex-1 flex-wrap">
|
||||||
<Avatar className="h-10 w-10">
|
<Avatar className="h-10 w-10">
|
||||||
<AvatarImage
|
<AvatarImage
|
||||||
src={data?.user?.image || ""}
|
src={data?.user?.image || ""}
|
||||||
@@ -319,7 +301,7 @@ export const ImpersonationBar = () => {
|
|||||||
{data?.user?.name || ""}
|
{data?.user?.name || ""}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
<div className="flex items-center gap-3 text-sm text-muted-foreground flex-wrap">
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<UserIcon className="h-3 w-3" />
|
<UserIcon className="h-3 w-3" />
|
||||||
{data?.user?.email} • {data?.role}
|
{data?.user?.email} • {data?.role}
|
||||||
|
|||||||
@@ -102,10 +102,7 @@ export const ProfileForm = () => {
|
|||||||
keepValues: true,
|
keepValues: true,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
form.setValue("allowImpersonation", data?.user?.allowImpersonation);
|
||||||
form.reset({
|
|
||||||
allowImpersonation: data?.user?.allowImpersonation,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (data.user.email) {
|
if (data.user.email) {
|
||||||
generateSHA256Hash(data.user.email).then((hash) => {
|
generateSHA256Hash(data.user.email).then((hash) => {
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import Page from "./side";
|
import Page from "./side";
|
||||||
import { ImpersonationBar } from "../dashboard/impersonation/impersonation-bar";
|
import { ImpersonationBar } from "../dashboard/impersonation/impersonation-bar";
|
||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
import { authClient } from "@/lib/auth-client";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
@@ -10,25 +8,12 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const DashboardLayout = ({ children }: Props) => {
|
export const DashboardLayout = ({ children }: Props) => {
|
||||||
const { data: user } = api.user.get.useQuery();
|
const { data: haveRootAccess } = api.user.haveRootAccess.useQuery();
|
||||||
const { data: isCloud } = api.settings.isCloud.useQuery();
|
|
||||||
const [isBeingImpersonated, setIsBeingImpersonated] = useState(false);
|
|
||||||
const isAdmin = user?.role === "admin" || user?.role === "owner";
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const checkImpersonation = async () => {
|
|
||||||
const session = await authClient.getSession();
|
|
||||||
setIsBeingImpersonated(!!session?.data?.session?.impersonatedBy);
|
|
||||||
};
|
|
||||||
checkImpersonation();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const showImpersonationBar = (isAdmin || isBeingImpersonated) && isCloud;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Page>{children}</Page>
|
<Page>{children}</Page>
|
||||||
{showImpersonationBar && <ImpersonationBar />}
|
{haveRootAccess === true && <ImpersonationBar />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
1
apps/dokploy/drizzle/0091_spotty_kulan_gath.sql
Normal file
1
apps/dokploy/drizzle/0091_spotty_kulan_gath.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "user_temp" ADD COLUMN "role" text DEFAULT 'user' NOT NULL;
|
||||||
5711
apps/dokploy/drizzle/meta/0091_snapshot.json
Normal file
5711
apps/dokploy/drizzle/meta/0091_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -638,6 +638,13 @@
|
|||||||
"when": 1746509318678,
|
"when": 1746509318678,
|
||||||
"tag": "0090_clean_wolf_cub",
|
"tag": "0090_clean_wolf_cub",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 91,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1746518402168,
|
||||||
|
"tag": "0091_spotty_kulan_gath",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
IS_CLOUD,
|
IS_CLOUD,
|
||||||
auth,
|
|
||||||
createApiKey,
|
createApiKey,
|
||||||
findOrganizationById,
|
findOrganizationById,
|
||||||
findUserById,
|
findUserById,
|
||||||
@@ -92,42 +91,18 @@ export const userRouter = createTRPCRouter({
|
|||||||
|
|
||||||
return memberResult;
|
return memberResult;
|
||||||
}),
|
}),
|
||||||
listUsers: adminProcedure
|
haveRootAccess: protectedProcedure.query(async ({ ctx }) => {
|
||||||
.input(
|
if (!IS_CLOUD) {
|
||||||
z.object({
|
return false;
|
||||||
search: z.string().optional(),
|
}
|
||||||
}),
|
if (
|
||||||
)
|
process.env.USER_ADMIN_ID === ctx.user.id ||
|
||||||
.query(async ({ ctx, input }) => {
|
ctx.session?.impersonatedBy === process.env.USER_ADMIN_ID
|
||||||
try {
|
) {
|
||||||
console.log(process.env.USER_ADMIN_ID, ctx.user.id);
|
return true;
|
||||||
if (process.env.USER_ADMIN_ID !== ctx.user.id) {
|
}
|
||||||
return [];
|
return false;
|
||||||
}
|
}),
|
||||||
const users = await auth.listUsers({
|
|
||||||
query: {
|
|
||||||
limit: 100,
|
|
||||||
filterField: "allowImpersonation",
|
|
||||||
filterOperator: "eq",
|
|
||||||
filterValue: true,
|
|
||||||
...(input.search && {
|
|
||||||
searchField: "email",
|
|
||||||
searchOperator: "contains",
|
|
||||||
searchValue: input.search,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
// @ts-ignore
|
|
||||||
headers: {
|
|
||||||
cookie: ctx.req.headers.cookie,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
console.log(users);
|
|
||||||
return users;
|
|
||||||
} catch (error) {
|
|
||||||
console.log(error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
getBackups: adminProcedure.query(async ({ ctx }) => {
|
getBackups: adminProcedure.query(async ({ ctx }) => {
|
||||||
const memberResult = await db.query.member.findFirst({
|
const memberResult = await db.query.member.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ import { ZodError } from "zod";
|
|||||||
|
|
||||||
interface CreateContextOptions {
|
interface CreateContextOptions {
|
||||||
user: (User & { role: "member" | "admin" | "owner"; ownerId: string }) | null;
|
user: (User & { role: "member" | "admin" | "owner"; ownerId: string }) | null;
|
||||||
session: (Session & { activeOrganizationId: string }) | null;
|
session:
|
||||||
|
| (Session & { activeOrganizationId: string; impersonatedBy?: string })
|
||||||
|
| null;
|
||||||
req: CreateNextContextOptions["req"];
|
req: CreateNextContextOptions["req"];
|
||||||
res: CreateNextContextOptions["res"];
|
res: CreateNextContextOptions["res"];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ export const users_temp = pgTable("user_temp", {
|
|||||||
sshPrivateKey: text("sshPrivateKey"),
|
sshPrivateKey: text("sshPrivateKey"),
|
||||||
enableDockerCleanup: boolean("enableDockerCleanup").notNull().default(false),
|
enableDockerCleanup: boolean("enableDockerCleanup").notNull().default(false),
|
||||||
logCleanupCron: text("logCleanupCron"),
|
logCleanupCron: text("logCleanupCron"),
|
||||||
|
role: text("role").notNull().default("user"),
|
||||||
// Metrics
|
// Metrics
|
||||||
enablePaidFeatures: boolean("enablePaidFeatures").notNull().default(false),
|
enablePaidFeatures: boolean("enablePaidFeatures").notNull().default(false),
|
||||||
allowImpersonation: boolean("allowImpersonation").notNull().default(false),
|
allowImpersonation: boolean("allowImpersonation").notNull().default(false),
|
||||||
@@ -135,6 +136,8 @@ export const usersRelations = relations(users_temp, ({ one, many }) => ({
|
|||||||
const createSchema = createInsertSchema(users_temp, {
|
const createSchema = createInsertSchema(users_temp, {
|
||||||
id: z.string().min(1),
|
id: z.string().min(1),
|
||||||
isRegistered: z.boolean().optional(),
|
isRegistered: z.boolean().optional(),
|
||||||
|
}).omit({
|
||||||
|
role: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const apiCreateUserInvitation = createSchema.pick({}).extend({
|
export const apiCreateUserInvitation = createSchema.pick({}).extend({
|
||||||
|
|||||||
@@ -194,7 +194,6 @@ const { handler, api } = betterAuth({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
plugins: [
|
plugins: [
|
||||||
apiKey({
|
apiKey({
|
||||||
enableMetadata: true,
|
enableMetadata: true,
|
||||||
@@ -232,7 +231,6 @@ const { handler, api } = betterAuth({
|
|||||||
export const auth = {
|
export const auth = {
|
||||||
handler,
|
handler,
|
||||||
createApiKey: api.createApiKey,
|
createApiKey: api.createApiKey,
|
||||||
listUsers: api.listUsers,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const validateRequest = async (request: IncomingMessage) => {
|
export const validateRequest = async (request: IncomingMessage) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user