COLEAN
COLEAN

Reputation: 695

Using bcrypt on Node.js results in validation failed

I am writing code in Node.js to encrypt passwords using bcrypt.

However, if you use bcrypt, you will get an ValidationError: User validation failed: password: Cast to String failed for value "Promise { <pending> }" at path "password"

I do not get this error if I save it as plain text without encryption.

Is there a secret of bcrypt I do not know?

bcrypt (not working)

const bcrypt = require('bcrypt');

sign_up = (req, res, next) => {
  const { email, password } = req.body;
  const User = User.findOne({ email: email });
  if (exUser) {
    return res.send('exist user');
  }
  const hash = bcrypt.hash(password, 8);
  const user = new User({
    email: email,
    password: hash
  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    res.send('signup success');
  });
};

no bcrypt (working)

sign_up = (req, res, next) => {
  const { email, password } = req.body;
  const User = User.findOne({ email: email });
  if (exUser) {
    return res.send('exist user');
  }
  const user = new User({
    email: email,
    password: password
  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    res.send('signup success');
  });
};

Upvotes: 0

Views: 1213

Answers (1)

Benjamin Davies
Benjamin Davies

Reputation: 354

To elaborate on Chris's comment:

It appears that bcrypt.hash is asynchronous, and is returning a Promise.

To fix this, I would recommend using an async function and awaiting the result. MDN page

This may require a newer version of NodeJS than what you are running.

const bcrypt = require('bcrypt');

// Async function allows us to use await
sign_up = async (req, res, next) => {

  const { email, password } = req.body;
  const User = User.findOne({ email: email });
  if (exUser) {
    return res.send('exist user');
  }

  // We await the result of the hash function
  const hash = await bcrypt.hash(password, 8);

  const user = new User({
    email: email,
    password: hash
  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    res.send('signup success');
  });
};

Do not use the bcrypt.hashSync function, as while it is running your server will not be able to do anything else.

Upvotes: 1

Related Questions