email-verification-code
Version:
Send a Verification Code to Confirm the User Email's.
119 lines (111 loc) • 3.13 kB
JavaScript
const nodemailer = require("nodemailer");
const TokenGenerator = require("uuid-token-generator");
const { addUser, removeUser, getUser, tokenExistence } = require("./func");
const getCode = function (email) {
const oldData = getUser(email);
console.log(oldData);
let code, token;
if (oldData) {
if (new Date(oldData.expirateDate) > new Date()) {
code = Number(oldData.code);
token = oldData.token;
} else removeUser(email);
}
code = code || Math.floor(Math.random() * 900000 + 100000);
token = token || new TokenGenerator().generate();
addUser(email, { code, token });
return { code, token };
};
exports.sendCode = async function ({ smtpInfo, company, mailInfo }) {
const { code, token } = getCode(mailInfo.emailReceiver);
const transporter = nodemailer.createTransport({
host: smtpInfo.host,
port: smtpInfo.port || 465,
secure: smtpInfo.port ? smtpInfo.port === 465 : true, // true for 465, false for other ports
auth: {
user: smtpInfo.user,
pass: smtpInfo.pass,
},
});
const info = await transporter.sendMail({
from: `${company.name} <${company.email}>`,
to: `${mailInfo.emailReceiver}`,
subject: `${mailInfo.subject}`,
text: mailInfo.text ? `${mailInfo.text(code, token)}` : "",
html: mailInfo.html ? `${mailInfo.html(code, token)}` : "",
});
console.log("Message sent:");
console.log({ info });
};
exports.verifyCode = function (email, code) {
const data = getUser(email);
let error, reason;
if (data) {
if (new Date(data.expirateDate) > new Date()) {
error = Number(data.code) !== Number(code);
reason =
Number(data.code) !== Number(code) ? "This code is not Valid!" : "";
Number(data.code) === Number(code) ? removeUser(email) : "";
} else {
removeUser(email);
error = true;
reason = "This code has expirated, Please retry again!";
}
} else {
error = true;
reason = "Email not found!";
}
return {
error,
reason,
};
};
exports.verifyToken = function (token) {
const { data, email } = tokenExistence(token);
if (data) {
removeUser(email);
if (new Date(data.expirateDate) > new Date())
return {
error: false,
email,
code: data.code,
};
return {
error: true,
reason:
"This link has expired, Please re-send a verification code to Confirm your email!",
};
}
return {
error: true,
reason: "Invalid Token!",
};
};
exports.verifyBoth = function ({ code, token }) {
const { data, email } = tokenExistence(token);
if (data) {
if (new Date(data.expirateDate) > new Date()) {
if (data.code === code) {
removeUser(email);
return {
error: false,
email,
};
}
return {
error: true,
reason: "This code is not Valid!",
};
}
removeUser(email);
return {
error: true,
reason:
"This link has expired, Please re-send a verification code to Confirm your email!",
};
}
return {
error: true,
reason: "Invalid Token!",
};
};