82 lines
2.1 KiB
JavaScript
82 lines
2.1 KiB
JavaScript
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']
|
|
}
|
|
]
|
|
});
|
|
|
|
UserParam.upsertParam = async function (userId, paramTypeId, value) {
|
|
try {
|
|
const [userParam, created] = await UserParam.findOrCreate({
|
|
where: { userId, paramTypeId },
|
|
defaults: { value }
|
|
});
|
|
|
|
if (!created) {
|
|
userParam.value = value;
|
|
await userParam.save();
|
|
}
|
|
} catch (error) {
|
|
console.error('Error in upsertParam:', error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export default UserParam;
|