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

138 lines
3.5 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 { z } from "zod";
import { fromError } from "zod-validation-error";
import HttpCode from "@server/types/HttpCode";
2025-01-01 21:41:31 -05:00
import { response } from "@server/lib";
2024-10-04 23:14:40 -04:00
import { db } from "@server/db";
import { User, emailVerificationCodes, users } from "@server/db/schema";
import { eq } from "drizzle-orm";
import { isWithinExpirationDate } from "oslo";
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";
2024-10-04 23:14:40 -04:00
2024-12-21 21:01:12 -05:00
export const verifyEmailBody = z
.object({
code: z.string()
})
.strict();
2024-10-04 23:14:40 -04:00
export type VerifyEmailBody = z.infer<typeof verifyEmailBody>;
export type VerifyEmailResponse = {
valid: boolean;
};
export async function verifyEmail(
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
const parsedBody = verifyEmailBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
2024-10-04 23:14:40 -04:00
);
}
const { code } = parsedBody.data;
const user = req.user as User;
if (user.emailVerified) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Email is already verified")
2024-10-04 23:14:40 -04:00
);
}
try {
const valid = await isValidCode(user, code);
if (valid) {
2024-12-24 16:00:02 -05:00
await db.transaction(async (trx) => {
await trx
.delete(emailVerificationCodes)
.where(eq(emailVerificationCodes.userId, user.userId));
2024-10-04 23:14:40 -04:00
2024-12-24 16:00:02 -05:00
await trx
.update(users)
.set({
emailVerified: true
})
.where(eq(users.userId, user.userId));
});
2024-10-12 23:00:36 -04:00
} else {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Email verification code incorrect. Email: ${user.email}. IP: ${req.ip}.`
);
}
2024-10-12 23:00:36 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid verification code"
)
2024-10-12 23:00:36 -04:00
);
2024-10-04 23:14:40 -04:00
}
return response<VerifyEmailResponse>(res, {
success: true,
error: false,
2024-10-12 23:00:36 -04:00
message: "Email verified",
2024-10-04 23:14:40 -04:00
status: HttpCode.OK,
data: {
2024-12-21 21:01:12 -05:00
valid
}
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 verify email"
)
2024-10-04 23:14:40 -04:00
);
}
}
export default verifyEmail;
async function isValidCode(user: User, code: string): Promise<boolean> {
const codeRecord = await db
.select()
.from(emailVerificationCodes)
2024-10-13 17:13:47 -04:00
.where(eq(emailVerificationCodes.userId, user.userId))
2024-10-04 23:14:40 -04:00
.limit(1);
if (user.email !== codeRecord[0].email) {
return false;
}
if (codeRecord.length === 0) {
return false;
}
if (codeRecord[0].code !== code) {
return false;
}
if (!isWithinExpirationDate(new Date(codeRecord[0].expiresAt))) {
return false;
}
return true;
}