eyght-models
Version:
Models for eyght
80 lines (70 loc) • 2.59 kB
JavaScript
let crypto = require('crypto'),
mongoose = require('mongoose'),
variableUtils = require('js-code-utils').VariableUtils;
mongoose.Promise = global.Promise;
let eygClientCredentialSchema = new mongoose.Schema({
clientID: {type: mongoose.Schema.Types.ObjectId, ref: 'eygClient'},
midID: {type: mongoose.Schema.Types.ObjectId, ref: 'eygClientMid'},
aggrAcctNum: {type: 'String'},
addlIDX500: {type: 'String'},
aggrID: {type: mongoose.Schema.Types.ObjectId, ref: 'genAggr'},
apiInfo: {type: 'Object'}, //encrypted
scrapeInfo: {type: 'Object'}, //encrypted
active: {type: 'Boolean', required: true},
inactDt: {type: 'Date'}, //store all dates in utc
inactRsnID: {type: mongoose.Schema.Types.ObjectId, ref: 'genInactRsn'}
}, {timestamps: true});
eygClientCredentialSchema.statics.encrypt = (text, configInfo) => {
let cipher,
iv;
iv = crypto.randomBytes(Number(configInfo.ivLength));
iv = iv.toString('base64').slice(0, configInfo.ivLength);
cipher = crypto.createCipheriv(configInfo.algorithm, configInfo.password, iv);
let typeThing = variableUtils.getType(text);
switch(typeThing) {
case 'STRING':
break;
case 'NUMBER':
text = text.toString();
break;
case 'NULL':
text = 'null';
break;
case 'UNDEFINED':
text = 'undefined';
break;
case 'BOOLEAN':
if (text === false) text = 'false';
else text = 'true';
break;
default:
throw new Error(`type not allowed to be encrypted: value - ${text}, type ${variableUtils.getType(text)}`);
}
return iv + cipher.update(text, 'utf8', configInfo.encoding) + cipher.final(configInfo.encoding);
};
eygClientCredentialSchema.statics.decrypt = (text, configInfo) => {
let decipher,
iv;
iv = text.slice(0, Number(configInfo.ivLength));
text = text.slice(Number(configInfo.ivLength));
decipher = crypto.createDecipheriv(configInfo.algorithm, configInfo.password, iv);
let decryptedThing = decipher.update(text, configInfo.encoding) + decipher.final();
if (isNaN(Number(decryptedThing))) {
switch(decryptedThing) {
case 'undefined':
decryptedThing = undefined;
break;
case 'null':
decryptedThing = null;
break;
case 'true':
decryptedThing = true;
break;
case 'false':
decryptedThing = false;
break;
}
} else if (decryptedThing[0] !== '0') decryptedThing = Number(decryptedThing);
return decryptedThing;
};
module.exports = mongoose.model('eygClientCredential', eygClientCredentialSchema, 'eygClientCredential');