Updates
This commit is contained in:
@@ -12,8 +12,10 @@ import {
|
||||
PackageUserLoginRequestBody,
|
||||
} from "../../types";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
import numberfy from "../../utils/numberfy";
|
||||
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
|
||||
import emailRegexCheck from "../../functions/email/verification/email-regex-test";
|
||||
import emailMxLookup from "../../functions/email/verification/email-mx-lookup";
|
||||
import validateEmail from "../../functions/email/fns/validate-email";
|
||||
|
||||
type Param = {
|
||||
key?: string;
|
||||
@@ -24,6 +26,7 @@ type Param = {
|
||||
password?: string;
|
||||
};
|
||||
additionalFields?: string[];
|
||||
request?: http.IncomingMessage & { [s: string]: any };
|
||||
response?: http.ServerResponse & { [s: string]: any };
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
@@ -64,6 +67,7 @@ export default async function loginUser({
|
||||
debug,
|
||||
cleanupTokens,
|
||||
secureCookie,
|
||||
request,
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
@@ -108,11 +112,13 @@ export default async function loginUser({
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
if (!payload.email) {
|
||||
const isEmailValid = await validateEmail({ email: payload.email });
|
||||
|
||||
if (!payload.email || !isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Email Required",
|
||||
msg: isEmailValid.message,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// import arcjet, { ArcjetOptions, Primitive, Product } from "@arcjet/node";
|
||||
|
||||
// interface Params<
|
||||
// Rules extends (Primitive | Product)[],
|
||||
// Characteristics extends readonly string[]
|
||||
// > {
|
||||
// options?: Omit<ArcjetOptions<Rules, Characteristics>, "key" | "rules"> & {
|
||||
// rules?: Rules;
|
||||
// };
|
||||
// }
|
||||
|
||||
// export default function arcjetClient<
|
||||
// Rules extends (Primitive | Product)[],
|
||||
// Characteristics extends readonly string[]
|
||||
// >(params?: Params<Rules, Characteristics>) {
|
||||
// const ARCJET_KEY = process.env.DSQL_ARCJET_KEY;
|
||||
// const ARCJET_ENV = process.env.NODE_ENV || "development";
|
||||
|
||||
// if (!ARCJET_KEY) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// const aj = arcjet({
|
||||
// key: ARCJET_KEY,
|
||||
// characteristics: ["ip.src"],
|
||||
// rules: [],
|
||||
// ...params?.options,
|
||||
// });
|
||||
|
||||
// return aj;
|
||||
// }
|
||||
@@ -6,6 +6,7 @@ import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import validateEmail from "../../email/fns/validate-email";
|
||||
|
||||
/**
|
||||
* # API Create User
|
||||
@@ -118,6 +119,16 @@ export default async function apiCreateUser({
|
||||
};
|
||||
}
|
||||
|
||||
const isEmailValid = await validateEmail({ email: payload.email });
|
||||
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
const addUser = await addDbEntry({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
|
||||
@@ -1,103 +1,79 @@
|
||||
import fs from "fs";
|
||||
import _ from "lodash";
|
||||
import nodemailer from "nodemailer";
|
||||
import Mail from "nodemailer/lib/mailer";
|
||||
import SMTPTransport from "nodemailer/lib/smtp-transport";
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: process.env.DSQL_MAIL_HOST,
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.DSQL_MAIL_EMAIL,
|
||||
pass: process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
type Param = {
|
||||
to?: string;
|
||||
subject?: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
export type HandleNodemailerParam = Mail.Options & {
|
||||
senderName?: string;
|
||||
alias?: string | null;
|
||||
options?: SMTPTransport.Options;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Handle mails With Nodemailer
|
||||
*/
|
||||
export default async function handleNodemailer({
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
alias,
|
||||
senderName,
|
||||
}: Param): Promise<any> {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
export default async function handleNodemailer(
|
||||
params: HandleNodemailerParam
|
||||
): Promise<SMTPTransport.SentMessageInfo | undefined> {
|
||||
if (
|
||||
!process.env.DSQL_MAIL_HOST ||
|
||||
!process.env.DSQL_MAIL_EMAIL ||
|
||||
!process.env.DSQL_MAIL_PASSWORD
|
||||
) {
|
||||
return null;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: process.env.DSQL_MAIL_HOST,
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.DSQL_MAIL_EMAIL,
|
||||
pass: process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
...params.options,
|
||||
});
|
||||
|
||||
const sender = (() => {
|
||||
if (alias?.match(/support/i)) return process.env.DSQL_MAIL_EMAIL;
|
||||
if (params.alias?.match(/support/i)) return process.env.DSQL_MAIL_EMAIL;
|
||||
return process.env.DSQL_MAIL_EMAIL;
|
||||
})();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const mailRootPath = process.env.DSQL_MAIL_ROOT || "./email/index.html";
|
||||
|
||||
let sentMessage;
|
||||
let mailRoot = fs.existsSync(mailRootPath)
|
||||
? fs.readFileSync(mailRootPath, "utf8")
|
||||
: undefined;
|
||||
|
||||
if (!fs.existsSync("./email/index.html")) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mailRoot = fs.readFileSync("./email/index.html", "utf8");
|
||||
let finalHtml = mailRoot
|
||||
.replace(/{{email_body}}/, html ? html : "")
|
||||
.replace(/{{issue_date}}/, Date().substring(0, 24));
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
? mailRoot
|
||||
.replace(/{{email_body}}/, params.html?.toString() || "")
|
||||
.replace(/{{issue_date}}/, Date().substring(0, 24))
|
||||
: params.html?.toString();
|
||||
|
||||
try {
|
||||
let mailObject: any = {};
|
||||
|
||||
mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`;
|
||||
mailObject["from"] = `"${
|
||||
params.senderName || "Datasquirel"
|
||||
}" <${sender}>`;
|
||||
mailObject["sender"] = sender;
|
||||
if (alias) mailObject["replyTo"] = sender;
|
||||
mailObject["to"] = to;
|
||||
mailObject["subject"] = subject;
|
||||
mailObject["text"] = text;
|
||||
if (params.alias) mailObject["replyTo"] = sender;
|
||||
mailObject["to"] = params.to;
|
||||
mailObject["subject"] = params.subject;
|
||||
mailObject["text"] = params.text;
|
||||
mailObject["html"] = finalHtml;
|
||||
|
||||
// send mail with defined transport object
|
||||
let info = await transporter.sendMail(mailObject);
|
||||
|
||||
sentMessage = info;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
let info = await transporter.sendMail({
|
||||
..._.omit(mailObject, ["alias", "senderName", "options"]),
|
||||
...mailObject,
|
||||
});
|
||||
|
||||
return info;
|
||||
} catch (error: any) {
|
||||
console.log("ERROR in handleNodemailer Function =>", error.message);
|
||||
// serverError({
|
||||
// component: "handleNodemailer",
|
||||
// message: error.message,
|
||||
// user: { email: to },
|
||||
// });
|
||||
}
|
||||
|
||||
return sentMessage;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import handleNodemailer, {
|
||||
HandleNodemailerParam,
|
||||
} from "../../backend/handleNodemailer";
|
||||
import emailMxLookup from "../verification/email-mx-lookup";
|
||||
import emailRegexCheck from "../verification/email-regex-test";
|
||||
|
||||
type Param = {
|
||||
email?: string;
|
||||
welcomeEmailOptions?: HandleNodemailerParam;
|
||||
};
|
||||
export default async function validateEmail({
|
||||
email,
|
||||
welcomeEmailOptions,
|
||||
}: Param): Promise<{ isValid: boolean; message?: string }> {
|
||||
if (!email) {
|
||||
return {
|
||||
isValid: false,
|
||||
message: "Email is required.",
|
||||
};
|
||||
}
|
||||
|
||||
if (!emailRegexCheck(email)) {
|
||||
return {
|
||||
isValid: false,
|
||||
message: "Invalid email format.",
|
||||
};
|
||||
}
|
||||
|
||||
const checkEmailMxRecords = await emailMxLookup(email);
|
||||
|
||||
if (!checkEmailMxRecords) {
|
||||
return {
|
||||
isValid: false,
|
||||
message: "Email domain does not have valid MX records.",
|
||||
};
|
||||
}
|
||||
|
||||
if (welcomeEmailOptions) {
|
||||
const welcomeEmail = await handleNodemailer(welcomeEmailOptions);
|
||||
if (!welcomeEmail?.accepted?.[0]) {
|
||||
return {
|
||||
isValid: false,
|
||||
message: "Email verification failed.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: true,
|
||||
message: "Email is valid.",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import dns from "dns";
|
||||
import debugLog from "../../../utils/logging/debug-log";
|
||||
|
||||
export default function emailMxLookup(
|
||||
email?: string,
|
||||
debug?: boolean
|
||||
): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!email) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const domain = email.split("@")[1];
|
||||
|
||||
dns.resolveMx(domain, (err, addresses) => {
|
||||
if (err || !addresses.length) {
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: err?.message || "No MX records found",
|
||||
addTime: true,
|
||||
label: "Email MX Lookup",
|
||||
type: "error",
|
||||
});
|
||||
}
|
||||
resolve(false);
|
||||
} else {
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: addresses,
|
||||
addTime: true,
|
||||
label: "MX Records",
|
||||
});
|
||||
}
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export default function emailRegexCheck(email: string): boolean {
|
||||
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return regex.test(email);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import net from "net";
|
||||
import dns from "dns";
|
||||
|
||||
export default function verifyEmailSMTP(email: string): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const domain = email.split("@")[1];
|
||||
|
||||
dns.resolveMx(domain, (err, addresses) => {
|
||||
if (err || !addresses.length) {
|
||||
console.log("Invalid email domain.");
|
||||
return;
|
||||
}
|
||||
|
||||
const mxServer = addresses[0].exchange;
|
||||
console.log(`Connecting to ${mxServer} to verify email...`);
|
||||
|
||||
const client = net.createConnection(25, mxServer);
|
||||
|
||||
client.on("connect", () => {
|
||||
console.log("Connected to SMTP server.");
|
||||
client.write("HELO example.com\r\n");
|
||||
client.write(`MAIL FROM: <test@example.com>\r\n`);
|
||||
client.write(`RCPT TO: <${email}>\r\n`);
|
||||
});
|
||||
|
||||
client.on("data", (data) => {
|
||||
const response = data.toString();
|
||||
|
||||
if (response.includes("250")) {
|
||||
console.log("✅ Email exists!");
|
||||
resolve(true);
|
||||
} else {
|
||||
console.log("❌ Email does not exist.");
|
||||
resolve(false);
|
||||
}
|
||||
|
||||
client.end();
|
||||
});
|
||||
|
||||
client.on("error", (err) => {
|
||||
console.log("SMTP verification failed:", err.message);
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user