首页 文章

在没有存储的Sequelize中创建模型属性

提问于
浏览
0

我使用Sequelize作为我的ORM . 我想创建一个具有没有相关存储的属性的模型(即没有相应的表列) . 这些属性可能包含getter和setter,也可能有验证 .

如何在 .save() 上创建不会存储到光盘的实例级属性?

The Scenario

我有一个LocalLogins模型 . 我的模型有 usernamesalt ,盐渍 password 和无盐 rawPassword . 每次设置 password 时,都会对该值进行加盐和散列 . 哈希的结果成为新密码 . 原始"raw"值保存为 rawPassword .

我不想存储未加密的 rawPassword ,但是只要调用 .save() 它就会用于验证 . 这允许模型要求具有一定强度的密码 .

The Attempt

我尝试将字段设置为 '' ,但遗憾的是没有效果 .

var LocalLogin = sequelize.define('LocalLogin', {
  username: {
    allowNull: false,
    field: 'username',
    type: DataTypes.STRING,
  },
  password: {
    allowNull: false,
    field: 'password',
    type: DataTypes.STRING,
  },
  rawPassword: {
    field: '',
    type: DataTypes.STRING
  },
  salt: {
    allowNull: false,
    defaultValue: function() {
      var buf = crypto.randomBytes(32);
      return buf.toString('hex');
    },
    field: 'salt',
    type: DataTypes.STRING,
    }
}, {
  getterMethods: {
    password: function() { return undefined; },
    rawPassword: function() { return undefined; },
    salt: function() { return undefined; }
  },
  setterMethods: {
    password: function(val) {
      // Salt and hash the password
      this.setDataValue('rawPassword', val);
      if(typeof val === 'string')
        this.setDataValue('password', hash(val + this.getDataValue('selt')));
    },
    salt: function(val) {
      // Salt cannot be modified
      return null;
    }
  },
  validate: {
    passwordCheck: function() {
      // Has a new password been set?
      if(this.getDataValue('rawPassword') == null)
        return

      // Did they try to set the password as something other than a string?
      if(typeof this.getDataValue('rawPassword') !== 'string')
        throw new Error('Password must be a string');

      // Make sure the password is long enough
      if(this.getDataValue('rawPassword').length < 6)
        throw new Error('Password must be longer than six characters.');
    }
  }
});

1 回答

相关问题