-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongoose-encrypted-string.js
More file actions
41 lines (35 loc) · 1.18 KB
/
mongoose-encrypted-string.js
File metadata and controls
41 lines (35 loc) · 1.18 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
const SchemaType = require('mongoose').SchemaType;
const sc = require('@tsmx/string-crypto');
const allowedAlgorithms = ['aes-256-gcm', 'aes-256-cbc'];
class EncryptedString extends SchemaType {
constructor(key, options) {
options.get = (v) => {
return sc.decrypt(v, {
key: EncryptedString.options.key,
passNull: true
});
};
options.set = (v) => {
return sc.encrypt(v, {
key: EncryptedString.options.key,
passNull: true,
algorithm: EncryptedString.options.algorithm
});
};
super(key, options, 'EncryptedString');
}
cast(val) {
return String(val);
}
static options = {
key: null
};
}
module.exports.registerEncryptedString = function (mongoose, key, algorithm = 'aes-256-gcm') {
if (!allowedAlgorithms.includes(algorithm)) {
throw new Error(`Invalid algorithm '${algorithm}'. Allowed: ${allowedAlgorithms.join(', ')}`);
}
EncryptedString.options.key = key;
EncryptedString.options.algorithm = algorithm;
mongoose.Schema.Types.EncryptedString = EncryptedString;
};