【问题标题】:How to save password using Hook (beforeCreate) with sequelize and mysql如何使用 Hook (beforeCreate) 与 sequelize 和 mysql 保存密码
【发布时间】:2017-09-24 05:42:50
【问题描述】:

我是 sequelize 的新手,我有一个模型用户,必须在创建用户之前加密密码,我使用了一个钩子“beforeCreate”,但不起作用。我的意思是,密码正确加密,但 mysql 没有。

当我使用 console.log() 时,密码是加密的,但是当我去我的数据库时,密码是不加密的。

也许忘记了什么,但我遵循 sequelize 文档,我不知道我错过了什么

这是我的代码

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

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    因为你的beforeCreate钩子是异步操作,所以你应该调用回调函数或者Promise。这是回调示例:

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

    【讨论】:

    • 是的,没错。一些超级简单的事情,但我没有注意到我鼻子前面的错误。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多