md5 Password hashing in Node Mongo APp

md5 is a javascript function for hashing messages, passwords with MD5. Passwords are saved securely in the mongo db database by hashing the user input with MD5.

Install md5 package in Node App using npm

npm i md5

Using md5 package with Node JS and Mondo DB App

const md5 = require("md5");

const newUser = new User({
     email : req.body.username,
     password : md5(req.body.password)
  })

Full Code:

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const mongoose = require('mongoose');
const md5 = require("md5");
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){

  const newUser = new User({
     email : req.body.username,
     password : md5(req.body.password)
  })

  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 = md5(req.body.password);

    User.findOne({email: username}, function(err, foundUser){
      if(err){
        res.send(err);
      } 
      else{ if(foundUser){
        if(foundUser.password === password){
            res.render('secrets');
          } else{
            res.send("Wrong Password");
          } 
        }
        
      }

    });


});


app.listen(3000, function() {
    console.log("Server started on port 3000");
  });

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *