Skip to main content

How to Generate unique verification link to get verify user once - Node js , Express Js

// Only Logic code included - modify according to your project 

// do basic things create app.js & create routes, controller and models folder and add files respectively IndexRouter.js , IndexController.js & IndexModel.js   


// IndexRouter.js (only logic code added here) 

router.post("/register",(req,res)=>{

        IndexController.registerUser(req.body).then((result)=>{

    var token = result.token; // this token is added from result coming from IndexController

      sendEmail(req.body.email,req.body.password,token);

      res.render("register",{"output":"User register successfully..."});

             //res.status(201).send({ message : "User Logged In"})   

 }).catch((err)=>{

       res.render("register",{"output":err});

    //console.log(err);

 });

});

=====================

//IndexController.js  start 


class IndexController {

 registerUser(userDetails,cb) {

  return new Promise((resolve,reject)=>{

    IndexModel.fetchUsers({}).then((result)=>{

     var l=result.length;

     var _id=(l==0)?1:result[l-1]._id+1;

     var token = crypto.randomBytes(32).toString("hex"); // random key to add in link

     userDetails={...userDetails,"_id":_id,"status":0,"role":"user","info":Date(),"token":token}   

     IndexModel.registerUserModel(userDetails).then((result)=>{

        resolve(result);    

     }).catch((err)=>{

        reject(err);            

     });   

    }).catch((err)=>{

     reject(err);    

    });

  })   

 }

}

=============================================================


//connection.js  // for database creation and connectivity

import mongoose from 'mongoose';  // to connect with Mongo database we use mongoose module

const url="mongodb://localhost:27017/vasu1" // here vasu1 is database name , 

mongoose.set('strictQuery',true)   // new updated version of mongoose require this query 

mongoose.connect(url);

console.log("Successfully connected to mongodb database....");

===================================================================

//IndexModel.js start  

//Create your own RegisterSchema and import it


class IndexModel

{  

 registerUserModel(userDetails) {

  return new Promise((resolve,reject)=>{

    var obj = new RegisterSchemaModel(userDetails);   

     obj.setPassword(userDetails.password);     

    obj.save((err,result)=>{

            err ? reject(err) : resolve(result) ;            

    });

  });  

 }

 }

===============================================================

// user will get email like this 

// your token will be seen like this in database 


 as well you can see  status is 0 in database , it means user can not login until status will be  1 , and  we are going to get update this status 0 to 1 via link by user.  

now we have to add this token to our link which will be sent to user on registration . on the time of registration a automatic email sent to user's email  (You Can See MY previous Post ).  so we have to add only token in it.  you can see above in IndexRouter.js coding  we have passed token as argument also.  

  sendEmail(req.body.email,req.body.password,token); 

=======================================================================

// go to EmailAPI.js  in routes folder 

import nodemailer from 'nodemailer';

var sendMail=(email,password,token)=>{

   process.env.NODE_TLS_REJECT_UNAUTHORIZED='0'

var transporter = nodemailer.createTransport({

  service: 'gmail',

  auth: {

    user: 'vasubirla@gmail.com',  // through which you want to send to verification mails

    pass: 'mtvrqzmxlarnrkl'  // create your own temporary password in google security setting 

  }

});

var mailOptions = {

  from: 'vasubirla@gmail.com',

  to: email,

  subject: 'Verification Mail MyApp',

  html: "<h1>Welcome To MyApp</h1><p>you have successfully register to our app , your login credentials are attached below</p><h3>Email : "+email+"</h3><h3>Password : "+password+"</h1>"+"</h3><br><h2>Click on the link below to verify your account</h2>http://localhost:3000/verifyUser/"+email+'/'+token

};

transporter.sendMail(mailOptions, function(error, info){

  if (error) {

    console.log(error);

  } else {

    console.log('Email sent: ' + info.response);

  }

}); 

}

export default sendMail; // export this function to use in IndexRouter.js  at the time or registration

=======================================================================

Now We have sent Email with unique link successfully -  now we have to get update status value 0 to 1 in database when user click on that unique link sent to his email . 

// IndexRouter.js 

