How can I add bcryptjs to this code to encrypt passwords?

262 Views Asked by At

Sorry but enter code hereI can't make mongo database shows me the passwords encrypted and when I changed directly from the body the login doesn't work. How can I modify this code to encrypt passwords with bcryptjs?

var express = require('express');
var router = express.Router();
var {client,dbName} = require('../db/mongo');
var passport = require('passport');
var LocalStrategy = require('passport-local');

const bcryptjs = require("bcryptjs");



passport.use(new LocalStrategy(
  async function(username, password, done) {

    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('usuarios');
    await collection.findOne({ usuario: username }, function (err, user) {


      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      console.log(password);
      console.log(user.password);
      if (password!==user.password) { return done(null, false); }
      return done(null, user);
    });
  }
));


passport.serializeUser(function(user, done) {
  console.log(user);
  done(null, user.usuario);
});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('login');
});

router.post('/registro', async function(req, res){

  regUser(req.body)

    .then(()=>{
      res.render('login',{info: "Registrado"})
    })
    .catch((err)=>{
      console.log(err);
    })
    .finally(()=>{
      client.close()
    })

});



async function regUser(datos){
  await client.connect();
  const db = client.db(dbName);
  const collection = db.collection('usuarios');
  await collection.insertOne(
    {
      usuario: datos.usuario,
      password: datos.password
    }
  )
}

router.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {


    res.redirect('/');
  });

module.exports = router;

    

> `enter code here`

1

There are 1 best solutions below

3
On

You can do something like to hash your password.

password = await bcrypt.hash(password, 10)

then check hash of both of the passwords, if both matches then you can allow user further like

const hashPassword = await bcrypt.hash(password, 10)
const hashUserPassword = await bcrypt.hash(user.password, 10)
// and then do this to check if password same or not
if (hashPassword !== hashUserPassword) { return done(null, false); }

OR you can directly do this while inserting the password in db, this will put hash password in the db.

async function regUser(datos){
  await client.connect();
  const db = client.db(dbName);
  const collection = db.collection('usuarios');
  const hashUserPassword = await bcrypt.hash(datos.password, 10)
  await collection.insertOne(
    {
      usuario: datos.usuario,
      password: hashUserPassword
    }
  )
}

You can also have a look at this link to know more about bcrypt.

If issue still persists, let me know on comments.