1

im new on sequelize, i have a model user and have to encrypt the password before user create, i use a hook "beforeCreate", but doesn't work. i mean, th password its correctly encrypt, but the mysql does not.

when i use a console.log() the password is encrypt, but When i go to my db, the password isn't encrypt.

maybe forget somethng, but i follow the sequelize docs, i dont know what i missing

here's my code

//db
const mysql = require('mysql2')
const Sequelize = require('sequelize')
const connection = new Sequelize(config.MySql_db, config.MySql_user, 
config.Mysql_pass, 
              {
                host: config.MySql_host,
                dialect: 'mysql',
                port: config.MySql_port
              });

const UsuarioSchema = connection.define('Usuario', {
nombres: {type: Sequelize.STRING, allowNull: false},
apellidos: {type: Sequelize.STRING, allowNull: false},
email: {type: Sequelize.STRING, unique: true, lowercase: true, allowNull: false},
clave: {type: Sequelize.STRING, allowNull: false /*select:false*/}, //para que los get no retornen el password
fechaRegistro: {type: Sequelize.DATE, defaultValue: Sequelize.NOW},
fechaUltimoIngreso: {type: Sequelize.DATE},
perfil: {type: Sequelize.STRING, enum: ['Admin', 'Concursante'], defaultValue: 'Admin'}
  }, {
  timestamps: false,
  freezeTableName: true, //Evita que mysql pluralice el nombre de la BD
  hooks: {
      beforeCreate: (user)=>{
        bcrypt.genSalt(10, (err, salt) => {
                    if(err)
                        throw new Error(err)
                    bcrypt.hash(user.clave, salt, null, (err, hash) => {
                        if(err)
                            throw new Error(err)
                        else{
                            user.clave = hash  
                        }
                    })
                })
      }
  }
  });

UsuarioSchema.sync({logging: console.log}).then(function(){

}).catch((err)=>{
    console.log(`Error sincronizando el modelo Usuario ${err}`)
})

1 Answer 1

1

It's because your beforeCreate hook is async operation, so you should call callback function or Promise. Here is callback example:

beforeCreate((user, options, cb) => {
    bcrypt.genSalt(10, (err, salt) => {   
      if (err) return cb(err);  
      bcrypt.hash(user.clave, salt, null, (err, hash) => {
         if (err) return cb(err);  
         user.clave = hash  
         return cb(null, options);
       })
    })  
});
Sign up to request clarification or add additional context in comments.

1 Comment

yeah, thats rigth. Something super simple, but I had not noticed the error that was in front of my nose. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.