Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

Merge branch 'dev' into ajnart/fix-duplicate-users

Meier Lukasc3b2215c7ae5
diff --cc apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx
index 01a3e06c7,54f45526b..44ba9ddb7
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx
@@@ -70,23 -55,11 +64,11 @@@ export const UserProfileForm = ({ user
return (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack>
- <TextInput
- label={t("user.field.username.label")}
- withAsterisk
- {...form.getInputProps("name")}
- />
- <TextInput
- label={t("user.field.email.label")}
- {...form.getInputProps("email")}
- />
+ <TextInput label={t("user.field.username.label")} withAsterisk {...form.getInputProps("name")} />
+ <TextInput label={t("user.field.email.label")} {...form.getInputProps("email")} />
<Group justify="end">
- <Button
- type="submit"
- color="teal"
- disabled={!form.isDirty()}
- loading={isPending}
- >
- <Button type="submit" color="teal" loading={isPending}>
++ <Button type="submit" color="teal" disabled={!form.isDirty()} loading={isPending}>
{t("common.action.saveChanges")}
</Button>
</Group>
diff --cc apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx
index e35b1ae1b,5a27d206c..eadf51ddd
--- a/apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx
@@@ -14,10 -5,10 +5,11 @@@ import { Avatar, Card, PasswordInput, S
import { IconUserCheck } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
- import { useForm, zodResolver } from "@homarr/form";
+ import { useZodForm } from "@homarr/form";
+import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { validation, z } from "@homarr/validation";
+ import { createCustomErrorParams } from "@homarr/validation/form";
import { StepperNavigationComponent } from "./stepper-navigation.component";
@@@ -39,60 -26,42 +27,51 @@@ export const UserCreateStepperComponen
const hasNext = active < stepperMax;
const hasPrevious = active > 0;
- const { mutateAsync, isPending } = clientApi.user.create.useMutation();
+ const { mutateAsync, isPending } = clientApi.user.create.useMutation({
+ onError(error) {
+ showErrorNotification({
+ autoClose: false,
+ id: "create-user-error",
+ title: t("step.error.title"),
+ message: error.message,
+ });
+ },
+ });
- const generalForm = useForm({
- initialValues: {
- username: "",
- email: undefined,
+ const generalForm = useZodForm(
+ z.object({
+ username: z.string().min(1),
+ email: z.string().email().or(z.string().length(0).optional()),
+ }),
+ {
+ initialValues: {
+ username: "",
+ email: "",
+ },
},
- validate: zodResolver(
- z.object({
- username: z.string().min(1),
- email: z.string().email().or(z.string().length(0).optional()),
- }),
- ),
- validateInputOnBlur: true,
- validateInputOnChange: true,
- });
+ );
- const securityForm = useForm({
- initialValues: {
- password: "",
- confirmPassword: "",
+ const securityForm = useZodForm(
+ z
+ .object({
+ password: validation.user.password,
+ confirmPassword: z.string(),
+ })
+ .refine((data) => data.password === data.confirmPassword, {
+ path: ["confirmPassword"],
+ params: createCustomErrorParams("passwordsDoNotMatch"),
+ }),
+ {
+ initialValues: {
+ password: "",
+ confirmPassword: "",
+ },
},
- validate: zodResolver(
- z
- .object({
- password: validation.user.password,
- confirmPassword: z.string(),
- })
- .refine((data) => data.password === data.confirmPassword, {
- path: ["confirmPassword"],
- message: "Passwords do not match",
- }),
- ),
- validateInputOnBlur: true,
- validateInputOnChange: true,
- });
-
- const allForms = useMemo(
- () => [generalForm, securityForm],
- [generalForm, securityForm],
);
- const isCurrentFormValid = allForms[active]
- ? (allForms[active]!.isValid satisfies () => boolean)
- : () => true;
+ const allForms = useMemo(() => [generalForm, securityForm], [generalForm, securityForm]);
+
+ const isCurrentFormValid = allForms[active] ? (allForms[active]!.isValid satisfies () => boolean) : () => true;
const canNavigateToNextStep = isCurrentFormValid();
const controlledGoToNextStep = useCallback(async () => {
diff --cc packages/api/src/router/user.ts
index 4d44884fa,edffc2ae5..7d3fbd100
--- a/packages/api/src/router/user.ts
+++ b/packages/api/src/router/user.ts
@@@ -11,60 -11,46 +11,58 @@@ import { validation, z } from "@homarr/
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const userRouter = createTRPCRouter({
- initUser: publicProcedure
- .input(validation.user.init)
- .mutation(async ({ ctx, input }) => {
- const firstUser = await ctx.db.query.users.findFirst({
- columns: {
- id: true,
- },
+ initUser: publicProcedure.input(validation.user.init).mutation(async ({ ctx, input }) => {
+ const firstUser = await ctx.db.query.users.findFirst({
+ columns: {
+ id: true,
+ },
+ });
+
+ if (firstUser) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "User already exists",
});
+ }
- if (firstUser) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "User already exists",
- });
- }
+ await createUserAsync(ctx.db, input);
+ }),
+ register: publicProcedure.input(validation.user.registrationApi).mutation(async ({ ctx, input }) => {
+ const inviteWhere = and(eq(invites.id, input.inviteId), eq(invites.token, input.token));
+ const dbInvite = await ctx.db.query.invites.findFirst({
+ columns: {
+ id: true,
+ expirationDate: true,
+ },
+ where: inviteWhere,
+ });
- await createUserAsync(ctx.db, input);
- }),
- register: publicProcedure
- .input(validation.user.registrationApi)
- .mutation(async ({ ctx, input }) => {
- const inviteWhere = and(
- eq(invites.id, input.inviteId),
- eq(invites.token, input.token),
- );
- const dbInvite = await ctx.db.query.invites.findFirst({
- columns: {
- id: true,
- expirationDate: true,
- },
- where: inviteWhere,
+ if (!dbInvite || dbInvite.expirationDate < new Date()) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Invalid invite",
});
+ }
- if (!dbInvite || dbInvite.expirationDate < new Date()) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid invite",
- });
- }
++ if (!dbInvite || dbInvite.expirationDate < new Date()) {
++ throw new TRPCError({
++ code: "FORBIDDEN",
++ message: "Invalid invite",
++ });
++ }
+
- await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, input.username);
++ await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, input.username);
+
- await createUserAsync(ctx.db, input);
+ await createUserAsync(ctx.db, input);
+
- // Delete invite as it's used
- await ctx.db.delete(invites).where(inviteWhere);
- }),
- create: publicProcedure
- .input(validation.user.create)
- .mutation(async ({ ctx, input }) => {
- await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, input.username);
+ // Delete invite as it's used
+ await ctx.db.delete(invites).where(inviteWhere);
+ }),
+ create: publicProcedure.input(validation.user.create).mutation(async ({ ctx, input }) => {
++ await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, input.username);
+
- await createUserAsync(ctx.db, input);
- }),
+ await createUserAsync(ctx.db, input);
+ }),
setProfileImage: protectedProcedure
.input(
z.object({
@@@ -131,60 -114,50 +126,52 @@@
},
});
}),
- getById: publicProcedure
- .input(z.object({ userId: z.string() }))
- .query(async ({ input, ctx }) => {
- const user = await ctx.db.query.users.findFirst({
- columns: {
- id: true,
- name: true,
- email: true,
- emailVerified: true,
- image: true,
- },
- where: eq(users.id, input.userId),
+ getById: publicProcedure.input(z.object({ userId: z.string() })).query(async ({ input, ctx }) => {
+ const user = await ctx.db.query.users.findFirst({
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ emailVerified: true,
+ image: true,
+ },
+ where: eq(users.id, input.userId),
+ });
+
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
});
+ }
- if (!user) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
- });
- }
+ return user;
+ }),
+ editProfile: publicProcedure.input(validation.user.editProfile).mutation(async ({ input, ctx }) => {
+ const user = await ctx.db.query.users.findFirst({
+ columns: { email: true },
+ where: eq(users.id, input.id),
+ });
- return user;
- }),
- editProfile: publicProcedure
- .input(validation.user.editProfile)
- .mutation(async ({ input, ctx }) => {
- const user = await ctx.db.query.users.findFirst({
- columns: { email: true },
- where: eq(users.id, input.id),
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
});
+ }
- if (!user) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
- });
- }
-
- await checkUsernameAlreadyTakenAndThrowAsync(
- ctx.db,
- input.name,
- input.id,
- );
++ await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, input.name, input.id);
+
- const emailDirty = input.email && user.email !== input.email;
- await ctx.db
- .update(users)
- .set({
- name: input.name,
- email: emailDirty === true ? input.email : undefined,
- emailVerified: emailDirty === true ? null : undefined,
- })
- .where(eq(users.id, input.id));
- }),
+ const emailDirty = input.email && user.email !== input.email;
+ await ctx.db
+ .update(users)
+ .set({
+ name: input.name,
+ email: emailDirty === true ? input.email : undefined,
+ emailVerified: emailDirty === true ? null : undefined,
+ })
+ .where(eq(users.id, input.id));
+ }),
delete: publicProcedure.input(z.string()).mutation(async ({ input, ctx }) => {
await ctx.db.delete(users).where(eq(users.id, input));
}),
@@@ -267,26 -230,9 +246,23 @@@ const createUserAsync = async (db: Data
const userId = createId();
await db.insert(schema.users).values({
id: userId,
- name: input.username,
+ name: username,
+ email: input.email,
password: hashedPassword,
salt,
});
};
+
- const checkUsernameAlreadyTakenAndThrowAsync = async (
- db: Database,
- username: string,
- ignoreId?: string,
- ) => {
++const checkUsernameAlreadyTakenAndThrowAsync = async (db: Database, username: string, ignoreId?: string) => {
+ const user = await db.query.users.findFirst({
+ where: eq(users.name, username.toLowerCase()),
+ });
+
+ if (!user) return;
+ if (ignoreId && user.id === ignoreId) return;
+
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: "Username already taken",
+ });
+};