Implemented personal settings

This commit is contained in:
Torsten Schulz
2024-07-22 18:14:12 +02:00
parent cd0699f3fd
commit 89842ff6c5
34 changed files with 899 additions and 113 deletions

View File

@@ -26,9 +26,25 @@ const UserParam = sequelize.define('user_param', {
allowNull: false,
set(value) {
if (value) {
const iv = generateIv();
this.setDataValue('iv', iv.toString('hex'));
this.setDataValue('value', encrypt(value, iv));
try {
const iv = generateIv();
console.log(value);
this.setDataValue('iv', iv.toString('hex'));
this.setDataValue('value', encrypt(value, iv));
} catch (error) {
console.log('Error setting value:', 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) {
console.log('Error getting value:', error);
return '';
}
}
},
@@ -40,31 +56,29 @@ const UserParam = sequelize.define('user_param', {
tableName: 'user_param',
schema: 'community',
underscored: true,
hooks: {
beforeSave: (userParam) => {
if (userParam.value && !userParam.iv) {
const iv = generateIv();
userParam.iv = iv.toString('hex');
userParam.value = encrypt(userParam.value, iv);
}
},
afterFind: (userParams) => {
if (userParams) {
if (Array.isArray(userParams)) {
userParams.forEach((userParam) => {
const iv = Buffer.from(userParam.iv, 'hex');
userParam.value = decrypt(userParam.value, iv);
});
} else {
const iv = Buffer.from(userParams.iv, 'hex');
userParams.value = decrypt(userParams.value, iv);
}
}
indexes: [
{
unique: true,
fields: ['user_id', 'param_type_id']
}
}
]
});
UserParam.belongsTo(User, { foreignKey: 'userId' });
UserParam.belongsTo(UserParamType, { foreignKey: 'paramTypeId' });
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;