mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 20:13:49 +00:00
Implement confirm user functionality
This commit adds the necessary functionality to confirm a user's account. It includes the addition of a new column in the user table to track whether an account is confirmed or not, and the implementation of JWT for confirmation tokens. This commit integrates the SparkPost API as well as React Email to send dynamic emails for whatever purpose. Upon user registration, a confirmation email will be sent to the user.
This commit is contained in:
56
pages/api/users/confirm.ts
Normal file
56
pages/api/users/confirm.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { UserExtendedNextApiRequest } from '@/config/auth/types';
|
||||
import { verifyConfirmationToken } from '@/config/jwt';
|
||||
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
|
||||
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiResponse } from 'next';
|
||||
import { createRouter } from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||
import updateUserToBeConfirmedById from '@/services/User/updateUserToBeConfirmedById';
|
||||
|
||||
const ConfirmUserValidationSchema = z.object({ token: z.string() });
|
||||
|
||||
interface ConfirmUserRequest extends UserExtendedNextApiRequest {
|
||||
query: z.infer<typeof ConfirmUserValidationSchema>;
|
||||
}
|
||||
|
||||
const confirmUser = async (req: ConfirmUserRequest, res: NextApiResponse) => {
|
||||
const { token } = req.query;
|
||||
|
||||
const user = req.user!;
|
||||
const { id } = verifyConfirmationToken(token);
|
||||
|
||||
if (user.id !== id) {
|
||||
throw new ServerError('Could not confirm user.', 401);
|
||||
}
|
||||
|
||||
if (user.isAccountVerified) {
|
||||
throw new ServerError('User is already verified.', 400);
|
||||
}
|
||||
|
||||
await updateUserToBeConfirmedById(id);
|
||||
|
||||
res.status(200).json({
|
||||
message: 'User confirmed successfully.',
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
});
|
||||
};
|
||||
|
||||
const router = createRouter<
|
||||
ConfirmUserRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>();
|
||||
|
||||
router.get(
|
||||
getCurrentUser,
|
||||
validateRequest({ querySchema: ConfirmUserValidationSchema }),
|
||||
confirmUser,
|
||||
);
|
||||
|
||||
const handler = router.handler(NextConnectOptions);
|
||||
|
||||
export default handler;
|
||||
Reference in New Issue
Block a user