makitocode
makitocode

Reputation: 948

How to save password using Hook (beforeCreate) with sequelize and mysql

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}`)
})

Upvotes: 1

Views: 1825

Answers (1)

Den Rupp
Den Rupp

Reputation: 307

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);
       })
    })  
});

Upvotes: 1

Related Questions