(現実の生活の中で他のコレクションへの参照)自分で - mongoose-encryptionのコードを使用して、集約が完了した後で復号化します。
コードのほとんどは、GitHubの(私のコードでdecryptOneと呼ばれる)から取られました: decryptSync function of mongoose-encryption
「トリッキー」のものは、内部ルックアップ値を復号化することでした - 内部文書はまた、「_ct」フィールドを持っています解読する必要があります。
let lookup: { [innerField: string]: string[]; } = {
user: ['bio']
};
this.decryptAggregation(aggregationResult, lookup);
My関数は、解読後に既知のルックアップコレクションとその必要なフィールドの辞書を取得します。この例では、ユーザーとその暗号化されたフィールドという名前の他のコレクションは、彼のバイオです。 lodash.pick
で - 私は私の希望のオブジェクトを持って、それらの機能が完全に解読された後
decryptAggregation(res: any[], innerLookup: { [innerField: string]: string[]; }) {
for (let doc of res) {
this.decryptSync(doc, innerLookup);
}
}
private decryptSync(doc: any, innerLookup: { [innerField: string]: string[]; }) {
this.decryptOne(doc, this.encryptedFields);
for (let innerObj in innerLookup) {
if (innerLookup.hasOwnProperty(innerObj)) {
this.decryptOne(doc[innerObj], innerLookup[innerObj]);
}
}
};
private decryptOne(doc: any, fields: string[]) {
let ct, ctWithIV, decipher, iv, idString, decryptedObject, decryptedObjectJSON, decipheredVal;
if (doc._ct) {
ctWithIV = doc._ct.hasOwnProperty('buffer') ? doc._ct.buffer : doc._ct;
iv = ctWithIV.slice(this.VERSION_LENGTH, this.VERSION_LENGTH + this.IV_LENGTH);
ct = ctWithIV.slice(this.VERSION_LENGTH + this.IV_LENGTH, ctWithIV.length);
decipher = crypto.createDecipheriv(this.ENCRYPTION_ALGORITHM, this.encryptionKey, iv);
try {
decryptedObjectJSON = decipher.update(ct, undefined, 'utf8') + decipher.final('utf8');
decryptedObject = JSON.parse(decryptedObjectJSON);
} catch (err) {
if (doc._id) {
idString = doc._id.toString();
} else {
idString = 'unknown';
}
throw new Error('Error parsing JSON during decrypt of ' + idString + ': ' + err);
}
fields.forEach((field) => {
decipheredVal = mpath.get(field, decryptedObject);
//JSON.parse returns {type: "Buffer", data: Buffer} for Buffers
//https://nodejs.org/api/buffer.html#buffer_buf_tojson
if (_.isObject(decipheredVal) && decipheredVal.type === "Buffer") {
this.setFieldValue(doc, field, decipheredVal.data);
} else {
this.setFieldValue(doc, field, decipheredVal);
}
});
doc._ct = undefined;
doc._ac = undefined;
}
}
は、実行する最後のものは、クライアントに望んでいたフィールドを投影するました