diff --git a/src/controllers/09-verification-controller.ts b/src/controllers/09-verification-controller.ts index cc39433..692a5bf 100644 --- a/src/controllers/09-verification-controller.ts +++ b/src/controllers/09-verification-controller.ts @@ -3,8 +3,10 @@ import prisma from "../db"; import nodemailer from "nodemailer"; import { notFoundError } from "../utils/error"; import { RequestWithLineUser } from "../interfaces/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; -type sendEmail = { +type SendEmail = { email: string; } & ({ legalPersonNo: string } | { citizenId: string }); @@ -13,6 +15,8 @@ type VerificationPayload = { otp: string; } & ({ legalPersonNo: string } | { citizenId: string }); +let emailTransport: ReturnType<(typeof nodemailer)["createTransport"]>; + @Route("/api/v1/verification") @Tags("Verification") export class verificationController extends Controller { @@ -23,7 +27,34 @@ export class verificationController extends Controller { } @Post("/send-otp") - public async sendOTP(@Body() body: sendEmail) { + public async sendOTP(@Body() body: SendEmail) { + if ( + ![ + process.env.SMTP_HOST, + process.env.SMTP_PORT, + process.env.SMTP_USER, + process.env.SMTP_PASS, + ].every(Boolean) + ) { + throw new HttpError( + HttpStatus.PRECONDITION_FAILED, + "SMTP not configured", + "smtpNotConfigured", + ); + } + + if (!emailTransport) { + emailTransport = nodemailer.createTransport({ + host: process.env.SMTP_HOST!, + port: +process.env.SMTP_PORT!, + secure: false, // true for port 465, false for other ports + auth: { + user: process.env.SMTP_USER!, + pass: process.env.SMTP_PASS!, + }, + }); + } + const generateOTP = Math.floor(100000 + Math.random() * 900000).toString(); const expiresTime = new Date(Date.now() + 5 * 60 * 1000); @@ -48,17 +79,7 @@ export class verificationController extends Controller { if (!dataCustomerBranch) throw notFoundError("Customer Branch"); - const fromData = nodemailer.createTransport({ - host: "smtp.gmail.com", - port: 587, - secure: false, // true for port 465, false for other ports - auth: { - user: process.env.SMTP_USER, - pass: process.env.SMTP_PASS, - }, - }); - - await fromData.sendMail({ + await emailTransport.sendMail({ from: process.env.SMTP_USER, to: body.email, subject: "Your OTP Code",