Im trying to build confirm email address for users, to verify their email is real. What package should i use to confirm the email address of the user. So far Im using mongoo
var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
/*
Here we are configuring our SMTP Server details.
STMP is mail server which is responsible for sending and recieving email.
*/
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "Your Gmail ID",
pass: "Gmail Password"
}
});
var rand,mailOptions,host,link;
/*------------------SMTP Over-----------------------------*/
/*------------------Routing Started ------------------------*/
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.get('/send',function(req,res){
rand=Math.floor((Math.random() * 100) + 54);
host=req.get('host');
link="http://"+req.get('host')+"/verify?id="+rand;
mailOptions={
to : req.query.to,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br><a href="+link+">Click here to verify</a>"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});
app.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
console.log("Domain is matched. Information is from Authentic email");
if(req.query.id==rand)
{
console.log("email is verified");
res.end("<h1>Email "+mailOptions.to+" is been Successfully verified");
}
else
{
console.log("email is not verified");
res.end("<h1>Bad Request</h1>");
}
}
else
{
res.end("<h1>Request is from unknown source");
}
});
/*--------------------Routing Over----------------------------*/
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});
Follow the code example, you can use nodemailer
to send the link, and then verify it.
Here is a link: https://codeforgeek.com/2014/07/node-email-verification-script/
function generateLink() {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var token = '';
for (var i = 16; i > 0; --i) {
var rand = Math.round(Math.random() * (chars.length - 1))
token += chars[rand];
}
var link = "http://localhost" + "/verify?id=" + token;
return link;
}
// npm install @sendGrid/mail --save
//library for generating link using SendGrid
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey("SENDGRID_API_KEY"); //create an account on sendgrid and get an API key
// generated link is send to the user's email for email verification
let sendVerifyEmailLink = (req, res) => {
var link = generateLink();
const msg = {
to: 'test@gmail.com',
from: 'test@gmail.com',
subject: 'Account Verifictaion',
text: 'Hello,\n\n' + 'Please verify your account by clicking the link:\/\/\n',
html: 'Hello,\n\n <br> Please verify your account by clicking the link: \n <br> <strong><a href = ' + link + '>http:\/\/ Click here to verify the given Link </a></strong>.\n .<br>Thanks<br>',
};
sgMail.send(msg).then(() => { }, error => {
console.error(error);
if (error.response) {
console.error(error.response.body)
}
});
console.log(msg)
}
Kindly use the NPM Package (two-step-auth)
I have made a NPM package that can take care of the verification of the Email ID that you provide, It takes in the Email ID and returns you an OTP and sends the Email ID you provide the same OTP, and you can verify them and then easily store the hashed mail ID in your DB with a satisfaction that they are real :)
Kindly check the full procedures with example here
const {Auth} = require('two-step-auth');
async function login(emailId){
const res = await Auth(emailId);
// You can follw the above approach, But we recommend you to follow the one below, as the mails will be treated as important
const res = await Auth(emailId, "Company Name");
console.log(res);
console.log(res.mail);
console.log(res.OTP);
console.log(res.success);
}
login("YourEmail@anyDomain.com")
This will help you a lot taking care of the process of verification under the HOOD :)
What you're looking for is called "account verification" or "email verification". There are plenty of Node modules that can perform this, but the principle goes like this:
active
attribute that is false
by defaultactive
will be false
initially)active
property to true
Your user is now verified.
if you are just testing on your local machine, one simple way of understanding how to do it can be :
Assuming you already know sending mails through nodemailer..
Once user signs up, after storing sign-up data in your database, on your server side take user email from sign-up data received and a random generated number and build a custom url with the address of page where user will be directed after he/she clicks on the link given in mail.
var customUrl = "http://"+ your host + "/" + your verification web-page + "?email=" + userEmail + "&id=" + randomNumber;
An example can be:
var userEmail = someone@example.com
var host = localhost:8080
var directWebPage = verifyUserEmail.html
var randomNumber = // generate with math.random() // lets say 111
Putting in above format of customUrl it looks something like this
customUrl:http://localhost:8080/verifyUserEmail.htmlemail=someone@example.com&id=111
Save this customUrl somewhere (probably in your database) Now, send an email to user with email body containing this cutomUrl link.
<a href="customUrl">Click to verify your email</a>
When user clicks on the link he/she will be directed to verifyUserEmail.html page and when that happens you can extract the page url containing email and id information
For example in angular I go like this-
var urlVerifyData = $location.url(); or $location.absUrl();
Now extract email form urlVerifyData string using javascript string methods
Request your server with this email and urlVerifyData
Now query your database for this email and verify previously stored customUrl with user's urlVerifyData
If they match, hola ! You got yourself a genuine user !!!
I would like to present a slightly different approach from the ones proposed.
This method does not put the hash into the database (therefore less interaction with it)
You don't need to register the hash in the database. Here's an overview after receiving a registration request:
Translated into code, you would have something like this:
1- Encode the token
function encodeRegistrationToken()
{
// jsonweb automatically adds a key that determines the time, but you can use any module
const jwt = require('jsonwebtoken');
// The information we need to find our user in the database (not sensible info)
let info = {id: yourUserId};
// The hash we will be sending to the user
const token = jwt.sign(info, "yoursecretkey");
return token;
}
// ...
let token = encodeRegistrationToken();
2- Send token to the user via any appropriate way
// Your implementation of sending the token
sendTokenToUser(token);
3- Decode the token
function decodeRegistrationToken(token)
{
const jwt = require('jsonwebtoken');
let decoded = jwt.verify(token, "yoursecretkey");
let userId = decoded.id;
// Check that the user didn't take too long
let dateNow = new Date();
let tokenTime = decoded.iat * 1000;
// Two hours
let hours = 2;
let tokenLife = hours * 60 * 1000;
// User took too long to enter the code
if (tokenTime + tokenLife < dateNow.getTime())
{
return {
expired: true
};
}
// User registered in time
return {
userID
};
}
4 - Update your database
or
Quick note: You can further encode the user id when encoding your token if you want (it's easily accessible).