requestEmailVerificationCode.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Request, Response, NextFunction } from "express";
  2. import createHttpError from "http-errors";
  3. import HttpCode from "@server/types/HttpCode";
  4. import { response } from "@server/utils";
  5. import { User } from "@server/db/schema";
  6. import { sendEmailVerificationCode } from "./sendEmailVerificationCode";
  7. export type RequestEmailVerificationCodeResponse = {
  8. codeSent: boolean;
  9. };
  10. export async function requestEmailVerificationCode(
  11. req: Request,
  12. res: Response,
  13. next: NextFunction,
  14. ): Promise<any> {
  15. try {
  16. const user = req.user as User;
  17. if (user.emailVerified) {
  18. return next(
  19. createHttpError(
  20. HttpCode.BAD_REQUEST,
  21. "Email is already verified",
  22. ),
  23. );
  24. }
  25. await sendEmailVerificationCode(user.email, user.userId);
  26. return response<RequestEmailVerificationCodeResponse>(res, {
  27. data: {
  28. codeSent: true,
  29. },
  30. status: HttpCode.OK,
  31. success: true,
  32. error: false,
  33. message: `Email verification code sent to ${user.email}`,
  34. });
  35. } catch (error) {
  36. return next(
  37. createHttpError(
  38. HttpCode.INTERNAL_SERVER_ERROR,
  39. "Failed to send email verification code",
  40. ),
  41. );
  42. }
  43. }
  44. export default requestEmailVerificationCode;