-1

i have registration/login system and for hashing i used third party library bcryptjs and it works (i mean it hashes passwofrd) but problem is that this password is saved raw in database. here is my code of mongoose pre save hook

AdminSchema.pre('save', async function(next){
var user = this;
if(!user.isModified('password')) return next();

bcrypt.genSalt(SALT_WORK_FACTORY, function(err, salt){
    if(err) return next(err);

    bcrypt.hash(user.password, salt,function(err,hash){
       if(err) return next(err);
       console.log(hash)
       user.password = hash;
       console.log(user.password)
       next();
    })
  })
})

and here is save method in registration.js

 let admin;
  admin = new Admin();
  admin.username = username;
  admin.password = password;
  admin.save(function(err, user){
         if(err){
           console.log(err)
           return res.status(500).send({message:err.message})
         }
           console.log(user)
           const redirectTo = '/';
         return res.status(200).send({redirectTo})

        })
    }

when i log user.password in pre hook it shows me hash but when i log user in save it shows me raw text. what is problem? Thank you

iLiA
  • 3,053
  • 4
  • 23
  • 45
  • Might be an asynchronous issue. https://stackoverflow.com/questions/48799894/trying-to-hash-a-password-using-bcrypt-inside-an-async-function – Jaybird Aug 21 '19 at 21:32

2 Answers2

0

Try copying the string and not referring:

user.password = hash.slice();

PS: I can't comment, it should be a comment, if it is wrong I will delete this answer

0

Try This is work for You.

const bcrypt = require("bcrypt");

let admin;
  admin = new Admin();
  admin.username = username;
  admin.password = bcrypt.hashSync(password, 10);
  admin.save(function(err, user){
         if(err){
           console.log(err)
           return res.status(500).send({message:err.message})
         }
           console.log(user)
           const redirectTo = '/';
         return res.status(200).send({redirectTo})

        })
    }
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43