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

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 to your project folder)             you can push your entire project folder to git-hub and and

Part 19- Router (Networking Devices)- Computer Networking- CCNA

Hello friends...i am Vasu Birla and today will discuss about the most important Networking Device ..Router.  so let's start... ROUTER Router is a device which connect two or more networks together, which is why router is also known is Inter-networking device also. Inter-networking means two or more networks are connected together with the help of router. one more thing router is just like a computer  but it is designed for routing only, our computer can be router also but that are software router while hardware router which are specialize for routing is more efficient and fast than software router.  There is a Operating System installed on router which get moves data from one network to another network with the help of routing table.  Router does work on Network layer or Layer 3 of the OSI model.  Cisco Router There many companies which manufacture Router but main companies are - Cisco , Juniper , HP, 3com and Nortel  Functions of Router

Part 16- HUB (Networking Devices)- Computer Networking- CCNA

hello friends , Today we will discuss about the second Networking Devices Ethernet HUB. HUB Hub is a centralize device via all devices (computers, printers etc.) are connected with the star topology.  Hub connects other multiple devices together and helps to make connectivity mutually so that they can share and transfer data to each and every devices which is connected to that hub.  Hub does work at the first layer means at Physical layer of the OSI Model. Hub has many ports, and each port works like a repeater so Hub is also known as Multiport Repeater. A Hub Types of Hubs. there are three kind of Hubs. Active , passive and Manageable hubs. 1. Active Hubs - These hubs regenerates and amplify the signals to keep them strong. one more thing there is electricity needed in the active Hubs. 2. Passive Hubs- Passive Hubs simply forward the received signals. this type of hub does not make pure signal or regenerate so  these passive hubs doesn't n