2024-10-04 23:14:40 -04:00
|
|
|
import { TimeSpan, createDate } from "oslo";
|
|
|
|
import { generateRandomString, alphabet } from "oslo/crypto";
|
|
|
|
import db from "@server/db";
|
|
|
|
import { users, emailVerificationCodes } from "@server/db/schema";
|
|
|
|
import { eq } from "drizzle-orm";
|
|
|
|
import { sendEmail } from "@server/emails";
|
2025-01-01 21:41:31 -05:00
|
|
|
import config from "@server/lib/config";
|
2024-11-24 14:53:46 -05:00
|
|
|
import { VerifyEmail } from "@server/emails/templates/VerifyEmailCode";
|
2024-10-04 23:14:40 -04:00
|
|
|
|
|
|
|
export async function sendEmailVerificationCode(
|
|
|
|
email: string,
|
2024-12-15 17:47:07 -05:00
|
|
|
userId: string
|
2024-10-04 23:14:40 -04:00
|
|
|
): Promise<void> {
|
|
|
|
const code = await generateEmailVerificationCode(userId, email);
|
|
|
|
|
2024-11-28 00:11:13 -05:00
|
|
|
await sendEmail(
|
|
|
|
VerifyEmail({
|
|
|
|
username: email,
|
|
|
|
verificationCode: code,
|
2025-01-01 17:50:12 -05:00
|
|
|
verifyLink: `${config.getRawConfig().app.base_url}/auth/verify-email`
|
2024-11-28 00:11:13 -05:00
|
|
|
}),
|
|
|
|
{
|
|
|
|
to: email,
|
2025-01-01 17:50:12 -05:00
|
|
|
from: config.getRawConfig().email?.no_reply,
|
2024-12-15 17:47:07 -05:00
|
|
|
subject: "Verify your email address"
|
|
|
|
}
|
2024-11-28 00:11:13 -05:00
|
|
|
);
|
2024-10-04 23:14:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
async function generateEmailVerificationCode(
|
|
|
|
userId: string,
|
2024-12-15 17:47:07 -05:00
|
|
|
email: string
|
2024-10-04 23:14:40 -04:00
|
|
|
): Promise<string> {
|
|
|
|
const code = generateRandomString(8, alphabet("0-9"));
|
2024-12-24 16:00:02 -05:00
|
|
|
await db.transaction(async (trx) => {
|
|
|
|
await trx
|
|
|
|
.delete(emailVerificationCodes)
|
|
|
|
.where(eq(emailVerificationCodes.userId, userId));
|
2024-10-04 23:14:40 -04:00
|
|
|
|
2024-12-24 16:00:02 -05:00
|
|
|
await trx.insert(emailVerificationCodes).values({
|
|
|
|
userId,
|
|
|
|
email,
|
|
|
|
code,
|
|
|
|
expiresAt: createDate(new TimeSpan(15, "m")).getTime()
|
|
|
|
});
|
2024-10-04 23:14:40 -04:00
|
|
|
});
|
|
|
|
return code;
|
|
|
|
}
|