import { sequelize } from '../../utils/sequelize.js'; import { DataTypes } from 'sequelize'; import User from './user.js'; import UserParamType from '../type/user_param.js'; import { encrypt, decrypt, generateIv } from '../../utils/encryption.js'; const UserParam = sequelize.define('user_param', { userId: { type: DataTypes.INTEGER, allowNull: false, references: { model: User, key: 'id' } }, paramTypeId: { type: DataTypes.INTEGER, allowNull: false, references: { model: UserParamType, key: 'id' } }, value: { type: DataTypes.STRING, allowNull: false, set(value) { if (value) { try { const iv = generateIv(); this.setDataValue('iv', iv.toString('hex')); this.setDataValue('value', encrypt(value.toString(), iv)); } catch (error) { this.setDataValue('value', ''); } } }, get() { try { const value = this.getDataValue('value'); const iv = Buffer.from(this.getDataValue('iv'), 'hex'); return decrypt(value, iv); } catch (error) { return ''; } } }, iv: { type: DataTypes.STRING, allowNull: false } }, { tableName: 'user_param', schema: 'community', underscored: true, indexes: [ { unique: true, fields: ['user_id', 'param_type_id'] } ] }); export default UserParam;