简体   繁体   中英

Cannot get Bcrypt.js to encrypt Users model password

I'm working on my first Sequelize server and mySQL db. I can't seem to get bcrypt to work and hash my users passwords. I can get the model to successfully add to the db. But none of the methods for password encrypting seem to be working.

Here is my users model:

module.exports = function(sequelize, DataTypes) {

const bcrypt = require('bcrypt');

const Users = sequelize.define('users', {

    user_id: {
    
        allowNull: false,
        primaryKey: true,
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4
    },

   ..................

    user_password: {
        type:  DataTypes.STRING,
        validate: {
            // must have at least 6 characters no more than 16
            // must contain at least 1 capital and 1 number
            is: /^(?=.*\d)(?=.*[A-Z])(?!.*[^a-zA-Z0-9@#$^+=])(.{6,16})$/
            // must not be ['password', 'username', etc...]
        }
    }

}, {
  freezeTableName: true,
})

Users.beforeCreate(function(user, options) {
    return cryptPassword(user.user_password)
      .then(success => {
        user.user_password = success;
      })
      .catch(err => {
        if (err) console.log(err);
      });
  });

function cryptPassword(password) {
  console.log("cryptPassword " + password);
  return new Promise(function(resolve, reject) {
    bcrypt.genSalt(10, function(err, salt) {
      // Encrypt password using bycrpt module
      if (err) return reject(err);

      bcrypt.hash(password, salt, null, function(err, hash) {
        if (err) return reject(err);
        return resolve(hash);
      });
    });
  });

// Users.associate = function(models) {
//     Users.hasMany(models.comments, {foreignKey: "comment_id"})
//     Users.hasMany(models.posts,  {foreignKey: "post_id"})
}
return Users
};

Any help is appreciated, thanks!

bcrypt.hash expects 2-3 arguments, but got 4. It should be used like this:

bcrypt.hash(password, salt, function(err, hash) {
  if (err) return reject(err);
  return resolve(hash);
});

The completed working example:

const Users = sequelize.define(
  'users',
  {
    user_id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    user_password: {
      type: DataTypes.STRING,
      validate: { is: /^(?=.*\d)(?=.*[A-Z])(?!.*[^a-zA-Z0-9@#$^+=])(.{6,16})$/ },
    },
  },
  { freezeTableName: true },
);

Users.beforeCreate(function(user, options) {
  return cryptPassword(user.user_password)
    .then((success) => {
      user.user_password = success;
    })
    .catch((err) => console.log(err));
});

function cryptPassword(password) {
  console.log('cryptPassword ' + password);
  return new Promise(function(resolve, reject) {
    bcrypt.genSalt(10, function(err, salt) {
      if (err) return reject(err);

      bcrypt.hash(password, salt, function(err, hash) {
        if (err) return reject(err);
        return resolve(hash);
      });
    });
  });
}

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // seed
    await Users.create({ user_password: 'Abc123456' });
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

Check the data in the database:

=# select * from users;
               user_id                |                        user_password
--------------------------------------+--------------------------------------------------------------
 97763483-4c34-43e9-9a00-4782c7d59e79 | $2b$10$wtY1TTVx5aGSkeWwqIREUO7ZoCuEEC3KS5kPV1hv0/Nh5okQRHcQi
(1 row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM