mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Feat: Add edit user functionality
This commit is contained in:
166
src/components/Account/AccountInfo.tsx
Normal file
166
src/components/Account/AccountInfo.tsx
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
import validateEmail from '@/requests/valdiateEmail';
|
||||||
|
import validateUsername from '@/requests/validateUsername';
|
||||||
|
import { BaseCreateUserSchema } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||||
|
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||||
|
import { Switch } from '@headlessui/react';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useRouter } from 'next/router';
|
||||||
|
import { FC, useState } from 'react';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import FormError from '../ui/forms/FormError';
|
||||||
|
import FormInfo from '../ui/forms/FormInfo';
|
||||||
|
import FormLabel from '../ui/forms/FormLabel';
|
||||||
|
import FormTextInput from '../ui/forms/FormTextInput';
|
||||||
|
|
||||||
|
interface AccountInfoProps {
|
||||||
|
user: z.infer<typeof GetUserSchema>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AccountInfo: FC<AccountInfoProps> = ({ user }) => {
|
||||||
|
const router = useRouter();
|
||||||
|
const EditUserSchema = BaseCreateUserSchema.pick({
|
||||||
|
username: true,
|
||||||
|
email: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
}).extend({
|
||||||
|
email: z
|
||||||
|
.string()
|
||||||
|
.email({ message: 'Email must be a valid email address.' })
|
||||||
|
.refine(
|
||||||
|
async (email) => {
|
||||||
|
if (user.email === email) return true;
|
||||||
|
return validateEmail(email);
|
||||||
|
},
|
||||||
|
{ message: 'Email is already taken.' },
|
||||||
|
),
|
||||||
|
username: z
|
||||||
|
.string()
|
||||||
|
.min(1, { message: 'Username must not be empty.' })
|
||||||
|
.max(20, { message: 'Username must be less than 20 characters.' })
|
||||||
|
.refine(
|
||||||
|
async (username) => {
|
||||||
|
if (user.username === username) return true;
|
||||||
|
return validateUsername(username);
|
||||||
|
},
|
||||||
|
{ message: 'Username is already taken.' },
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { register, handleSubmit, formState, reset } = useForm<
|
||||||
|
z.infer<typeof EditUserSchema>
|
||||||
|
>({
|
||||||
|
resolver: zodResolver(EditUserSchema),
|
||||||
|
defaultValues: {
|
||||||
|
username: user.username,
|
||||||
|
email: user.email,
|
||||||
|
firstName: user.firstName,
|
||||||
|
lastName: user.lastName,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const [inEditMode, setInEditMode] = useState(false);
|
||||||
|
|
||||||
|
const onSubmit = async (data: z.infer<typeof EditUserSchema>) => {
|
||||||
|
const response = await fetch(`/api/users/${user.id}/edit`, {
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Something went wrong.');
|
||||||
|
}
|
||||||
|
|
||||||
|
await response.json();
|
||||||
|
|
||||||
|
router.reload();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-8">
|
||||||
|
<div className="flex flex-col space-y-3">
|
||||||
|
<form
|
||||||
|
className="form-control space-y-5"
|
||||||
|
onSubmit={handleSubmit(onSubmit)}
|
||||||
|
noValidate
|
||||||
|
>
|
||||||
|
<label className="label w-36 cursor-pointer p-0">
|
||||||
|
<span className="label-text font-bold uppercase">Enable Edit</span>
|
||||||
|
<Switch
|
||||||
|
checked={inEditMode}
|
||||||
|
className="toggle"
|
||||||
|
onClick={() => {
|
||||||
|
setInEditMode((editMode) => !editMode);
|
||||||
|
reset();
|
||||||
|
}}
|
||||||
|
id="edit-toggle"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="username">Username</FormLabel>
|
||||||
|
<FormError>{formState.errors.username?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<FormTextInput
|
||||||
|
type="text"
|
||||||
|
disabled={!inEditMode || formState.isSubmitting}
|
||||||
|
error={!!formState.errors.username}
|
||||||
|
id="username"
|
||||||
|
formValidationSchema={register('username')}
|
||||||
|
/>
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="email">Email</FormLabel>
|
||||||
|
<FormError>{formState.errors.email?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<FormTextInput
|
||||||
|
type="email"
|
||||||
|
disabled={!inEditMode || formState.isSubmitting}
|
||||||
|
error={!!formState.errors.email}
|
||||||
|
id="email"
|
||||||
|
formValidationSchema={register('email')}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex space-x-3">
|
||||||
|
<div className="w-1/2">
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="firstName">First Name</FormLabel>
|
||||||
|
<FormError>{formState.errors.firstName?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<FormTextInput
|
||||||
|
type="text"
|
||||||
|
disabled={!inEditMode || formState.isSubmitting}
|
||||||
|
error={!!formState.errors.firstName}
|
||||||
|
id="firstName"
|
||||||
|
formValidationSchema={register('firstName')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="w-1/2">
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="lastName">Last Name</FormLabel>
|
||||||
|
<FormError>{formState.errors.lastName?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<FormTextInput
|
||||||
|
type="text"
|
||||||
|
disabled={!inEditMode || formState.isSubmitting}
|
||||||
|
error={!!formState.errors.lastName}
|
||||||
|
id="lastName"
|
||||||
|
formValidationSchema={register('lastName')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{inEditMode && (
|
||||||
|
<button className="btn-primary btn w-full" type="submit">
|
||||||
|
Save Changes
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AccountInfo;
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
import sendRegisterUserRequest from '@/requests/sendRegisterUserRequest';
|
import sendRegisterUserRequest from '@/requests/sendRegisterUserRequest';
|
||||||
import CreateUserValidationSchema, {
|
import { CreateUserValidationSchemaWithUsernameAndEmailCheck } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||||
CreateUserValidationSchemaWithUsernameAndEmailCheck,
|
|
||||||
} from '@/services/User/schema/CreateUserValidationSchema';
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useRouter } from 'next/router';
|
import { useRouter } from 'next/router';
|
||||||
import { FC, useState } from 'react';
|
import { FC, useState } from 'react';
|
||||||
@@ -19,13 +17,15 @@ import FormTextInput from './ui/forms/FormTextInput';
|
|||||||
const RegisterUserForm: FC = () => {
|
const RegisterUserForm: FC = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { reset, register, handleSubmit, formState } = useForm<
|
const { reset, register, handleSubmit, formState } = useForm<
|
||||||
z.infer<typeof CreateUserValidationSchema>
|
z.infer<typeof CreateUserValidationSchemaWithUsernameAndEmailCheck>
|
||||||
>({ resolver: zodResolver(CreateUserValidationSchemaWithUsernameAndEmailCheck) });
|
>({ resolver: zodResolver(CreateUserValidationSchemaWithUsernameAndEmailCheck) });
|
||||||
|
|
||||||
const { errors } = formState;
|
const { errors } = formState;
|
||||||
const [serverResponseError, setServerResponseError] = useState('');
|
const [serverResponseError, setServerResponseError] = useState('');
|
||||||
|
|
||||||
const onSubmit = async (data: z.infer<typeof CreateUserValidationSchema>) => {
|
const onSubmit = async (
|
||||||
|
data: z.infer<typeof CreateUserValidationSchemaWithUsernameAndEmailCheck>,
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
await sendRegisterUserRequest(data);
|
await sendRegisterUserRequest(data);
|
||||||
reset();
|
reset();
|
||||||
|
|||||||
@@ -1,120 +1,17 @@
|
|||||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||||
import { NextPage } from 'next';
|
import { NextPage } from 'next';
|
||||||
|
|
||||||
import { FC, useState } from 'react';
|
import { Tab } from '@headlessui/react';
|
||||||
import { Switch, Tab } from '@headlessui/react';
|
|
||||||
import Head from 'next/head';
|
import Head from 'next/head';
|
||||||
import FormInfo from '@/components/ui/forms/FormInfo';
|
|
||||||
import FormLabel from '@/components/ui/forms/FormLabel';
|
|
||||||
import FormError from '@/components/ui/forms/FormError';
|
|
||||||
import FormTextInput from '@/components/ui/forms/FormTextInput';
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||||
import { useForm } from 'react-hook-form';
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import DBClient from '@/prisma/DBClient';
|
import DBClient from '@/prisma/DBClient';
|
||||||
|
import AccountInfo from '@/components/Account/AccountInfo';
|
||||||
|
|
||||||
interface AccountPageProps {
|
interface AccountPageProps {
|
||||||
user: z.infer<typeof GetUserSchema>;
|
user: z.infer<typeof GetUserSchema>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const AccountInfo: FC<{
|
|
||||||
user: z.infer<typeof GetUserSchema>;
|
|
||||||
}> = ({ user }) => {
|
|
||||||
const { register, handleSubmit, formState, reset } = useForm<
|
|
||||||
z.infer<typeof GetUserSchema>
|
|
||||||
>({
|
|
||||||
resolver: zodResolver(GetUserSchema),
|
|
||||||
defaultValues: {
|
|
||||||
username: user.username,
|
|
||||||
email: user.email,
|
|
||||||
firstName: user.firstName,
|
|
||||||
lastName: user.lastName,
|
|
||||||
dateOfBirth: user.dateOfBirth,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const [inEditMode, setInEditMode] = useState(false);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="mt-8">
|
|
||||||
<div className="flex flex-col space-y-3">
|
|
||||||
<div className="flex flex-row">
|
|
||||||
<label className="label-text" htmlFor="edit-toggle">
|
|
||||||
Edit Account Info
|
|
||||||
</label>
|
|
||||||
<Switch
|
|
||||||
checked={inEditMode}
|
|
||||||
className="toggle"
|
|
||||||
onClick={() => {
|
|
||||||
setInEditMode((editMode) => !editMode);
|
|
||||||
reset();
|
|
||||||
}}
|
|
||||||
id="edit-toggle"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form className="space-y-5" onSubmit={handleSubmit(() => {})}>
|
|
||||||
<div>
|
|
||||||
<FormInfo>
|
|
||||||
<FormLabel htmlFor="username">Username</FormLabel>
|
|
||||||
<FormError>{formState.errors.username?.message}</FormError>
|
|
||||||
</FormInfo>
|
|
||||||
<FormTextInput
|
|
||||||
type="text"
|
|
||||||
disabled={!inEditMode || formState.isSubmitting}
|
|
||||||
error={!!formState.errors.username}
|
|
||||||
id="username"
|
|
||||||
formValidationSchema={register('username')}
|
|
||||||
/>
|
|
||||||
<FormInfo>
|
|
||||||
<FormLabel htmlFor="email">Email</FormLabel>
|
|
||||||
<FormError>{''}</FormError>
|
|
||||||
</FormInfo>
|
|
||||||
<FormTextInput
|
|
||||||
type="email"
|
|
||||||
disabled={!inEditMode || formState.isSubmitting}
|
|
||||||
error={!!formState.errors.email}
|
|
||||||
id="email"
|
|
||||||
formValidationSchema={register('email')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="flex space-x-3">
|
|
||||||
<div className="w-1/2">
|
|
||||||
<FormInfo>
|
|
||||||
<FormLabel htmlFor="firstName">First Name</FormLabel>
|
|
||||||
<FormError>{formState.errors.firstName?.message}</FormError>
|
|
||||||
</FormInfo>
|
|
||||||
<FormTextInput
|
|
||||||
type="text"
|
|
||||||
disabled={!inEditMode || formState.isSubmitting}
|
|
||||||
error={!!formState.errors.firstName}
|
|
||||||
id="firstName"
|
|
||||||
formValidationSchema={register('firstName')}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="w-1/2">
|
|
||||||
<FormInfo>
|
|
||||||
<FormLabel htmlFor="lastName">Last Name</FormLabel>
|
|
||||||
<FormError>{formState.errors.lastName?.message}</FormError>
|
|
||||||
</FormInfo>
|
|
||||||
<FormTextInput
|
|
||||||
type="text"
|
|
||||||
disabled={!inEditMode || formState.isSubmitting}
|
|
||||||
error={!!formState.errors.lastName}
|
|
||||||
id="lastName"
|
|
||||||
formValidationSchema={register('lastName')}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{inEditMode && <button className="btn-primary btn w-full">Save Changes</button>}
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
|
const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -126,7 +23,7 @@ const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
|
|||||||
/>
|
/>
|
||||||
</Head>
|
</Head>
|
||||||
<div className="flex h-full flex-col items-center bg-base-300">
|
<div className="flex h-full flex-col items-center bg-base-300">
|
||||||
<div className="m-12 flex w-9/12 flex-col items-center justify-center space-y-3">
|
<div className="m-12 flex w-11/12 flex-col items-center justify-center space-y-3 lg:w-7/12">
|
||||||
<div className="flex flex-col items-center space-y-3">
|
<div className="flex flex-col items-center space-y-3">
|
||||||
<div className="avatar">
|
<div className="avatar">
|
||||||
<div className="bg-base-black w-24 rounded-full bg-slate-700" />
|
<div className="bg-base-black w-24 rounded-full bg-slate-700" />
|
||||||
@@ -141,10 +38,13 @@ const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
|
|||||||
<div className="w-full">
|
<div className="w-full">
|
||||||
<Tab.Group>
|
<Tab.Group>
|
||||||
<Tab.List className="tabs tabs-boxed items-center justify-center rounded-2xl">
|
<Tab.List className="tabs tabs-boxed items-center justify-center rounded-2xl">
|
||||||
<Tab className="tab tab-md w-1/2 uppercase ui-selected:tab-active">
|
<Tab className="tab tab-md w-1/3 uppercase ui-selected:tab-active">
|
||||||
Account Info
|
Account Info
|
||||||
</Tab>
|
</Tab>
|
||||||
<Tab className="tab tab-md w-1/2 uppercase ui-selected:tab-active">
|
<Tab className="tab tab-md w-1/3 uppercase ui-selected:tab-active">
|
||||||
|
Security
|
||||||
|
</Tab>
|
||||||
|
<Tab className="tab tab-md w-1/3 uppercase ui-selected:tab-active">
|
||||||
Your Posts
|
Your Posts
|
||||||
</Tab>
|
</Tab>
|
||||||
</Tab.List>
|
</Tab.List>
|
||||||
|
|||||||
108
src/pages/api/users/[id]/edit.ts
Normal file
108
src/pages/api/users/[id]/edit.ts
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
import { UserExtendedNextApiRequest } from '@/config/auth/types';
|
||||||
|
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
|
||||||
|
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
|
||||||
|
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||||
|
import ServerError from '@/config/util/ServerError';
|
||||||
|
import DBClient from '@/prisma/DBClient';
|
||||||
|
import findUserByEmail from '@/services/User/findUserByEmail';
|
||||||
|
import findUserById from '@/services/User/findUserById';
|
||||||
|
import findUserByUsername from '@/services/User/findUserByUsername';
|
||||||
|
import { BaseCreateUserSchema } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||||
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
|
|
||||||
|
import { NextApiResponse } from 'next';
|
||||||
|
import { NextHandler, createRouter } from 'next-connect';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const EditUserSchema = BaseCreateUserSchema.pick({
|
||||||
|
username: true,
|
||||||
|
email: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
interface EditUserRequest extends UserExtendedNextApiRequest {
|
||||||
|
body: z.infer<typeof EditUserSchema>;
|
||||||
|
query: {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkIfUserCanEditUser = async (
|
||||||
|
req: EditUserRequest,
|
||||||
|
res: NextApiResponse,
|
||||||
|
next: NextHandler,
|
||||||
|
) => {
|
||||||
|
const authenticatedUser = req.user!;
|
||||||
|
|
||||||
|
const userToUpdate = await findUserById(req.query.id);
|
||||||
|
if (!userToUpdate) {
|
||||||
|
throw new ServerError('User not found', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (authenticatedUser.id !== userToUpdate.id) {
|
||||||
|
throw new ServerError('You are not permitted to edit this user', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
};
|
||||||
|
|
||||||
|
const editUser = async (
|
||||||
|
req: EditUserRequest,
|
||||||
|
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||||
|
) => {
|
||||||
|
const { email, firstName, lastName, username } = req.body;
|
||||||
|
|
||||||
|
const [usernameIsTaken, emailIsTaken] = await Promise.all([
|
||||||
|
findUserByUsername(username),
|
||||||
|
findUserByEmail(email),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const emailChanged = req.user!.email !== email;
|
||||||
|
const usernameChanged = req.user!.username !== username;
|
||||||
|
|
||||||
|
if (emailIsTaken && emailChanged) {
|
||||||
|
throw new ServerError('Email is already taken', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (usernameIsTaken && usernameChanged) {
|
||||||
|
throw new ServerError('Username is already taken', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedUser = await DBClient.instance.user.update({
|
||||||
|
where: { id: req.user!.id },
|
||||||
|
data: {
|
||||||
|
email,
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
username,
|
||||||
|
accountIsVerified: emailChanged ? false : undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
message: 'User edited successfully',
|
||||||
|
payload: updatedUser,
|
||||||
|
success: true,
|
||||||
|
statusCode: 200,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const router = createRouter<
|
||||||
|
EditUserRequest,
|
||||||
|
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||||
|
>();
|
||||||
|
|
||||||
|
router.put(
|
||||||
|
getCurrentUser,
|
||||||
|
validateRequest({
|
||||||
|
bodySchema: EditUserSchema,
|
||||||
|
querySchema: z.object({ id: z.string().uuid() }),
|
||||||
|
}),
|
||||||
|
checkIfUserCanEditUser,
|
||||||
|
editUser,
|
||||||
|
);
|
||||||
|
|
||||||
|
const handler = router.handler(NextConnectOptions);
|
||||||
|
|
||||||
|
export default handler;
|
||||||
@@ -29,7 +29,7 @@ const checkEmail = async (req: NextApiRequest, res: NextApiResponse) => {
|
|||||||
success: true,
|
success: true,
|
||||||
payload: { emailIsTaken: !!email },
|
payload: { emailIsTaken: !!email },
|
||||||
statusCode: 200,
|
statusCode: 200,
|
||||||
message: 'Getting username availability.',
|
message: 'Getting email availability.',
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { z } from 'zod';
|
|||||||
import ServerError from '@/config/util/ServerError';
|
import ServerError from '@/config/util/ServerError';
|
||||||
import { createRouter } from 'next-connect';
|
import { createRouter } from 'next-connect';
|
||||||
import createNewUser from '@/services/User/createNewUser';
|
import createNewUser from '@/services/User/createNewUser';
|
||||||
import CreateUserValidationSchema from '@/services/User/schema/CreateUserValidationSchema';
|
import { CreateUserValidationSchema } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||||
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
|
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
|
||||||
import findUserByUsername from '@/services/User/findUserByUsername';
|
import findUserByUsername from '@/services/User/findUserByUsername';
|
||||||
import findUserByEmail from '@/services/User/findUserByEmail';
|
import findUserByEmail from '@/services/User/findUserByEmail';
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import CreateUserValidationSchema from '@/services/User/schema/CreateUserValidationSchema';
|
import { CreateUserValidationSchema } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
@@ -6,9 +6,7 @@ import { z } from 'zod';
|
|||||||
async function sendRegisterUserRequest(data: z.infer<typeof CreateUserValidationSchema>) {
|
async function sendRegisterUserRequest(data: z.infer<typeof CreateUserValidationSchema>) {
|
||||||
const response = await fetch('/api/users/register', {
|
const response = await fetch('/api/users/register', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: { 'Content-Type': 'application/json' },
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(data),
|
body: JSON.stringify(data),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -12,14 +12,14 @@ const validateEmail = async (email: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsedPayload = z
|
const parsedPayload = z
|
||||||
.object({ usernameIsTaken: z.boolean() })
|
.object({ emailIsTaken: z.boolean() })
|
||||||
.safeParse(parsed.data.payload);
|
.safeParse(parsed.data.payload);
|
||||||
|
|
||||||
if (!parsedPayload.success) {
|
if (!parsedPayload.success) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return !parsedPayload.data.usernameIsTaken;
|
return !parsedPayload.data.emailIsTaken;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default validateEmail;
|
export default validateEmail;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { hashPassword } from '@/config/auth/passwordFns';
|
import { hashPassword } from '@/config/auth/passwordFns';
|
||||||
import DBClient from '@/prisma/DBClient';
|
import DBClient from '@/prisma/DBClient';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import CreateUserValidationSchema from './schema/CreateUserValidationSchema';
|
import { CreateUserValidationSchema } from './schema/CreateUserValidationSchemas';
|
||||||
import GetUserSchema from './schema/GetUserSchema';
|
import GetUserSchema from './schema/GetUserSchema';
|
||||||
|
|
||||||
const createNewUser = async ({
|
const createNewUser = async ({
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ import validateUsername from '@/requests/validateUsername';
|
|||||||
import sub from 'date-fns/sub';
|
import sub from 'date-fns/sub';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const minimumDateOfBirth = sub(new Date(), { years: 19 });
|
const MINIMUM_DATE_OF_BIRTH = sub(new Date(), { years: 19 });
|
||||||
const CreateUserValidationSchema = z.object({
|
|
||||||
// use special characters, numbers, and uppercase letters
|
export const BaseCreateUserSchema = z.object({
|
||||||
password: z
|
password: z
|
||||||
.string()
|
.string()
|
||||||
.min(8, { message: 'Password must be at least 8 characters.' })
|
.min(8, { message: 'Password must be at least 8 characters.' })
|
||||||
@@ -33,29 +33,25 @@ const CreateUserValidationSchema = z.object({
|
|||||||
.refine((lastName) => /^[a-zA-Z]+$/.test(lastName), {
|
.refine((lastName) => /^[a-zA-Z]+$/.test(lastName), {
|
||||||
message: 'Last name must only contain letters.',
|
message: 'Last name must only contain letters.',
|
||||||
}),
|
}),
|
||||||
dateOfBirth: z.string().refine(
|
dateOfBirth: z
|
||||||
(dateOfBirth) => {
|
.string()
|
||||||
const parsedDateOfBirth = new Date(dateOfBirth);
|
.refine((dateOfBirth) => new Date(dateOfBirth) <= MINIMUM_DATE_OF_BIRTH, {
|
||||||
return parsedDateOfBirth <= minimumDateOfBirth;
|
message: 'You must be at least 19 years old to register.',
|
||||||
},
|
}),
|
||||||
{ message: 'You must be at least 19 years old to register.' },
|
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
export default CreateUserValidationSchema.extend({
|
|
||||||
username: z
|
username: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, { message: 'Username must not be empty.' })
|
.min(1, { message: 'Username must not be empty.' })
|
||||||
.max(20, { message: 'Username must be less than 20 characters.' }),
|
.max(20, { message: 'Username must be less than 20 characters.' }),
|
||||||
|
|
||||||
email: z.string().email({ message: 'Email must be a valid email address.' }),
|
email: z.string().email({ message: 'Email must be a valid email address.' }),
|
||||||
}).refine((data) => data.password === data.confirmPassword, {
|
|
||||||
message: 'Passwords do not match.',
|
|
||||||
path: ['confirmPassword'],
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const CreateUserValidationSchema = BaseCreateUserSchema.refine(
|
||||||
|
(data) => data.password === data.confirmPassword,
|
||||||
|
{ message: 'Passwords do not match.', path: ['confirmPassword'] },
|
||||||
|
);
|
||||||
|
|
||||||
export const CreateUserValidationSchemaWithUsernameAndEmailCheck =
|
export const CreateUserValidationSchemaWithUsernameAndEmailCheck =
|
||||||
CreateUserValidationSchema.extend({
|
BaseCreateUserSchema.extend({
|
||||||
email: z
|
email: z
|
||||||
.string()
|
.string()
|
||||||
.email({ message: 'Email must be a valid email address.' })
|
.email({ message: 'Email must be a valid email address.' })
|
||||||
Reference in New Issue
Block a user