忽略密码' '与Sequelize一起更新

时间:2017-09-04 21:03:08

标签: node.js sequelize.js

我需要帮助,我需要检查密码是否为" EMPTY"在更新子句中。如果为空,则应更新,否则不会。

import bcrypt from 'bcrypt-nodejs';

module.exports = function (sequelize, DataTypes) {
  const Users = sequelize.define('users', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      unique: true,
      autoIncrement: true,
      field: 'id_user_acess'
    },
    username: {
      type: DataTypes.STRING,
      allowNull: true
    },
    nome: {
      type: DataTypes.STRING,
      allowNull: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
      tableName: 'tb_user_acess',
      timestamps: false,
      classMethods: {
        generateHash: function(password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null);
        },
        comparePassword: function(canditate, password) {
          console.log(canditate);
          console.log(password);
          return bcrypt.compareSync(canditate, password);
        }
      },
      hooks: {
        beforeCreate: function (model) {
          let user = model.dataValues;
          user.password = Users.generateHash(user.password);
          return user;
        },
        beforeUpdate: function (model) {
          let user = model.dataValues;
          if(user.password == ''){
            exclude: user.password;
          }else{
            user.password = Users.generateHash(user.password); 
            console.log(user.password);
          }

          return user;
        }
      }
    });
  return Users;
};

我尝试应用某些东西,但效果不大 这是我的模型与sequ​​elize,PLZ一些光< 3

2 个答案:

答案 0 :(得分:0)

我认为您需要使用Sequelize Validations来确保提供的密码不为空。试试这样的事情

module.exports = function (sequelize, DataTypes) {
  const Users = sequelize.define('users', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      unique: true,
      autoIncrement: true,
      field: 'id_user_acess'
    },
    username: {
      type: DataTypes.STRING,
      allowNull: true
    },
    nome: {
      type: DataTypes.STRING,
      allowNull: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
          notEmpty: true
      }
    }

答案 1 :(得分:0)

如果我理解了这个问题,如果字段为空,则您不想更新用户的密码。如果是这样,只需添加一个检查并返回null。

  function hashPassword(user) {
     const password = user.password || user.attributes.password;
     if (!user.changed('password')) return null;
    return bcrypt.genSaltAsync(5).then(salt =>
      bcrypt.hashAsync(password, salt, null).then((hash) => {
        user.password = hash; // eslint-disable-line
      })
    );
  }

  User.beforeCreate(hashPassword);
  User.beforeUpdate(hashPassword);