Sequelize:在创建挂钩之前无法正常工作

时间:2017-09-30 13:42:45

标签: javascript node.js sequelize.js

我试图对我通过Sequelize创建的模型执行beforeCreate操作。我在尝试创建用户之前尝试保存密码和盐。但是,创建的用户没有加密密码或salt。我对Node.JS不太熟悉,但我认为这与它的异步性质有关。知道如何正确引入回调,以便我的创建函数按预期运行吗?

型号:



'use strict';
var Promise = require("bluebird"); 
var bcrypt =Promise.promisifyAll(require("bcrypt-nodejs"));
const SALT_ROUNDS = 10; 

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    username: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { notEmpty: true } }, 
    email: { type: DataTypes.STRING, unique: true, allowNull: false, isEmail: true },
    phone_number: DataTypes.STRING,
    password_hash: { type: DataTypes.STRING, allowNull: false, unique: true, validate: { notEmpty: true } }, 
    password_salt: DataTypes.STRING,
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    user_type: DataTypes.INTEGER,
    two_factor_enabled: { type: DataTypes.BOOLEAN, defaultValue: false, },
    email_verified: DataTypes.DATE,
    active: { type: DataTypes.BOOLEAN, defaultValue: true, },
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      },
      validPassword: function(password, passwd, callback) {
        bcrypt.compare(password, passwd, function(err, isMatch) {
          if (isMatch) {
            return callback(null, true);
          } else {
            return callback(null, false); 
          }
        });
      },
    },
    hooks: {
	beforeCreate: function(user, {}) {
		bcrypt.genSalt(SALT_ROUNDS, function(err, salt) {
			bcrypt.hash(user.password_hash, salt, function(){}, function(err, hash) {
				if (err) {
					return sequelize.Promise.reject(err); 
				}

	        		user.setDataValue('password_hash',hash);
				user.setDataValue('password_salt',salt);
			});

		});
	}
    },
    instanceMethods: {
	generateHash: function(password) {
		return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null); 
	},
	validPassword: function(password) {
		return bcrypt.compareSync(password, this.password); 
	}
    }
  });

  //User.associate = (models) => {
  //  User.hasMany(models.UserType, {
  //    foreignKey: 'userId',
  //    as: 'userTypes'
  //  });
  //};

  return User;
};




这就是电话:



return db.User
			.create({
				first_name: req.body.first_name,
				last_name: req.body.last_name, 
				username: req.body.username,
				email: req.body.email, 
				password_hash: req.body.password	
			})
			.then(user => res.status(201).send(user))
			.catch(error => res.status(400).send(error));
		},




1 个答案:

答案 0 :(得分:0)

Personnaly我使用了crypto,包含在node.js中:https://nodejs.org/api/crypto.html

我有一个创建哈希的函数:

function createHash(password, salt) {
  const generatedSalt = typeof salt !== 'undefined' ? salt : crypto.randomBytes(128).toString('base64');
  const hmac = crypto.createHmac('sha256', generatedSalt);
  hmac.update(password);
  const hashedPassword = hmac.digest('hex');
  return {
    salt: generatedSalt,
    hash: hashedPassword
  };
}

在我的用户模型中:

beforeCreate: (user, options, cb) => {
  const saltAndHash = createHash(user.password);
  user.salt = saltAndHash.salt;
  user.password = saltAndHash.hash;
  return cb(null, options);
}

我希望这会对你有帮助;)