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 Lukasf0891dda310d
diff --cc apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsxindex 000000000,f7ea9ace5..091bcfa78mode 000000,100644..100644--- a/apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsx+++ b/apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsx@@@ -1,0 -1,92 +1,97 @@@+ "use client";++ import { useRouter } from "next/navigation";+ import { Button, PasswordInput, Stack, TextInput } from "@mantine/core";++ import { clientApi } from "@homarr/api/client";+ import { useForm, zodResolver } from "@homarr/form";+ import {+ showErrorNotification,+ showSuccessNotification,+ } from "@homarr/notifications";+ import { useScopedI18n } from "@homarr/translation/client";+ import type { z } from "@homarr/validation";+ import { validation } from "@homarr/validation";++ interface RegistrationFormProps {+ invite: {+ id: string;+ token: string;+ };+ }++ export const RegistrationForm = ({ invite }: RegistrationFormProps) => {+ const t = useScopedI18n("user");+ const router = useRouter();+ const { mutate, isPending } = clientApi.user.register.useMutation();+ const form = useForm<FormType>({+ validate: zodResolver(validation.user.registration),+ initialValues: {+ username: "",+ password: "",+ confirmPassword: "",+ },+ validateInputOnBlur: true,+ validateInputOnChange: true,+ });++ const handleSubmit = (values: FormType) => {+ mutate(+ {+ ...values,+ inviteId: invite.id,+ token: invite.token,+ },+ {+ onSuccess() {+ showSuccessNotification({+ title: t("action.register.notification.success.title"),+ message: t("action.register.notification.success.message"),+ });+ router.push("/auth/login");+ },- onError() {++ onError(error) {++ const message =++ error.data?.code === "CONFLICT"++ ? t("error.usernameTaken")++ : t("action.register.notification.error.message");+++ showErrorNotification({+ title: t("action.register.notification.error.title"),- message: t("action.register.notification.error.message"),++ message,+ });+ },+ },+ );+ };++ return (+ <Stack gap="xl">+ <form onSubmit={form.onSubmit(handleSubmit)}>+ <Stack gap="lg">+ <TextInput+ label={t("field.username.label")}+ autoComplete="off"+ {...form.getInputProps("username")}+ />+ <PasswordInput+ label={t("field.password.label")}+ autoComplete="new-password"+ {...form.getInputProps("password")}+ />++ <PasswordInput+ label={t("field.passwordConfirm.label")}+ autoComplete="new-password"+ {...form.getInputProps("confirmPassword")}+ />+ <Button type="submit" fullWidth loading={isPending}>+ {t("action.register.label")}+ </Button>+ </Stack>+ </form>+ </Stack>+ );+ };++ type FormType = z.infer<typeof validation.user.registration>;diff --cc apps/nextjs/src/app/[locale]/manage/users/[userId]/_profile-form.tsxindex 000000000,af2028300..ae55c8a16mode 000000,100644..100644--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/_profile-form.tsx+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/_profile-form.tsx@@@ -1,0 -1,84 +1,98 @@@+ "use client";++ import { useCallback } from "react";+ import { Button, Group, Stack, TextInput } from "@mantine/core";++ import type { RouterInputs, RouterOutputs } from "@homarr/api";+ import { clientApi } from "@homarr/api/client";+ import { useForm, zodResolver } from "@homarr/form";+ import {+ showErrorNotification,+ showSuccessNotification,+ } from "@homarr/notifications";+ import { useI18n } from "@homarr/translation/client";+ import { validation } from "@homarr/validation";++ import { revalidatePathAction } from "~/app/revalidatePathAction";++ interface UserProfileFormProps {+ user: RouterOutputs["user"]["getById"];+ }++ export const UserProfileForm = ({ user }: UserProfileFormProps) => {+ const t = useI18n();++ const form = useForm({++ initialValues: {++ name: user.name ?? "",++ email: user.email ?? "",++ },++ validate: zodResolver(validation.user.editProfile.omit({ id: true })),++ validateInputOnBlur: true,++ validateInputOnChange: true,++ });+ const { mutate, isPending } = clientApi.user.editProfile.useMutation({+ async onSettled() {+ await revalidatePathAction("/manage/users");+ },- onSuccess() {++ onSuccess(_, variables) {++ // Reset form initial values to reset dirty state++ form.setInitialValues({++ name: variables.name,++ email: variables.email ?? "",++ });+ showSuccessNotification({+ title: t("common.notification.update.success"),+ message: t("user.action.editProfile.notification.success.message"),+ });+ },- onError() {++ onError(error) {++ const message =++ error.data?.code === "CONFLICT"++ ? t("user.error.usernameTaken")++ : t("user.action.editProfile.notification.error.message");+ showErrorNotification({+ title: t("common.notification.update.error"),- message: t("user.action.editProfile.notification.error.message"),++ message,+ });+ },+ });- const form = useForm({- initialValues: {- name: user.name ?? "",- email: user.email ?? "",- },- validate: zodResolver(validation.user.editProfile.omit({ id: true })),- validateInputOnBlur: true,- validateInputOnChange: true,- });++ const handleSubmit = useCallback(+ (values: FormType) => {+ mutate({+ ...values,+ id: user.id,+ });+ },+ [user.id, mutate],+ );++ 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")}+ />++ <Group justify="end">- <Button type="submit" color="teal" loading={isPending}>++ <Button++ type="submit"++ color="teal"++ disabled={!form.isDirty()}++ loading={isPending}++ >+ {t("common.action.saveChanges")}+ </Button>+ </Group>+ </Stack>+ </form>+ );+ };++ type FormType = Omit<RouterInputs["user"]["editProfile"], "id">;diff --cc packages/api/src/router/user.tsindex cb2e58702,02bffd3f3..0f35a0c46--- a/packages/api/src/router/user.ts+++ b/packages/api/src/router/user.ts@@@ -29,19 -29,82 +29,86 @@@ export const userRouter = createTRPCRouawait createUser(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",+ });+ }+++ await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, input.username);+++ await createUser(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);+++ await createUser(ctx.db, input);+ }),+ setProfileImage: protectedProcedure+ .input(+ z.object({+ userId: z.string(),+ // Max image size of 256KB, only png and jpeg are allowed+ image: z+ .string()+ .regex(/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9/+]+=*$/g)+ .max(262144)+ .nullable(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ // Only admins can change other users profile images+ if (+ ctx.session.user.id !== input.userId &&+ !ctx.session.user.permissions.includes("admin")+ ) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You are not allowed to change other users profile images",+ });+ }+const user = await ctx.db.query.users.findFirst({- where: eq(users.name, input.username.toLowerCase()),+ columns: {+ id: true,+ image: true,+ },+ where: eq(users.id, input.userId),});- if (user !== undefined) {++ if (!user) {throw new TRPCError({- code: "CONFLICT",- message: "User already exists",+ code: "NOT_FOUND",+ message: "User not found",});}- await createUser(ctx.db, input);++ await ctx.db+ .update(users)+ .set({+ image: input.image,+ })+ .where(eq(users.id, input.userId));}),getAll: publicProcedure.query(async ({ ctx }) => {return ctx.db.query.users.findMany({@@@ -76,32 -139,32 +143,38 @@@},where: eq(users.id, input.userId),});++ if (!user) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "User not found",+ });+ }++ return user;}),editProfile: publicProcedure- .input(- z.object({- form: validation.user.editProfile,- userId: z.string(),- }),- )+ .input(validation.user.editProfile).mutation(async ({ input, ctx }) => {- const user = await ctx.db- .select()- .from(users)- .where(eq(users.id, input.userId))- .limit(1);- const existingUser = await ctx.db.query.users.findFirst({- where: eq(users.name, input.form.name.toLowerCase()),+ const user = await ctx.db.query.users.findFirst({+ columns: { email: true },+ where: eq(users.id, input.id),});- if (existingUser !== undefined) {+ if (!user) {throw new TRPCError({- code: "CONFLICT",- message: `User ${input.form.name} already exists`,+ code: "NOT_FOUND",+ message: "User not found",});}- const emailDirty =- input.form.email && user[0]?.email !== input.form.email;+++ await checkUsernameAlreadyTakenAndThrowAsync(++ ctx.db,++ input.name,++ input.id,++ );+++ const emailDirty = input.email && user.email !== input.email;await ctx.db.update(users).set({@@@ -155,3 -259,3 +271,21 @@@ const createUser = asyncsalt,});};++++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",++ });++};diff --cc packages/translation/src/lang/en.tsindex 369f6928f,8fec28235..c019f6889--- a/packages/translation/src/lang/en.ts+++ b/packages/translation/src/lang/en.ts@@@ -25,10 -32,95 +32,98 @@@ export defaultpasswordConfirm: {label: "Confirm password",},+ previousPassword: {+ label: "Previous password",+ },+ },++ error: {++ usernameTaken: "Username already taken",+ },action: {- login: "Login",+ login: {+ label: "Login",+ notification: {+ success: {+ title: "Login successful",+ message: "You are now logged in",+ },+ error: {+ title: "Login failed",+ message: "Your login failed",+ },+ },+ },+ register: {+ label: "Create account",+ notification: {+ success: {+ title: "Account created",+ message: "Please log in to continue",+ },+ error: {+ title: "Account creation failed",+ message: "Your account could not be created",+ },+ },+ },create: "Create user",+ changePassword: {+ label: "Change password",+ notification: {+ success: {+ message: "Password changed successfully",+ },+ error: {+ message: "Unable to change password",+ },+ },+ },+ manageAvatar: {+ changeImage: {+ label: "Change image",+ notification: {+ success: {+ message: "The image changed successfully",+ },+ error: {+ message: "Unable to change image",+ },+ toLarge: {+ title: "Image is too large",+ message: "Max image size is {size}",+ },+ },+ },+ removeImage: {+ label: "Remove image",+ confirm: "Are you sure you want to remove the image?",+ notification: {+ success: {+ message: "Image removed successfully",+ },+ error: {+ message: "Unable to remove image",+ },+ },+ },+ },+ editProfile: {+ notification: {+ success: {+ message: "Profile updated successfully",+ },+ error: {+ message: "Unable to update profile",+ },+ },+ },+ delete: {+ label: "Delete user permanently",+ description:+ "Deletes this user including their preferences. Will not delete any boards. User will not be notified.",+ confirm:+ "Are you sure, that you want to delete the user {username} with his preferences?",+ },select: {label: "Select user",notFound: "No user found",