mirror of
https://github.com/andwati/dokploy.git
synced 2026-11-09 21:45:17 +00:00
feat: add credentials-based user provisioning alongside invitation flow
This commit is contained in:
@@ -35,14 +35,63 @@ import {
|
|||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
|
|
||||||
const addInvitation = z.object({
|
const addInvitation = z
|
||||||
email: z
|
.object({
|
||||||
.string()
|
mode: z.enum(["invitation", "credentials"]),
|
||||||
.min(1, "Email is required")
|
email: z
|
||||||
.email({ message: "Invalid email" }),
|
.string()
|
||||||
role: z.enum(["member", "admin"]),
|
.min(1, "Email is required")
|
||||||
notificationId: z.string().optional(),
|
.email({ message: "Invalid email" }),
|
||||||
});
|
role: z.enum(["member", "admin"]),
|
||||||
|
notificationId: z.string().optional(),
|
||||||
|
password: z.string().optional(),
|
||||||
|
confirmPassword: z.string().optional(),
|
||||||
|
})
|
||||||
|
.superRefine((value, ctx) => {
|
||||||
|
if (value.mode !== "credentials") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value.password) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
message: "Password is required",
|
||||||
|
path: ["password"],
|
||||||
|
});
|
||||||
|
} else if (value.password.length < 8) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
message: "Password must be at least 8 characters",
|
||||||
|
path: ["password"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value.confirmPassword) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
message: "Confirm password is required",
|
||||||
|
path: ["confirmPassword"],
|
||||||
|
});
|
||||||
|
} else if (value.confirmPassword.length < 8) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
message: "Password must be at least 8 characters",
|
||||||
|
path: ["confirmPassword"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
value.password &&
|
||||||
|
value.confirmPassword &&
|
||||||
|
value.password !== value.confirmPassword
|
||||||
|
) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
message: "Passwords do not match",
|
||||||
|
path: ["confirmPassword"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
type AddInvitation = z.infer<typeof addInvitation>;
|
type AddInvitation = z.infer<typeof addInvitation>;
|
||||||
|
|
||||||
@@ -54,53 +103,91 @@ export const AddInvitation = () => {
|
|||||||
const { data: emailProviders } =
|
const { data: emailProviders } =
|
||||||
api.notification.getEmailProviders.useQuery();
|
api.notification.getEmailProviders.useQuery();
|
||||||
const { mutateAsync: sendInvitation } = api.user.sendInvitation.useMutation();
|
const { mutateAsync: sendInvitation } = api.user.sendInvitation.useMutation();
|
||||||
|
const { mutateAsync: createUserWithCredentials } =
|
||||||
|
api.user.createUserWithCredentials.useMutation();
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const { data: activeOrganization } = authClient.useActiveOrganization();
|
const { data: activeOrganization } = authClient.useActiveOrganization();
|
||||||
|
|
||||||
const form = useForm<AddInvitation>({
|
const form = useForm<AddInvitation>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
|
mode: "invitation",
|
||||||
email: "",
|
email: "",
|
||||||
role: "member",
|
role: "member",
|
||||||
notificationId: "",
|
notificationId: "",
|
||||||
|
password: "",
|
||||||
|
confirmPassword: "",
|
||||||
},
|
},
|
||||||
resolver: zodResolver(addInvitation),
|
resolver: zodResolver(addInvitation),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mode = form.watch("mode");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
form.reset();
|
form.reset();
|
||||||
}, [form, form.formState.isSubmitSuccessful, form.reset]);
|
}, [form, form.formState.isSubmitSuccessful, form.reset]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isCloud && form.getValues("mode") === "credentials") {
|
||||||
|
form.setValue("mode", "invitation");
|
||||||
|
}
|
||||||
|
}, [form, isCloud]);
|
||||||
|
|
||||||
const onSubmit = async (data: AddInvitation) => {
|
const onSubmit = async (data: AddInvitation) => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
const result = await authClient.organization.inviteMember({
|
setError(null);
|
||||||
email: data.email.toLowerCase(),
|
|
||||||
role: data.role,
|
|
||||||
organizationId: activeOrganization?.id,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (result.error) {
|
try {
|
||||||
setError(result.error.message || "");
|
if (data.mode === "credentials") {
|
||||||
} else {
|
await createUserWithCredentials({
|
||||||
if (!isCloud && data.notificationId) {
|
email: data.email.toLowerCase(),
|
||||||
await sendInvitation({
|
password: data.password || "",
|
||||||
invitationId: result.data.id,
|
role: data.role,
|
||||||
notificationId: data.notificationId || "",
|
});
|
||||||
})
|
toast.success("User created with initial credentials");
|
||||||
.then(() => {
|
setOpen(false);
|
||||||
toast.success("Invitation created and email sent");
|
|
||||||
})
|
|
||||||
.catch((error: any) => {
|
|
||||||
toast.error(error.message);
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
toast.success("Invitation created");
|
const result = await authClient.organization.inviteMember({
|
||||||
}
|
email: data.email.toLowerCase(),
|
||||||
setError(null);
|
role: data.role,
|
||||||
setOpen(false);
|
organizationId: activeOrganization?.id,
|
||||||
}
|
});
|
||||||
|
|
||||||
utils.organization.allInvitations.invalidate();
|
if (result.error) {
|
||||||
setIsLoading(false);
|
setError(result.error.message || "");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isCloud && data.notificationId) {
|
||||||
|
await sendInvitation({
|
||||||
|
invitationId: result.data.id,
|
||||||
|
notificationId: data.notificationId || "",
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
toast.success("Invitation created and email sent");
|
||||||
|
})
|
||||||
|
.catch((error: any) => {
|
||||||
|
toast.error(error.message);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
toast.success("Invitation created");
|
||||||
|
}
|
||||||
|
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const message =
|
||||||
|
error instanceof Error ? error.message : "Failed to create user";
|
||||||
|
setError(message);
|
||||||
|
toast.error(message);
|
||||||
|
} finally {
|
||||||
|
await Promise.all([
|
||||||
|
utils.organization.allInvitations.invalidate(),
|
||||||
|
utils.user.all.invalidate(),
|
||||||
|
]);
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
<DialogTrigger className="" asChild>
|
<DialogTrigger className="" asChild>
|
||||||
@@ -111,7 +198,11 @@ export const AddInvitation = () => {
|
|||||||
<DialogContent className="sm:max-w-2xl">
|
<DialogContent className="sm:max-w-2xl">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Add Invitation</DialogTitle>
|
<DialogTitle>Add Invitation</DialogTitle>
|
||||||
<DialogDescription>Invite a new user</DialogDescription>
|
<DialogDescription>
|
||||||
|
{mode === "credentials"
|
||||||
|
? "Create a user with initial credentials"
|
||||||
|
: "Invite a new user"}
|
||||||
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
{error && <AlertBlock type="error">{error}</AlertBlock>}
|
{error && <AlertBlock type="error">{error}</AlertBlock>}
|
||||||
|
|
||||||
@@ -121,6 +212,43 @@ export const AddInvitation = () => {
|
|||||||
onSubmit={form.handleSubmit(onSubmit)}
|
onSubmit={form.handleSubmit(onSubmit)}
|
||||||
className="grid w-full gap-4 "
|
className="grid w-full gap-4 "
|
||||||
>
|
>
|
||||||
|
{!isCloud && (
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="mode"
|
||||||
|
render={({ field }) => {
|
||||||
|
return (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Invite Method</FormLabel>
|
||||||
|
<Select
|
||||||
|
onValueChange={field.onChange}
|
||||||
|
defaultValue={field.value}
|
||||||
|
>
|
||||||
|
<FormControl>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select invite method" />
|
||||||
|
</SelectTrigger>
|
||||||
|
</FormControl>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="invitation">
|
||||||
|
Invitation Link
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem value="credentials">
|
||||||
|
Initial Credentials
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<FormDescription>
|
||||||
|
Choose between invitation link flow or direct
|
||||||
|
credentials provisioning
|
||||||
|
</FormDescription>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="email"
|
name="email"
|
||||||
@@ -170,7 +298,7 @@ export const AddInvitation = () => {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{!isCloud && (
|
{!isCloud && mode === "invitation" && (
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="notificationId"
|
name="notificationId"
|
||||||
@@ -210,6 +338,54 @@ export const AddInvitation = () => {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!isCloud && mode === "credentials" && (
|
||||||
|
<>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="password"
|
||||||
|
render={({ field }) => {
|
||||||
|
return (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Password</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
placeholder="Enter initial password"
|
||||||
|
{...field}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormDescription>
|
||||||
|
The user can sign in with this password immediately
|
||||||
|
</FormDescription>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="confirmPassword"
|
||||||
|
render={({ field }) => {
|
||||||
|
return (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Confirm Password</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
placeholder="Confirm initial password"
|
||||||
|
{...field}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<DialogFooter className="flex w-full flex-row">
|
<DialogFooter className="flex w-full flex-row">
|
||||||
<Button
|
<Button
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
createApiKey,
|
createApiKey,
|
||||||
|
createOrganizationUserWithCredentials,
|
||||||
findNotificationById,
|
findNotificationById,
|
||||||
findOrganizationById,
|
findOrganizationById,
|
||||||
findUserById,
|
findUserById,
|
||||||
@@ -495,6 +496,37 @@ export const userRouter = createTRPCRouter({
|
|||||||
|
|
||||||
return organizations.length;
|
return organizations.length;
|
||||||
}),
|
}),
|
||||||
|
createUserWithCredentials: adminProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
email: z.string().email(),
|
||||||
|
password: z.string().min(8),
|
||||||
|
role: z.enum(["member", "admin"]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mutation(async ({ input, ctx }) => {
|
||||||
|
if (IS_CLOUD) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "FORBIDDEN",
|
||||||
|
message:
|
||||||
|
"Creating users with initial credentials is only available in self-hosted mode",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ctx.session.activeOrganizationId) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: "Active organization is required",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return await createOrganizationUserWithCredentials({
|
||||||
|
organizationId: ctx.session.activeOrganizationId,
|
||||||
|
email: input.email,
|
||||||
|
password: input.password,
|
||||||
|
role: input.role,
|
||||||
|
});
|
||||||
|
}),
|
||||||
sendInvitation: adminProcedure
|
sendInvitation: adminProcedure
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import { db } from "@dokploy/server/db";
|
import { db } from "@dokploy/server/db";
|
||||||
import { apikey, member, user } from "@dokploy/server/db/schema";
|
import {
|
||||||
|
account,
|
||||||
|
apikey,
|
||||||
|
invitation,
|
||||||
|
member,
|
||||||
|
user,
|
||||||
|
} from "@dokploy/server/db/schema";
|
||||||
import { TRPCError } from "@trpc/server";
|
import { TRPCError } from "@trpc/server";
|
||||||
|
import * as bcrypt from "bcrypt";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import { auth } from "../lib/auth";
|
import { auth } from "../lib/auth";
|
||||||
|
|
||||||
@@ -389,6 +396,93 @@ export const findMemberById = async (
|
|||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const createOrganizationUserWithCredentials = async ({
|
||||||
|
organizationId,
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role,
|
||||||
|
}: {
|
||||||
|
organizationId: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
role: "member" | "admin";
|
||||||
|
}) => {
|
||||||
|
const normalizedEmail = email.trim().toLowerCase();
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
return await db.transaction(async (tx) => {
|
||||||
|
const existingUser = await tx.query.user.findFirst({
|
||||||
|
where: eq(user.email, normalizedEmail),
|
||||||
|
columns: {
|
||||||
|
id: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existingUser) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message:
|
||||||
|
"This email already has an account. Use the invitation link flow for existing users.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const createdUser = await tx
|
||||||
|
.insert(user)
|
||||||
|
.values({
|
||||||
|
email: normalizedEmail,
|
||||||
|
emailVerified: false,
|
||||||
|
updatedAt: now,
|
||||||
|
})
|
||||||
|
.returning({
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
})
|
||||||
|
.then((res) => res[0]);
|
||||||
|
|
||||||
|
if (!createdUser) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "INTERNAL_SERVER_ERROR",
|
||||||
|
message: "Failed to create user",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx.insert(account).values({
|
||||||
|
userId: createdUser.id,
|
||||||
|
providerId: "credential",
|
||||||
|
password: bcrypt.hashSync(password, 10),
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.insert(member).values({
|
||||||
|
organizationId,
|
||||||
|
userId: createdUser.id,
|
||||||
|
role,
|
||||||
|
createdAt: now,
|
||||||
|
isDefault: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx
|
||||||
|
.update(invitation)
|
||||||
|
.set({
|
||||||
|
status: "canceled",
|
||||||
|
})
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(invitation.organizationId, organizationId),
|
||||||
|
eq(invitation.email, normalizedEmail),
|
||||||
|
eq(invitation.status, "pending"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
userId: createdUser.id,
|
||||||
|
email: createdUser.email,
|
||||||
|
role,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
export const updateUser = async (userId: string, userData: Partial<User>) => {
|
export const updateUser = async (userId: string, userData: Partial<User>) => {
|
||||||
// Validate email if it's being updated
|
// Validate email if it's being updated
|
||||||
if (userData.email !== undefined) {
|
if (userData.email !== undefined) {
|
||||||
|
|||||||
Reference in New Issue
Block a user