//here email & token is parameter added to link localhost:3000/verifyuser/vasubirla.com/(here we have to add token value)

//Whenever User will click on link - email value will be set in /:email parameter and token value will be set in /:token parameter . 

router.get("/verifyuser/:email/:token",(req,res)=>{ 

 console.log(req.params);

 IndexController.verifyUser(req.params).then((result)=>{

    res.render("verifyuser",{"output":"User Verified successfully...","output1":""});

    console.log(result);

 }).catch((err)=>{

    res.render("verifyuser",{"output1":"Failed to Verify User","output":""});

    console.log(err);

 });          

});

==================================

//IndexController.js  

import IndexModel from '../models/IndexModel.js';

     

class IndexController {

  verifyUser(tokenDetails)

 {

   return new Promise((resolve,reject)=>{

    IndexModel.verifyUser(tokenDetails).then((result)=>{

      resolve(result);

    }).catch((err)=>{

      reject(err);  

    });   

   });

 }

}

===================================================================== 


// IndexModel.js ........ 

import './connection.js';  // we already created above 

import RegisterSchemaModel from '../schema/RegisterSchema.js'; //  open my previous post to find                                                                                                                     coding of Register schema 

class IndexModel{

 verifyUser(tokenDetails)

 {

  return new Promise((resolve,reject)=>{

        RegisterSchemaModel.update({"token":tokenDetails.token},{"status":1},(err,result)=>{

      err ? reject(err) : resolve(result);        

    });    

  }) 

 }

}

=====================================================================


Now user's status is 1 in data base so he can login now. 

if you have any doubts send Email at vasubirla@gmail.com 

Thanks 

Comments

Popular posts from this blog

Part 15- What is Repeater (Networking Devices)- Computer Networking- CCNA

Repeater  hello friends i am Vasu Birla and today i am starting new segment of CCNA computer networking  its a Networking Devices. we will discuss every important Devices used in networks. Repeater is a first networking devices. What is Repeater  Repeater is a device that receives signals and re-transmits by amplifying or regenerating signals. Repeater has two port one is for receive signals from previous network and second port is for retransmit signals to the next extended network. Two Port Repeater Repeater is a device which is used to Regenerate or replicate signal (Pichhe se aa rahe signal ko regenerate karke ya amplify karke aage strong signals bhej sakte he) Analog and digital both type of signals can be retransmitted by repeater. Here there is difference between regeneration and amplifying.  Amplification means , received signals will be amplified as it is , whether there are impurities in signals  and Regeneration means repeate...

GitHub Repo Collaboration Work on single project

 =============================================== To collaborate effectively with your friend on the same project, you should use Git branches to manage different lines of development. Here's a step-by-step procedure you can follow to streamline collaboration: 1. Create Separate Branches for Each Developer Create a New Branch for Your Friend: On your local repository, create a new branch for your friend. For example if your friend name is kilvish , if you want to create a branch named kilvish , you would run: make sure you would be on main branch already   command->  git checkout -b kilvish git push origin kilvish 2. Set Up Your Friend’s Environment( On your Friend's System )  at kilvish side  run ->  Clone the Repository (if not already done): If your friend hasn’t cloned the repository yet, they should do so: command ->  git clone https://github.com/Vasu-Birla/your-repo.git   // your your main clone line  Fetch All Bran...

How to deploy NodeJS app on server with Apache2 and acess it with Server IP addresss - Node JS deploy project Live.

     hello friens , This is Vasu Birla , in previous post we have seen the deployement of NodeJS app on AWS instance server instance but AWS server is expensive than other servers . SO today we will use simple Ubuntu server for making Live out Project using Apache2 . At the end you will be abe to access your NodeJS app using server IP address from anywhere  .. 1.  Login to your server using SSH terminal . (in AWS part i already explained how to do this )     -> Open your putty in hostname put your server IP -      login with ssh username ->root and password     (if you dont have root username and pass ask your      provider or reset it from cpanel or hosting panel ) 2. after login - on terminal you can Put your project anywhere.     There are two ways to put your project folder on server location     (i) - > using Github - (very popular and easy to track your everyday code changes t...