bcrypt is a node library that enables password hashing. So we ca securely store the password of our Node Express Mongo Apps.
Install bcrypt using terminal command
npm i bcrypt
If facing issue with installation of bcrypt, you can try installing the older version of it with the version number.
npm i [email protected]
bcrypt Reference: https://www.npmjs.com/package/bcrypt
Full Code:
const express = require("express"); const bodyParser = require("body-parser"); const ejs = require("ejs"); const app = express(); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const saltRounds = 10; app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); const uri = "mongodb://localhost:27017/usersDB" mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true}); const userSchema = new mongoose.Schema({ email: String, password: String }); const User = new mongoose.model("User", userSchema); app.get('/', function(req, res){ res.render('home'); }); app.get('/login', function(req, res){ res.render('login'); }); app.get('/register', function(req, res){ res.render('register'); }); app.post("/register", function(req,res){ bcrypt.hash(req.body.password, saltRounds, function(err, hash) { // Store hash in your password DB. const newUser = new User({ email : req.body.username, password : hash }); newUser.save(function(err){ if(err){ res.send("Registration failed..!"); }else{ res.render('secrets'); } }) }); }); app.post("/login", function(req,res){ const username = req.body.username; const password = req.body.password; User.findOne({email: username}, function(err, foundUser){ if(err){ res.send(err); } else{ if(foundUser){ bcrypt.compare(password, foundUser.password, function(err, result) { if(result === true){ res.render('secrets'); } else{ res.send("Wrong Password"); } }); } } }); }); app.listen(3000, function() { console.log("Server started on port 3000"); });