-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
43 lines (36 loc) · 1.23 KB
/
Copy pathplugin.js
File metadata and controls
43 lines (36 loc) · 1.23 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
var ee = require('easy-encryption');
/**
* Encrypted property plugin
* @param {Schema} schema
* @param {Object} options
* @param {string} options.secret
* @param {string} options.plaintextProperty
* @param {string} [options.ciphertextProperty]
*/
module.exports = function(schema, options) {
options = options || {};
if (!options.secret && !options.encryptionKey) {
throw new Error('Option `option.secret` is not defined.');
}
if (!options.plaintextProperty) {
throw new Error('Option `option.plaintextProperty` is not defined.');
}
var secret = options.secret || options.encryptionKey;
var plaintextProperty = options.plaintextProperty;
var ciphertextProperty = options.ciphertextProperty || options.encryptedProperty || 'encrypted_'+options.plaintextProperty;
//add a property for the encrypted value
var dfn = {};
dfn[ciphertextProperty] = 'String';
schema.add(dfn);
//add a virtual property for the plaintext value
schema.virtual(plaintextProperty)
.get(function() {
if (this[ciphertextProperty]) {
return JSON.parse(ee.decrypt(secret, this[ciphertextProperty]));
}
})
.set(function(value) {
this[ciphertextProperty] = ee.encrypt(secret, JSON.stringify(value));
})
;
};