Password Encryption in Express using bcryptjs module , Password Decryption in Express using bcryptjs module. Login API using Express with password encryption . Example . Testing with postman

 Password Encryption in Express using bcryptjs module , Password Decryption in Express using bcryptjs module. Login API using Express with password encryption . Example . Testing with postman


package.json

{
  "name": "login3app",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "author": "s.kundu",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "express": "^4.19.2",
    "mongoose": "^8.5.3",
    "nodemon": "^3.1.4"
  }
}





server.js
const express = require('express');

const authroute=require('./routes/authroute');

const app=express(); 

const port=4000; 

//configuration code for accepting json data / form data from ui
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//register router 

app.use('/sourav',authroute);


app.listen(port,()=>{
    console.log(`server is running in the port ${port}`);
})





dbconnect.js
const mongoose=require('mongoose');

async function main()
{
    await mongoose.connect('mongodb://127.0.0.1:27017/batch6');
}

main().then(
    ()=>{console.log("Database Connection Done!")}
).catch(
    (err)=>{console.log(err)}
)

module.exports=mongoose; 






LoginController.js
const User=require('../models/usermodel');
const bcrypt=require('bcryptjs');
class LoginController 
{
    //for user register
    static registeruser=async (req,res)=>{
        try
        {
           const data=req.body;
           //email unique check 
           const result = await User.findOne({email:data.email});
           if(result)
           {
             res.status(200).json({msg:'Email id already exsist'});
           }
           else
           {
             // password encryption 
               const salt = bcrypt.genSaltSync(10);  //generates a random 10 characters string
               const hashPassword = bcrypt.hashSync(data.pwd, salt);   //hasing original pwd + append salt
               const us=new User();
               us.name=data.name;
               us.pwd=hashPassword;
               us.email=data.email;
               const result2=await us.save();
               res.status(200).json({msg:'insert is success',info:result2});
           }
        }
        catch(err)
        {
            res.status(404).json({error:err.message})
        }
   }

    //for user login 
    static loguser=async (req,res)=>{
        try 
        {
           const data=req.body;
           //email id check 
           const result=await User.findOne({email:data.email});
           if(!result)
           {
             res.status(200).json({msg:'Emailid is invalid'});
           }
           else 
           {
             //password decryp and match 
             const isMatch=bcrypt.compareSync(data.pwd,result.pwd); //(user_given_pwd,db_hash_pwd)
             if(!isMatch)
             {
                 res.status(200).json({msg:'password is invalid'});
             }
             else 
             {
                 res.status(200).json({msg:'user login success',info:result.name});
             }
           }
        }
        catch(err)
        {
         res.status(404).json({error:err.message})
        }
    }


}

module.exports=LoginController;





userModel.js
const mongoose=require('../database/dbconnect');

const userSchema=mongoose.Schema({
    name:{type:String},
    pwd : {type:String},
    email : {type:String,unique:true}
})  

const User = mongoose.model("user",userSchema);

module.exports=User;




authroutes.js
const express=require('express');
const LC=require('../controllers/LoginController');

const router=express.Router();

router.get('/test',(req,res)=>{
    res.send("<h3>welcome to Login routing</h3>");
})

router.post('/register',LC.registeruser); 

router.post('/login',LC.loguser);

module.exports=router;



Comments

Popular posts from this blog

Express Install , MVC architecture concept , Nodemon install , express server configuration , Postman Install , basic get() , post() operations in api and testing using postman.

Routing concept in Express , Controller Concept in Express , Get() , Post() routing in express , Testing in postman. Mongoose (ODM) install , Connectivity with Mongodb using mongoose.Connect() . Examples