Add create user form

This commit is contained in:
Manuel
2023-07-29 17:29:57 +02:00
parent e045081346
commit e273c830b4
6 changed files with 263 additions and 25 deletions

View File

@@ -0,0 +1,62 @@
import { Button, Card, Flex, TextInput } from '@mantine/core';
import { useForm, zodResolver } from '@mantine/form';
import { IconArrowRight, IconAt, IconUser } from '@tabler/icons-react';
import { z } from 'zod';
interface CreateAccountStepProps {
nextStep: ({ eMail, username }: { username: string; eMail: string }) => void;
}
export const CreateAccountStep = ({ nextStep }: CreateAccountStepProps) => {
const form = useForm({
initialValues: {
username: '',
eMail: '',
},
validateInputOnBlur: true,
validateInputOnChange: true,
validate: zodResolver(createAccountStepValidationSchema),
});
return (
<Card mih={400}>
<TextInput
icon={<IconUser size="0.8rem" />}
label="Username"
variant="filled"
mb="md"
withAsterisk
{...form.getInputProps('username')}
/>
<TextInput
icon={<IconAt size="0.8rem" />}
label="E-Mail"
variant="filled"
mb="md"
{...form.getInputProps('eMail')}
/>
<Flex justify="end" wrap="nowrap">
<Button
rightIcon={<IconArrowRight size="1rem" />}
disabled={!form.isValid()}
onClick={() => {
nextStep({
username: form.values.username,
eMail: form.values.eMail,
});
}}
variant="light"
px="xl"
>
Next
</Button>
</Flex>
</Card>
);
};
export const createAccountStepValidationSchema = z.object({
username: z.string().min(1).max(100),
eMail: z.string().email().or(z.literal('')),
});

View File

@@ -0,0 +1,75 @@
import { Button, Card, Flex, Group, PasswordInput } from '@mantine/core';
import { useForm, zodResolver } from '@mantine/form';
import { IconArrowLeft, IconArrowRight, IconPassword } from '@tabler/icons-react';
import { z } from 'zod';
interface CreateAccountSecurityStepProps {
nextStep: ({ password }: { password: string }) => void;
prevStep: () => void;
}
export const CreateAccountSecurityStep = ({
nextStep,
prevStep,
}: CreateAccountSecurityStepProps) => {
const form = useForm({
initialValues: {
password: '',
},
validateInputOnBlur: true,
validateInputOnChange: true,
validate: zodResolver(createAccountSecurityStepValidationSchema),
});
return (
<Card mih={400}>
<Flex columnGap={10}>
<PasswordInput
icon={<IconPassword size="0.8rem" />}
label="Password"
variant="filled"
mb="md"
withAsterisk
style={{
flexGrow: 1,
}}
{...form.getInputProps('password')}
/>
<Button
onClick={() => {
form.setFieldValue('password', randomString());
}}
>
Generate random
</Button>
</Flex>
<Group position="apart" noWrap>
<Button leftIcon={<IconArrowLeft size="1rem" />} onClick={prevStep} variant="light" px="xl">
Previous
</Button>
<Button
rightIcon={<IconArrowRight size="1rem" />}
onClick={() => {
nextStep({
password: form.values.password,
});
}}
variant="light"
px="xl"
disabled={!form.isValid()}
>
Next
</Button>
</Group>
</Card>
);
};
const randomString = () => {
return window.crypto.getRandomValues(new BigUint64Array(1))[0].toString(36);
};
export const createAccountSecurityStepValidationSchema = z.object({
password: z.string().min(10).max(50),
});

View File

