fosrl.pangolin/server/routers/auth/requestEmailVerificationCode.ts

73 lines
2 KiB
TypeScript
Raw Normal View History

2024-10-04 23:14:40 -04:00
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
2025-01-01 21:41:31 -05:00
import { response } from "@server/lib";
2025-03-23 17:11:48 -04:00
import { User } from "@server/db/schemas";
2024-12-21 21:01:12 -05:00
import { sendEmailVerificationCode } from "../../auth/sendEmailVerificationCode";
2025-01-01 21:41:31 -05:00
import config from "@server/lib/config";
2024-12-21 21:01:12 -05:00
import logger from "@server/logger";
2025-04-13 17:57:27 -04:00
import { UserType } from "@server/types/UserTypes";
2024-10-04 23:14:40 -04:00
export type RequestEmailVerificationCodeResponse = {
codeSent: boolean;
};
export async function requestEmailVerificationCode(
req: Request,
res: Response,
next: NextFunction
2024-10-04 23:14:40 -04:00
): Promise<any> {
if (!config.getRawConfig().flags?.require_email_verification) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Email verification is not enabled"
)
);
}
2024-10-04 23:14:40 -04:00
try {
const user = req.user as User;
2025-04-13 17:57:27 -04:00
if (user.type !== UserType.Internal) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Email verification is not supported for external users"
)
);
}
2024-10-04 23:14:40 -04:00
if (user.emailVerified) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Email is already verified"
)
2024-10-04 23:14:40 -04:00
);
}
2025-04-13 17:57:27 -04:00
await sendEmailVerificationCode(user.email!, user.userId);
2024-10-04 23:14:40 -04:00
return response<RequestEmailVerificationCodeResponse>(res, {
data: {
2024-12-21 21:01:12 -05:00
codeSent: true
2024-10-04 23:14:40 -04:00
},
status: HttpCode.OK,
success: true,
error: false,
2024-12-21 21:01:12 -05:00
message: `Email verification code sent to ${user.email}`
2024-10-04 23:14:40 -04:00
});
} catch (error) {
2024-12-21 21:01:12 -05:00
logger.error(error);
2024-10-04 23:14:40 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to send email verification code"
)
2024-10-04 23:14:40 -04:00
);
}
}
export default requestEmailVerificationCode;