fix: change MongoDB database to one from .env file, add unsubscribe IDs, and add email validation

This commit is contained in:
Dorian Niemiec 2024-09-08 05:44:44 +02:00
parent c1ebbac05f
commit b1cf131925
6 changed files with 92 additions and 4 deletions

View file

@ -1,5 +1,7 @@
import { mailOptions, transporter } from "@/lib/nodemailer/nodemailer";
import { NextRequest, NextResponse } from "next/server";
import dns from "dns/promises";
import { isEmail } from "validator";
const CONTACT_MESSAGE_FIELDS: Record<string, string> = {
name: "Name",
@ -129,6 +131,29 @@ export async function POST(req: NextRequest) {
);
}
// Check email address
if (!isEmail(data.email)) {
return NextResponse.json(
{ message: "Invalid email address" },
{ status: 400 }
);
}
// Check email host
const emailDomainMatch = data.email.match(/@([^@]+)/);
const emailDomain = emailDomainMatch ? emailDomainMatch[1] : "";
let isEmailHostValid = false;
try {
const mxRecords = await dns.resolveMx(emailDomain);
if (mxRecords.length > 0) isEmailHostValid = true;
} catch (err) {}
if (!isEmailHostValid) {
return NextResponse.json(
{ message: "Email domain is misconfigured" },
{ status: 400 }
);
}
await transporter.sendMail({
...mailOptions,
...generateEmailContent(data),

View file

@ -31,7 +31,7 @@ export async function POST(req: NextRequest) {
const { subject, html } = await req.json();
const client = await clientPromise;
const db = client.db("newsletter");
const db = client.db(process.env.MONGODB_DB);
const collection = db.collection("subscribers");
const subscribers = await collection

View file

@ -16,7 +16,7 @@ export async function GET(req: Request) {
const skip = (page - 1) * limit;
const client = await clientPromise;
const db = client.db("newsletter");
const db = client.db(process.env.MONGODB_DB);
const collection = db.collection("subscribers");
// Pagination

View file

@ -1,7 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import clientPromise from "@/lib/db";
import { Collection } from "mongodb";
import dns from "dns/promises";
import { isEmail } from "validator";
export async function POST(req: NextRequest) {
const generateUnsubscribeID = () => {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
for (let i = 0; i < 32; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
};
const generateUniqueUnsubscribeID = async (collection: Collection) => {
const id = generateUnsubscribeID();
const result = await collection
.find({
unsubscribeId: id
})
.toArray();
if (result.length > 0) {
return await generateUniqueUnsubscribeID(collection);
}
return id;
};
try {
const { email, captchaToken } = await req.json();
@ -33,8 +59,31 @@ export async function POST(req: NextRequest) {
);
}
// Check email address
if (!isEmail(email)) {
return NextResponse.json(
{ message: "Invalid email address" },
{ status: 400 }
);
}
// Check email host
const emailDomainMatch = email.match(/@([^@]+)/);
const emailDomain = emailDomainMatch ? emailDomainMatch[1] : "";
let isEmailHostValid = false;
try {
const mxRecords = await dns.resolveMx(emailDomain);
if (mxRecords.length > 0) isEmailHostValid = true;
} catch (err) {}
if (!isEmailHostValid) {
return NextResponse.json(
{ message: "Email domain is misconfigured" },
{ status: 400 }
);
}
const client = await clientPromise;
const db = client.db("newsletter");
const db = client.db(process.env.MONGODB_DB);
const collection = db.collection("subscribers");
// checking if email alr exists
@ -47,7 +96,11 @@ export async function POST(req: NextRequest) {
}
// saves the email in the db
await collection.insertOne({ email, subscribedAt: new Date() });
await collection.insertOne({
email,
subscribedAt: new Date(),
unsubscribeId: await generateUniqueUnsubscribeID(collection)
});
return NextResponse.json(
{ message: "Successfully subscribed!" },

9
package-lock.json generated
View file

@ -61,6 +61,7 @@
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"uploadthing": "^6.12.0",
"validator": "^13.12.0",
"zod": "^3.23.8"
},
"devDependencies": {
@ -27913,6 +27914,14 @@
"builtins": "^1.0.3"
}
},
"node_modules/validator": {
"version": "13.12.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz",
"integrity": "sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/vfile": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",

View file

@ -65,6 +65,7 @@
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"uploadthing": "^6.12.0",
"validator": "^13.12.0",
"zod": "^3.23.8"
},
"devDependencies": {