@@ -1,47 +1,126 @@
import { Stepper } from '@mantine/core'; import { Button, Card, Flex, Group, Stepper, Text, TextInput } from '@mantine/core';
import { IconMailCheck, IconUser } from '@tabler/icons-react'; import { useForm, zodResolver } from '@mantine/form';
import {
IconArrowRight,
IconAt,
IconCheck,
IconLock,
IconMailCheck,
IconPremiumRights,
IconSignRight,
IconUser,
} from '@tabler/icons-react';
import Head from 'next/head'; import Head from 'next/head';
import Link from 'next/link';
import { useState } from 'react'; import { useState } from 'react';
import { z } from 'zod';
import {
CreateAccountStep,
createAccountStepValidationSchema,
} from '~/components/Admin/CreateNewUser/create-account-step';
import {
CreateAccountSecurityStep,
createAccountSecurityStepValidationSchema,
} from '~/components/Admin/CreateNewUser/security-step';
import { MainLayout } from '~/components/layout/admin/main-admin.layout'; import { MainLayout } from '~/components/layout/admin/main-admin.layout';
import { api } from '~/utils/api';
const CreateNewUserPage = () => { const CreateNewUserPage = () => {
const [active, setActive] = useState(1); const [active, setActive] = useState(0);
const nextStep = () => setActive((current) => (current < 3 ? current + 1 : current)); const nextStep = () => setActive((current) => (current < 3 ? current + 1 : current));
const prevStep = () => setActive((current) => (current > 0 ? current - 1 : current)); const prevStep = () => setActive((current) => (current > 0 ? current - 1 : current));
const form = useForm({
initialValues: {
account: {
username: '',
eMail: '',
},
security: {
password: '',
},
},
validate: zodResolver(
z.object({
account: createAccountStepValidationSchema,
security: createAccountSecurityStepValidationSchema,
})
),
});
const { mutateAsync, isSuccess } = api.user.createUser.useMutation();
return ( return (
<MainLayout> <MainLayout>
<Head> <Head>
<title>Create user Homarr</title> <title>Create user Homarr</title>
</Head> </Head>
<Stepper active={active} onStepClick={setActive} breakpoint="sm"> <Stepper active={active} onStepClick={setActive} breakpoint="sm" mih="100%">
<Stepper.Step <Stepper.Step
allowStepClick={false} allowStepClick={false}
allowStepSelect={false} allowStepSelect={false}
icon={<IconUser />} icon={<IconUser />}
label="First step" label="First step"
description="Create an account" description="Create account"
> >
Step 1 content: Create an account <CreateAccountStep
nextStep={(value) => {
form.setFieldValue('account', value);
nextStep();
}}
/>
</Stepper.Step>
<Stepper.Step
allowStepClick={false}
allowStepSelect={false}
icon={<IconLock />}
label="Second step"
description="Password"
>
<CreateAccountSecurityStep
nextStep={(value) => {
form.setFieldValue('security', value);
nextStep();
}}
prevStep={prevStep}
/>
</Stepper.Step> </Stepper.Step>
<Stepper.Step <Stepper.Step
allowStepClick={false} allowStepClick={false}
allowStepSelect={false} allowStepSelect={false}
icon={<IconMailCheck />} icon={<IconMailCheck />}
label="Second step"
description="Verify email"
>
Step 2 content: Verify email
</Stepper.Step>
<Stepper.Step
allowStepClick={false}
allowStepSelect={false}
icon={<IconUser />}
label="Final step" label="Final step"
description="Get full access" description="Save to database"
> >
Step 3 content: Get full access <Card mih={400}>
<Text>
User creation has been prepared. Do you want to create the user and store it in the
database?
</Text>
<Flex justify="end" wrap="nowrap">
<Button
onClick={async () => {
if (isSuccess) {
return;
}
await mutateAsync({
username: form.values.account.username,
password: form.values.security.password,
email: form.values.account.eMail === '' ? undefined : form.values.account.eMail,
});
}}
component={Link}
href="/manage/users"
rightIcon={<IconCheck size="1rem" />}
variant="light"
px="xl"
>
Finish
</Button>
</Flex>
</Card>
</Stepper.Step> </Stepper.Step>
<Stepper.Completed>Completed, click back button to get to previous step</Stepper.Completed> <Stepper.Completed>Completed, click back button to get to previous step</Stepper.Completed>
</Stepper> </Stepper>

View File

@@ -28,7 +28,9 @@ const ManageUsersPage = () => {
} }
); );
const [activePage, _] = useState(1); const [activePage, _] = useState(0);
console.log(data?.pages);
return ( return (
<MainLayout> <MainLayout>
@@ -71,7 +73,7 @@ const ManageUsersPage = () => {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{data.pages[0].users.map((user) => ( {data.pages[activePage].users.map((user) => (
<tr> <tr>
<td> <td>
<Group position="apart"> <Group position="apart">
@@ -92,7 +94,7 @@ const ManageUsersPage = () => {
</Table> </Table>
<Pagination <Pagination
total={data.pages.length} total={data.pages.length}
value={activePage} value={activePage + 1}
onNextPage={fetchNextPage} onNextPage={fetchNextPage}
onPreviousPage={fetchPreviousPage} onPreviousPage={fetchPreviousPage}
/> />

View File

@@ -138,7 +138,7 @@ export const userRouter = createTRPCRouter({
.input( .input(
z.object({ z.object({
limit: z.number().min(1).max(100).nullish(), limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(), cursor: z.string().nullish(),
}) })
) )
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
@@ -146,13 +146,13 @@ export const userRouter = createTRPCRouter({
const cursor = input.cursor; const cursor = input.cursor;
const users = await ctx.prisma.user.findMany({ const users = await ctx.prisma.user.findMany({
take: limit + 1, // get an extra item at the end which we'll use as next cursor take: limit + 1, // get an extra item at the end which we'll use as next cursor
cursor: cursor ? { myCursor: cursor } : undefined, cursor: cursor ? { id: cursor } : undefined,
}); });
let nextCursor: typeof cursor | undefined = undefined; let nextCursor: typeof cursor | undefined = undefined;
if (users.length > limit) { if (users.length > limit) {
const nextItem = users.pop(); const nextItem = users.pop();
nextCursor = nextItem!.myCursor; nextCursor = nextItem!.id;
} }
return { return {
@@ -160,9 +160,29 @@ export const userRouter = createTRPCRouter({
id: user.id, id: user.id,
name: user.name, name: user.name,
email: user.email, email: user.email,
emailVerified: user.emailVerified emailVerified: user.emailVerified,
})), })),
nextCursor, nextCursor,
}; };
}), }),
createUser: publicProcedure
.input(
z.object({
username: z.string(),
email: z.string().email().optional(),
password: z.string().min(8).max(100),
})
)
.mutation(async ({ ctx, input }) => {
const salt = bcrypt.genSaltSync(10);
const hashedPassword = hashPassword(input.password, salt);
await ctx.prisma.user.create({
data: {
name: input.username,
email: input.email,
password: hashedPassword,
salt: salt,
},
});
}),
}); });

View File

@@ -1,4 +1,4 @@
import bcrypt from "bcrypt"; import bcrypt from 'bcrypt';
export const hashPassword = (password: string, salt: string) => { export const hashPassword = (password: string, salt: string) => {
return bcrypt.hashSync(password, salt); return bcrypt.hashSync(password, salt);