-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsequelize.js
More file actions
97 lines (82 loc) · 2.16 KB
/
sequelize.js
File metadata and controls
97 lines (82 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const Sequelize = require("sequelize");
const Keyring = require("./keyring").keyring;
function isString(value) {
return typeof value === "string" || value instanceof String;
}
function getModelOptions(record) {
// This handles the change introduced by sequelize@v6.
return record._modelOptions || record.constructor.options;
}
function beforeSave(record, options) {
const {
keys,
keyringIdColumn,
encryption,
columns,
digestSalt,
} = getModelOptions(record).keyring;
const keyring = Keyring(keys, { encryption, digestSalt });
columns.forEach((column) => {
const digestColumn = `${column}_digest`;
const value = record[column];
let encrypted = null;
let digest = null;
let keyringId = record[keyringIdColumn] || keyring.currentId();
if (isString(value)) {
[encrypted, keyringId, digest] = keyring.encrypt(value);
}
record[`encrypted_${column}`] = encrypted;
record[keyringIdColumn] = keyringId;
// This handles the change introduced by sequelize@v5.
const attributes =
record.attributes || Object.keys(record.constructor.rawAttributes);
if (attributes.includes(digestColumn)) {
record[digestColumn] = digest;
}
});
}
function afterFind(record) {
if (!record) {
return;
} else if (record instanceof Array) {
return record.map(afterFind);
}
const {
keys,
keyringIdColumn,
encryption,
columns,
digestSalt,
} = getModelOptions(record).keyring;
const keyring = Keyring(keys, { encryption, digestSalt });
const keyringId = record[keyringIdColumn];
columns.forEach((column) => {
const keyringId = record[keyringIdColumn];
const encrypted = record[`encrypted_${column}`];
const value = isString(encrypted)
? keyring.decrypt(encrypted, keyringId)
: null;
record[column] = value;
});
}
function setup(
model,
{
keys,
columns,
digestSalt,
encryption = "aes-128-cbc",
keyringIdColumn = "keyring_id",
},
) {
model.options.keyring = {
keys,
columns,
encryption,
keyringIdColumn,
digestSalt,
};
model.beforeSave(beforeSave);
model.afterFind(afterFind);
}
module.exports = setup;