requestEmailVerificationCode.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 "../../auth/sendEmailVerificationCode";
  7. import config from "@server/config";
  8. import logger from "@server/logger";
  9. export type RequestEmailVerificationCodeResponse = {
  10. codeSent: boolean;
  11. };
  12. export async function requestEmailVerificationCode(
  13. req: Request,
  14. res: Response,
  15. next: NextFunction
  16. ): Promise<any> {
  17. if (!config.flags?.require_email_verification) {
  18. return next(
  19. createHttpError(
  20. HttpCode.BAD_REQUEST,
  21. "Email verification is not enabled"
  22. )
  23. );
  24. }
  25. try {
  26. const user = req.user as User;
  27. if (user.emailVerified) {
  28. return next(
  29. createHttpError(
  30. HttpCode.BAD_REQUEST,
  31. "Email is already verified"
  32. )
  33. );
  34. }
  35. await sendEmailVerificationCode(user.email, user.userId);
  36. return response<RequestEmailVerificationCodeResponse>(res, {
  37. data: {
  38. codeSent: true
  39. },
  40. status: HttpCode.OK,
  41. success: true,
  42. error: false,
  43. message: `Email verification code sent to ${user.email}`
  44. });
  45. } catch (error) {
  46. logger.error(error);
  47. return next(
  48. createHttpError(
  49. HttpCode.INTERNAL_SERVER_ERROR,
  50. "Failed to send email verification code"
  51. )
  52. );
  53. }
  54. }
  55. export default requestEmailVerificationCode;