Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to hash a password using bcrypt inside an async function

Following on from this question.

I feel like I'm almost there, but my incomplete understanding of async is preventing me from solving this. I'm basically trying to just hash a password using bcrypt and have decided to seperate out the hashPassword function so that I can potentially use it in other parts of the app.

hashedPassword keeps returning undefined though...

userSchema.pre('save', async function (next) {    let user = this   const password = user.password;    const hashedPassword = await hashPassword(user);   user.password = hashedPassword    next()  })  async function hashPassword (user) {    const password = user.password   const saltRounds = 10;    const hashedPassword = await bcrypt.hash(password, saltRounds, function(err, hash) {      if (err) {       return err;     }      return hash    });    return hashedPassword  } 
like image 954
Modermo Avatar asked Feb 15 '18 04:02

Modermo


People also ask

Is bcrypt hash async?

Bcrypt provides both asynchronous and synchronous password hashing methods. The asynchronous mode is recommended because hashing is a CPU intensive task, and the synchronous approach will block the event loop and prevent your application from handling any other incoming requests or events.

What hash function does bcrypt use?

BCrypt is based on the Blowfish block cipher cryptomatic algorithm and takes the form of an adaptive hash function.


1 Answers

await dosent wait for bcrypt.hash because bcrypt.hash does not return a promise. Use the following method, which wraps bcrypt in a promise in order to use await.

async function hashPassword (user) {    const password = user.password   const saltRounds = 10;    const hashedPassword = await new Promise((resolve, reject) => {     bcrypt.hash(password, saltRounds, function(err, hash) {       if (err) reject(err)       resolve(hash)     });   })    return hashedPassword } 

Update:-

The library has added code to return a promise which will make the use of async/await possible, which was not available earlier. the new way of usage would be as follows.

const hashedPassword = await bcrypt.hash(password, saltRounds) 
like image 180
Akash Avatar answered Oct 05 '22 17:10

Akash