How to Hash Passwords in Node.js Using Bcryptjs, Express and Mongoose
IntroductionStoring plaintext passwords in a database is one of the most critical security vulnerabilities a web application can have. If a database is compromised, every user account is instantly exposed. To protect user credentials, modern backend applications rely on secure cryptographic hashing functions like bcrypt. In this tutorial, we will walk through how to build a secure user registration and login API in Node.js using Express, Mongoose, and What is Bcrypt?Bcrypt is a password-hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and introduced at USENIX in 1999.
What is Hashing?Hashing is a one-way cryptographic mapping function. It transforms any input string (like a user's password) into a fixed-length string of characters.
Step 1: Project Setup and Dependencies1. Create and Enter Project DirectoryOpen your terminal and run the following commands: mkdir bcrypt cd bcrypt 2. Initialize Node.Js Initialize your workspace to generate a package.json configuration file:npm init -y 3.Install Required Pacakges Install Express, Mongoose, bcryptjs, and Body-Parser:npm install --save bcryptjs express body-parser mongoose Pacakges BreakDown
Step 2: Create the Mongoose User Model(models/user.js)Create a folder named models and add a file named user.js.Mongoose schemas map directly to MongoDB collections and define the structure of documents within them. var mongoose = require('mongoose'); var userSchema = new mongoose.Schema({ email:String, password:String }); module.exports = mongoose.model('user',userSchema); Step 3: Build the Entry Point & Authentication Logic(app.js)Create app.js in your root directory. This file handles database connections, registration (hashing passwords), and login (comparing hashes).var express = require('express'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var userModel = require('./models/user'); var bcrypt = require('bcryptjs'); //set the connection to db mongoose.connect('mongodb://localhost:27017/Demoo',{useNewUrlParser:true}) .then(function(){ console.log('connected to db'); }).catch(function(error){ console.log('error'+error); }); var app = express(); //fetch data from request app.use(bodyParser.json()); //register user app.post('/register',function(req,res){ bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(req.body.password, salt, function(err, hash) { var userr = new userModel({ email:req.body.email, password:hash }); userr.save(function(err,data){ if(err){ res.json({er:error}); }else{ res.json({da:data,msg:'user is registerd'}); } }); }); }); }); //user login app.post('/login',function(req,res){ userModel.find({email:req.body.email},function(err,data){ if(err){ res.json({er:err}); }else{ if(data!=''){ bcrypt.compare(req.body.password,data[0].password, function(err, result) { if(result){ res.json({msg:'password matched'}); }else{ res.json({msg:'password didnt matched'}); } }); } else{ res.json({msg:'user is not registerd'}); } } }); }); var port = process.env.PORT || 3000; app.listen(port,function(){ console.log('server running at '+port); }); ReferenceSource Code :- Download the code from here Video Tutorial: :- Watch Video Tutorial |
Comments
Post a Comment