30
server/models/decorators/Encrypted.ts
Normal file
30
server/models/decorators/Encrypted.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import vaults from "@server/database/vaults";
|
||||
|
||||
const key = "sequelize:vault";
|
||||
|
||||
/**
|
||||
* A decorator that stores the encrypted vault for a particular database column
|
||||
* so that it can be used by getters and setters. Must be accompanied by a
|
||||
* @Column(DataType.BLOB) annotation.
|
||||
*/
|
||||
export default function Encrypted(target: any, propertyKey: string) {
|
||||
Reflect.defineMetadata(key, vaults().vault(propertyKey), target, propertyKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of an encrypted column given the target and the property key.
|
||||
*/
|
||||
export function getEncryptedColumn(target: any, propertyKey: string): string {
|
||||
return Reflect.getMetadata(key, target, propertyKey).get.call(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of an encrypted column given the target and the property key.
|
||||
*/
|
||||
export function setEncryptedColumn(
|
||||
target: any,
|
||||
propertyKey: string,
|
||||
value: string
|
||||
) {
|
||||
Reflect.getMetadata(key, target, propertyKey).set.call(target, value);
|
||||
}
|
||||
50
server/models/decorators/Fix.ts
Normal file
50
server/models/decorators/Fix.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* A decorator that must be applied to every model definition to workaround
|
||||
* babel <> typescript incompatibility. See the following issue:
|
||||
* https://github.com/RobinBuschmann/sequelize-typescript/issues/612#issuecomment-491890977
|
||||
*
|
||||
* @param target model class
|
||||
*/
|
||||
|
||||
export default function Fix(target: any): void {
|
||||
return class extends target {
|
||||
constructor(...args: any[]) {
|
||||
super(...args);
|
||||
|
||||
const rawAttributes = Object.keys(new.target.rawAttributes);
|
||||
const associations = Object.keys(new.target.associations);
|
||||
|
||||
rawAttributes.forEach((propertyKey) => {
|
||||
// check if we already defined getter/setter – if so, do not override
|
||||
const desc = Object.getOwnPropertyDescriptor(
|
||||
target.prototype,
|
||||
propertyKey
|
||||
);
|
||||
if (desc) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.defineProperty(this, propertyKey, {
|
||||
get() {
|
||||
return this.getDataValue(propertyKey);
|
||||
},
|
||||
set(value) {
|
||||
this.setDataValue(propertyKey, value);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
associations.forEach((propertyKey) => {
|
||||
Object.defineProperty(this, propertyKey, {
|
||||
get() {
|
||||
return this.dataValues[propertyKey];
|
||||
},
|
||||
set(value) {
|
||||
// sets without changing the "changed" flag for associations
|
||||
this.dataValues[propertyKey] = value;
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
} as any;
|
||||
}
|
||||
Reference in New Issue
Block a user