Skip to main content

How to Register User with Hashed Password node js & express js

 // Create a a file named helper.js to convert plain password into hashed password as well compare it at the time of login -

//helper.js

import bcrypt from 'bcryptjs';

 function hashPassword(password){

const salt = bcrypt.genSaltSync(); 

return bcrypt.hashSync(password, salt); 

}

function comparePassword(raw, hash){

return bcrypt.compareSync(raw, hash)

}

  // here above in compare password function first argument is raw pass means plain pass which you have entered and second hash is that already saved hashed password , we will compare it and get user login

export {hashPassword, comparePassword } 


// End Helper ======================================================

// now at your IndexModel or User Model  import that functions which were created in helper.js as well RegisterSchema also 

import RegisterSchemaModel from '../schema/RegisterSchema.js';

import {hashPassword, comparePassword} from '../schema/helper.js';

class IndexModel{

// to Register User with Hashed Password

 registerUserModel(userDetails){

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

    userDetails.password = hashPassword(userDetails.password);

    var obj = new RegisterSchemaModel(userDetails);         

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

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

    });

  });  

 }


// For User Login with plain password by doing comparison with already saved your hashed pass

 fetchUsers(userDetails) {    

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

        const {email,password,status} = userDetails; 

        RegisterSchemaModel.find({email,status},(err,result)=>{

          const isValid = comparePassword(userDetails.password, result[0].password);  

  // here above in compare password function first argument is raw pass means plain pass which you have entered and second result[0].pass is that already saved hashed password , we will compare it and get user login

                var userDBpass = result[0].password

                if(isValid)

                  resolve(result)

                else

                  reject(err);

            //!isValid ? reject(err) : resolve(result);

        })

    })

 }


}

End 

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

// For Those Users who don't follow MVC architecture - or use Single file to code 

//create Schema first just like above and import it 

const express = require('express');  // use import if you use ES6 Module

const router = express.Router();  

const registerSchemaModel = require('../model/user'); 

// Signup API with hashed password ---------

router.post('/signup', (req, res, next) => { 

// Creating empty user object 

    let newUser = new registerSchemaModel(); 

    newUser.name = req.body.name, 

    newUser.email = req.body.email,

    newUser.password=req.body.password

 req.body.password = hashPassword( req.body.password);

    // Save object to DB

    newUser.save((err, User) => { 

        if (err) { 

            return res.status(400).send({ 

                message : "Failed to add user."

            }); 

        } 

        else { 

            return res.status(201).send({ 

                message : "User registered  successfully."

             });    } 

 }); 

}); 

// For Login API  -------------

router.post('/login', (req, res) => { 

    // Find user with requested email 

    registerSchemaModel.findOne({ email : req.body.email }, function(err, user) {     

        

const isValid = comparePassword(req.body.password, user.password); 

                if(isValid)

                    return res.status(201).send({ 

                    message : "User Logged In", 

                }) 

                else

                  return res.status(400).send({ 

                    message : "Wrong Password"

                });

          } 

        }); 

    }); 

module.exports = router;  

 



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...