email-verification-code-sendgrid
Version:
Using sendgrid, we added <strong>2 other functions</strong> to make the verification more secure and more intense.<br> Now you can confirm with a Token that is generated at the beginning, or confirm with the code and the token at the same time!
121 lines (111 loc) • 3.08 kB
JavaScript
const nodemailer = require("nodemailer");
const TokenGenerator = require("uuid-token-generator");
const { addUser, removeUser, getUser, tokenExistence } = require("./func");
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
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 info2 ={
from: company.email,
to:mailInfo.emailReceiver,
subject: mailInfo.subject,
text: mailInfo.text ? mailInfo.text(code, token) : "",
html: mailInfo.html ? mailInfo.html(code, token) : `The Confirmation Code is: ${code}`,
}
await sgMail.send(info2)
.then(() => {}, error => {
console.error(error);
if (error.response) {
console.error(error.response.body)
}
})
console.log("Message sent:");
console.log({ info2 });
};
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!",
};
};