mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 20:13:49 +00:00
Feat: Add edit user functionality
This commit is contained in:
@@ -1,120 +1,17 @@
|
||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||
import { NextPage } from 'next';
|
||||
|
||||
import { FC, useState } from 'react';
|
||||
import { Switch, Tab } from '@headlessui/react';
|
||||
import { Tab } from '@headlessui/react';
|
||||
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 { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import AccountInfo from '@/components/Account/AccountInfo';
|
||||
|
||||
interface AccountPageProps {
|
||||
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 }) => {
|
||||
return (
|
||||
<>
|
||||
@@ -126,7 +23,7 @@ const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
|
||||
/>
|
||||
</Head>
|
||||
<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="avatar">
|
||||
<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">
|
||||
<Tab.Group>
|
||||
<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
|
||||
</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
|
||||
</Tab>
|
||||
</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,
|
||||
payload: { emailIsTaken: !!email },
|
||||
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 { createRouter } from 'next-connect';
|
||||
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 findUserByUsername from '@/services/User/findUserByUsername';
|
||||
import findUserByEmail from '@/services/User/findUserByEmail';
|
||||
|
||||
Reference in New Issue
Block a user