|
| 1 | +import { NextApiRequest, NextApiResponse } from 'next'; |
| 2 | +import NextCors from 'nextjs-cors'; |
| 3 | +import verifySig from '../../../lib/verifySig'; |
| 4 | +import verifyJWT from '../../../lib/verifyJWT'; |
| 5 | +import objectPath from 'object-path'; |
| 6 | +import fs from 'fs'; |
| 7 | +import path from 'path'; |
| 8 | + |
| 9 | +const domain: string = process.env.DOMAIN !== undefined ? process.env.DOMAIN: ''; |
| 10 | + |
| 11 | +async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 12 | + await NextCors(req, res, { |
| 13 | + methods: ["POST"], |
| 14 | + origin: '*', |
| 15 | + optionsSuccessStatus: 200 |
| 16 | + }); |
| 17 | + // const body = { |
| 18 | + |
| 19 | + // from: '', |
| 20 | + // from_email: '[email protected]', |
| 21 | + // subject: '', |
| 22 | + // title: '', |
| 23 | + // previewtext: '', |
| 24 | + // paragraphtext: '', |
| 25 | + // paragraphtext2: '', |
| 26 | + // link: 'https://example.com', |
| 27 | + // buttonstyle: 'display:block' || 'display:none', |
| 28 | + // buttontext: '' |
| 29 | + // } |
| 30 | + if (await verifySig(req)) { |
| 31 | + if (objectPath.has(req, 'body.to')) { |
| 32 | + let proceed = false; |
| 33 | + if (req.headers['authorization'] !== undefined) { |
| 34 | + const jwt = req.headers['authorization'].split(' ')[1]; |
| 35 | + if (await verifyJWT(jwt, objectPath.get(req, 'body.from_email'))) { |
| 36 | + proceed = true; |
| 37 | + } |
| 38 | + } |
| 39 | + if (proceed) { |
| 40 | + const htmlContent = fs.readFileSync(path.join(process.cwd(), 'public', 'email.html'), 'utf-8'); |
| 41 | + const htmlFinal = htmlContent.replace(/[\r\n]+/gm, '') |
| 42 | + .replace('@title', req.body.title) |
| 43 | + .replace('@previewtext', req.body.previewtext) |
| 44 | + .replace('@paragraphtext', req.body.paragraphtext) |
| 45 | + .replace('@2paragraphtext', req.body.paragraphtext2) |
| 46 | + .replaceAll('@link', req.body.link) |
| 47 | + .replace('@buttonstyle', req.body.buttonstyle) |
| 48 | + .replace('@buttontext', req.body.buttontext); |
| 49 | + const sendmail = await fetch(domain + "/api/sendmail", { |
| 50 | + method: "POST", |
| 51 | + headers: { |
| 52 | + "Content-Type": "application/json", |
| 53 | + }, |
| 54 | + body: JSON.stringify({ |
| 55 | + email: req.body.to, |
| 56 | + subject: req.body.subject, |
| 57 | + html: htmlFinal, |
| 58 | + }) |
| 59 | + }); |
| 60 | + const { error } = await sendmail.json(); |
| 61 | + if (error) { |
| 62 | + console.log(error); |
| 63 | + } |
| 64 | + res.status(200).json({success: true}); |
| 65 | + } else { |
| 66 | + res.status(401).send('Unauthorized - verify JWT failed'); |
| 67 | + } |
| 68 | + } |
| 69 | + } else { |
| 70 | + res.status(401).send('Unauthorized - verify signature failed'); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +export default handler; |
0 commit comments