|
| 1 | +import path from 'path' |
| 2 | +import fs from 'fs' |
| 3 | +import mustache from 'mustache' |
| 4 | +import config from '../config/server' |
| 5 | +import { ProviderConstructor } from './provider' |
| 6 | + |
| 7 | +export type VerificationEmailKind = 'register' | 'recover' | 'update' |
| 8 | + |
| 9 | +let sendVerification: (data: { |
| 10 | + token: string, |
| 11 | + kind: VerificationEmailKind, |
| 12 | + email: string |
| 13 | +}) => Promise<void> = async () => { |
| 14 | + throw new Error('email verification requested when email provider is not configured') |
| 15 | +} |
| 16 | + |
| 17 | +const emailConfig = config.email |
| 18 | +if (emailConfig) { |
| 19 | + const provider = (async () => { |
| 20 | + const { default: Provider } = await import(path.join('../providers', emailConfig.provider.name)) as { default: ProviderConstructor } |
| 21 | + return new Provider(emailConfig.provider.options ?? {}) |
| 22 | + })() |
| 23 | + |
| 24 | + const verifyHtml = fs.readFileSync(path.join(__dirname, 'emails/verify.html')).toString() |
| 25 | + const verifyText = fs.readFileSync(path.join(__dirname, 'emails/verify.txt')).toString() |
| 26 | + |
| 27 | + // This function is already typed earlier in the file; no need to repeat the type definition |
| 28 | + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types |
| 29 | + sendVerification = async ({ token, kind, email }) => { |
| 30 | + const emailView = { |
| 31 | + ctf_name: config.ctfName, |
| 32 | + logo_url: config.logoUrl, |
| 33 | + origin: config.origin, |
| 34 | + token: encodeURIComponent(token), |
| 35 | + register: kind === 'register', |
| 36 | + recover: kind === 'recover', |
| 37 | + update: kind === 'update' |
| 38 | + } |
| 39 | + const subject = { |
| 40 | + register: `Email verification for ${config.ctfName}`, |
| 41 | + recover: `Account recovery for ${config.ctfName}`, |
| 42 | + update: `Update your ${config.ctfName} email` |
| 43 | + }[kind] |
| 44 | + |
| 45 | + await (await provider).send({ |
| 46 | + from: `${config.ctfName} <${emailConfig.from}>`, |
| 47 | + to: email, |
| 48 | + subject, |
| 49 | + html: mustache.render(verifyHtml, emailView), |
| 50 | + text: mustache.render(verifyText, emailView) |
| 51 | + }) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +export { sendVerification } |
0 commit comments