mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
update: add delete user api route, AuthProvider extracted from App.tsx
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import UserContext from '@/contexts/UserContext';
|
||||
import { AccountPageState, AccountPageAction } from '@/reducers/accountPageReducer';
|
||||
|
||||
import { Switch } from '@headlessui/react';
|
||||
import { useRouter } from 'next/router';
|
||||
import { Dispatch, FunctionComponent, useRef } from 'react';
|
||||
import { Dispatch, FunctionComponent, useContext, useRef } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
interface DeleteAccountProps {
|
||||
pageState: AccountPageState;
|
||||
@@ -13,6 +16,26 @@ const DeleteAccount: FunctionComponent<DeleteAccountProps> = ({
|
||||
}) => {
|
||||
const deleteRef = useRef<null | HTMLDialogElement>(null);
|
||||
const router = useRouter();
|
||||
const { user, mutate } = useContext(UserContext);
|
||||
|
||||
const onDeleteSubmit = async () => {
|
||||
deleteRef.current!.close();
|
||||
const loadingToast = toast.loading(
|
||||
'Deleting your account. We are sad to see you go. 😭',
|
||||
);
|
||||
const request = await fetch(`/api/users/${user?.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!request.ok) {
|
||||
throw new Error('Could not delete that user.');
|
||||
}
|
||||
|
||||
toast.remove(loadingToast);
|
||||
toast.success('Deleted your account. Goodbye. 😓');
|
||||
await mutate!();
|
||||
router.push('/');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card w-full space-y-4">
|
||||
@@ -49,10 +72,7 @@ const DeleteAccount: FunctionComponent<DeleteAccountProps> = ({
|
||||
<div className="modal-action flex-col space-x-0 space-y-3">
|
||||
<button
|
||||
className="btn-error btn-sm btn w-full"
|
||||
onClick={async () => {
|
||||
deleteRef.current!.close();
|
||||
await router.replace('/api/users/logout');
|
||||
}}
|
||||
onClick={onDeleteSubmit}
|
||||
>
|
||||
Okay, delete my account
|
||||
</button>
|
||||
|
||||
@@ -72,14 +72,14 @@ const Security: FunctionComponent<SecurityProps> = ({ dispatch, pageState }) =>
|
||||
formValidationSchema={register('password')}
|
||||
/>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="password">Confirm Password</FormLabel>
|
||||
<FormLabel htmlFor="confirm-password">Confirm Password</FormLabel>
|
||||
<FormError>{formState.errors.confirmPassword?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
type="password"
|
||||
disabled={!pageState.securityOpen || formState.isSubmitting}
|
||||
error={!!formState.errors.confirmPassword}
|
||||
id="password"
|
||||
id="confirm-password"
|
||||
formValidationSchema={register('confirmPassword')}
|
||||
/>
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const CustomToast: FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const alertType = toastToClassName(t.type);
|
||||
return (
|
||||
<div
|
||||
className={`alert ${alertType} flex w-11/12 items-center justify-between shadow-lg animate-in fade-in duration-200 lg:w-4/12`}
|
||||
className={`alert ${alertType} flex w-full items-center justify-between shadow-lg animate-in fade-in duration-200 lg:w-3/12`}
|
||||
>
|
||||
<p className="w-full">{resolveValue(t.message, t)}</p>
|
||||
{t.type !== 'loading' && (
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import useUser from '@/hooks/auth/useUser';
|
||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||
import { createContext } from 'react';
|
||||
import { z } from 'zod';
|
||||
|
||||
const UserContext = createContext<{
|
||||
user?: z.infer<typeof GetUserSchema>;
|
||||
error?: unknown;
|
||||
isLoading: boolean;
|
||||
mutate?: ReturnType<typeof useUser>['mutate'];
|
||||
}>({ isLoading: true });
|
||||
|
||||
export default UserContext;
|
||||
24
src/contexts/UserContext.tsx
Normal file
24
src/contexts/UserContext.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import useUser from '@/hooks/auth/useUser';
|
||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||
import { ReactNode, createContext } from 'react';
|
||||
import { z } from 'zod';
|
||||
|
||||
const UserContext = createContext<{
|
||||
user?: z.infer<typeof GetUserSchema>;
|
||||
error?: unknown;
|
||||
isLoading: boolean;
|
||||
mutate?: ReturnType<typeof useUser>['mutate'];
|
||||
}>({ isLoading: true });
|
||||
|
||||
export default UserContext;
|
||||
|
||||
type AuthProviderComponent = (props: { children: ReactNode }) => JSX.Element;
|
||||
|
||||
export const AuthProvider: AuthProviderComponent = ({ children }) => {
|
||||
const { error, isLoading, mutate, user } = useUser();
|
||||
return (
|
||||
<UserContext.Provider value={{ isLoading, error, mutate, user }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -46,7 +46,12 @@ const useUser = () => {
|
||||
return parsedPayload.data;
|
||||
});
|
||||
|
||||
return { user, isLoading, error: error as unknown, mutate };
|
||||
return {
|
||||
mutate,
|
||||
isLoading,
|
||||
user: error ? undefined : user,
|
||||
error: error as unknown,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUser;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import UserContext from '@/contexts/UserContext';
|
||||
import UserContext, { AuthProvider } from '@/contexts/UserContext';
|
||||
|
||||
import '@/styles/globals.css';
|
||||
import type { AppProps } from 'next/app';
|
||||
@@ -13,15 +13,12 @@ import Layout from '@/components/ui/Layout';
|
||||
import useUser from '@/hooks/auth/useUser';
|
||||
import CustomToast from '@/components/ui/CustomToast';
|
||||
|
||||
const spaceGrotesk = Space_Grotesk({
|
||||
subsets: ['latin'],
|
||||
});
|
||||
const spaceGrotesk = Space_Grotesk({ subsets: ['latin'] });
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
const App = ({ Component, pageProps }: AppProps) => {
|
||||
useEffect(() => {
|
||||
themeChange(false);
|
||||
}, []);
|
||||
const { user, isLoading, error, mutate } = useUser();
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -38,15 +35,17 @@ export default function App({ Component, pageProps }: AppProps) {
|
||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0"
|
||||
/>
|
||||
</Head>
|
||||
<UserContext.Provider value={{ user, isLoading, error, mutate }}>
|
||||
<AuthProvider>
|
||||
<Layout>
|
||||
<CustomToast>
|
||||
<Component {...pageProps} />
|
||||
</CustomToast>
|
||||
</Layout>
|
||||
</UserContext.Provider>
|
||||
</AuthProvider>
|
||||
|
||||
<Analytics />
|
||||
</>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default App;
|
||||
|
||||
@@ -4,6 +4,7 @@ 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 deleteUserById from '@/services/User/deleteUserById';
|
||||
import findUserByEmail from '@/services/User/findUserByEmail';
|
||||
import findUserById from '@/services/User/findUserById';
|
||||
import findUserByUsername from '@/services/User/findUserByUsername';
|
||||
@@ -21,11 +22,12 @@ const EditUserSchema = BaseCreateUserSchema.pick({
|
||||
lastName: true,
|
||||
});
|
||||
|
||||
interface EditUserRequest extends UserExtendedNextApiRequest {
|
||||
interface UserRouteRequest extends UserExtendedNextApiRequest {
|
||||
query: { id: string };
|
||||
}
|
||||
|
||||
interface EditUserRequest extends UserRouteRequest {
|
||||
body: z.infer<typeof EditUserSchema>;
|
||||
query: {
|
||||
id: string;
|
||||
};
|
||||
}
|
||||
|
||||
const checkIfUserCanEditUser = async (
|
||||
@@ -41,7 +43,7 @@ const checkIfUserCanEditUser = async (
|
||||
}
|
||||
|
||||
if (authenticatedUser.id !== userToUpdate.id) {
|
||||
throw new ServerError('You are not permitted to edit this user', 403);
|
||||
throw new ServerError('You are not permitted to modify this user', 403);
|
||||
}
|
||||
|
||||
await next();
|
||||
@@ -88,6 +90,24 @@ const editUser = async (
|
||||
});
|
||||
};
|
||||
|
||||
const deleteUser = async (
|
||||
req: UserRouteRequest,
|
||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||
) => {
|
||||
const { id } = req.query;
|
||||
const deletedUser = await deleteUserById(id);
|
||||
|
||||
if (!deletedUser) {
|
||||
throw new ServerError('Could not find a user with that id.', 400);
|
||||
}
|
||||
|
||||
res.send({
|
||||
message: 'Successfully deleted user.',
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
});
|
||||
};
|
||||
|
||||
const router = createRouter<
|
||||
EditUserRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
@@ -103,6 +123,15 @@ router.put(
|
||||
editUser,
|
||||
);
|
||||
|
||||
router.delete(
|
||||
getCurrentUser,
|
||||
validateRequest({
|
||||
querySchema: z.object({ id: z.string().cuid() }),
|
||||
}),
|
||||
checkIfUserCanEditUser,
|
||||
deleteUser,
|
||||
);
|
||||
|
||||
const handler = router.handler(NextConnectOptions);
|
||||
|
||||
export default handler;
|
||||
@@ -5,7 +5,6 @@ import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
|
||||
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { UpdatePasswordSchema } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiResponse } from 'next';
|
||||
import { createRouter } from 'next-connect';
|
||||
@@ -23,26 +22,15 @@ const updatePassword = async (
|
||||
const hash = await hashPassword(password);
|
||||
|
||||
const user = req.user!;
|
||||
const updatedUser: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
|
||||
await DBClient.instance.user.update({
|
||||
data: { hash },
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
accountIsVerified: true,
|
||||
},
|
||||
});
|
||||
|
||||
res.json({
|
||||
message: 'Updated user password.',
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
payload: updatedUser,
|
||||
});
|
||||
};
|
||||
const router = createRouter<
|
||||
|
||||
@@ -13,7 +13,7 @@ interface SendEditUserRequestArgs {
|
||||
}
|
||||
|
||||
const sendEditUserRequest = async ({ user, data }: SendEditUserRequestArgs) => {
|
||||
const response = await fetch(`/api/users/${user!.id}/edit`, {
|
||||
const response = await fetch(`/api/users/${user!.id}`, {
|
||||
body: JSON.stringify(data),
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { UpdatePasswordSchema } from '@/services/User/schema/CreateUserValidationSchemas';
|
||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -21,13 +20,7 @@ const sendUpdatePasswordRequest = async (data: z.infer<typeof UpdatePasswordSche
|
||||
throw new Error('API response validation failed.');
|
||||
}
|
||||
|
||||
const parsedPayload = GetUserSchema.safeParse(parsed.data.payload);
|
||||
|
||||
if (!parsedPayload.success) {
|
||||
throw new Error('API payload validation failed.');
|
||||
}
|
||||
|
||||
return parsedPayload.data;
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
export default sendUpdatePasswordRequest;
|
||||
|
||||
25
src/services/User/deleteUserById.ts
Normal file
25
src/services/User/deleteUserById.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { z } from 'zod';
|
||||
import GetUserSchema from './schema/GetUserSchema';
|
||||
|
||||
const deleteUserById = async (id: string) => {
|
||||
const deletedUser: z.infer<typeof GetUserSchema> | null =
|
||||
await DBClient.instance.user.delete({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
createdAt: true,
|
||||
accountIsVerified: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return deletedUser;
|
||||
};
|
||||
|
||||
export default deleteUserById;
|
||||
Reference in New Issue
Block a user