SHARE
TWEET

Untitled

a guest Jan 21st, 2020 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const checkSignature = async (obj) => {
  2.   let objVerify = {
  3.     _id: obj._id,
  4.     createdBy: obj.createdBy,
  5.     updatedBy: obj.updatedBy
  6.   };
  7.   Object.keys(_validate_schema).forEach(key => {
  8.     if (obj[key]) objVerify[key] = obj[key]
  9.   });
  10.  
  11.   if (!verifySignature(objVerify, obj.signature))
  12.     throw new PersonalDataStorageError("Verify signature failed!");
  13. }
  14.  
  15. const encryptSecureFields = (keys, data, initIv) => {
  16.   let object = {};
  17.   keys.forEach(key => {
  18.     const iv = parseInt((initIv).toString().slice(0, 16), 16) + _secure_keys.indexOf(key);
  19.     object[key] = data[key] ? encryptData(data[key], String(iv)) : undefined;
  20.   });
  21.   return object;
  22. }
  23.  
  24. const decryptSecureFields = (data) => {
  25.   let resObj = {};
  26.   _secure_keys.forEach((key, index) => {
  27.     const iv = parseInt((data._id).toString().slice(0, 16), 16) + index;
  28.     resObj[key] = data[key] ? decryptData(data[key], String(iv)) : undefined;
  29.   });
  30.   return resObj;
  31. };
  32.  
  33. const keyValueOpenSchema = (object) => {
  34.   let openPart = {};
  35.   _open_keys.forEach( key => openPart[key] = object[key] );
  36.   return openPart;
  37. }
  38.  
  39. const keyValueSecureSchema = (securePart, object) => {
  40.   _secure_keys.forEach( key => securePart[key] = object[key] );
  41.   return securePart;
  42. }
  43.  
  44. const filterValue = (obj, key, value) => obj.find(v => v[key] === value);
  45.  
  46. const updateOpenData = (objectFromDb, newData) => {
  47.   let resObject = {};
  48.   _open_keys.forEach(key => {
  49.     if (objectFromDb[key]) resObject[key] = objectFromDb[key];
  50.   });
  51.   _open_keys.forEach(key => {
  52.     if (Object.keys(newData).includes(key)) resObject[key] = newData[key];
  53.   });
  54.   return resObject;
  55. }
  56.  
  57. const createEIndex = async (object, data) => {
  58.   let promises = [];
  59.  
  60.   Object.keys(_search).forEach(async key => {
  61.     promises.push(new Promise (async (resolve) => {
  62.       if (_search[key] === "entire"){
  63.         promises.push(object[`${key}_eindex`] = await createIndexForEntireSearch(data[key]));
  64.         resolve();
  65.       } else resolve();
  66.     }));
  67.   });
  68.  
  69.   return await Promise.all(promises);
  70. };
  71.  
  72. const updateWIndex = async (data, id, opts) => {
  73.   const tmp = [];
  74.   Object.keys(data).forEach(async key => {
  75.     tmp.push(new Promise( async resolve => {
  76.       if (_search[key] === "word"){
  77.         let promises = [];
  78.         unique(data[key].split(" ")).forEach(word => promises.push(AddAs(word, id, key, opts)));
  79.         const arrAsId = await Promise.all(promises);
  80.  
  81.         let objAsId;
  82.         arrAsId.map(obj => objAsId = {...objAsId, ...obj});
  83.  
  84.         await AddAd(id, objAsId, key, opts);
  85.         resolve();
  86.       } else resolve();
  87.     }))
  88.   });
  89.   await Promise.all(tmp);
  90. };
  91.  
  92. const deleteWIndex = async (fileId) => {
  93.   let promises = [];
  94.   Object.keys(_search).forEach(async key => {
  95.     promises.push(new Promise(async resolve => {
  96.       if (_search[key] === "word"){
  97.         await Delete(fileId, key);
  98.         resolve();
  99.       } else resolve();
  100.     }))
  101.   });
  102.   await Promise.all(promises);
  103. };
  104.  
  105. module.exports.getModel = () => _model;
  106.  
  107. module.exports.setIndexSettings = async (schema, opts, secret) => {
  108.   setWIndexKeys(secret)
  109.   Object.keys(schema).forEach(key => {
  110.     if (schema[key].security) {
  111.       _search[key] = schema[key].search && (schema[key].search === "entire" || schema[key].search === "word") ? schema[key].search : "nosearch";
  112.     }
  113.   });
  114.  
  115.   let promises = [];
  116.   Object.keys(_search).forEach(async key => {
  117.     promises.push(new Promise(async resolve => {
  118.       if (_search[key] === "word") await setWIndexSettings(key, opts);
  119.       resolve();
  120.     }));
  121.   });
  122.  
  123.   await Promise.all(promises);
  124.   return "Ok";
  125. };
  126.  
  127. module.exports.generateModel = async (initSchema, modelName, schemaOptions) => {
  128.   _validate_schema = await generateValidationScheme(initSchema);
  129.   _open_keys = generateOpenKeys(initSchema);
  130.   _secure_keys = generateSecureKeys(initSchema);
  131.  
  132.   let tmp_schema = {};
  133.   _open_keys.forEach((item) => tmp_schema[item] = _validate_schema[item]); //add to schema open data
  134.   _secure_keys.forEach((item) => tmp_schema[item] = { type: String }); //add to schema secure data
  135.  
  136.  
  137.   //add index field for entire search
  138.   _secure_keys.forEach((item) => {
  139.     if (initSchema[item].search === "entire"){
  140.       tmp_schema[`${item}_eindex`] = {
  141.         type: Buffer,
  142.         required: true
  143.       };
  144.     };
  145.   });
  146.  
  147.   const newSchema = new mongoose.Schema({
  148.     ...tmp_schema,
  149.     signature: { type: Buffer },
  150.     createdBy: { type: String },
  151.     updatedBy: { type: String }
  152.   },{
  153.     timestamps: {
  154.       createdAt: "createdAt",
  155.       updatedAt: "updatedAt"
  156.     }, ...schemaOptions });
  157.    
  158.   _model = mongoose.model(modelName, newSchema);
  159. };
  160.  
  161. module.exports.insert = async (data, opts) => {
  162.   if (data){
  163.     const id = mongoose.Types.ObjectId(); //_id = iv
  164.     let object = {
  165.       _id: id,
  166.       ...keyValueOpenSchema(data),
  167.       ...encryptSecureFields(_secure_keys, data, id),
  168.       createdBy: data._author || "PersonalDataStorage",
  169.       updatedBy: data._author || "PersonalDataStorage"
  170.     };
  171.  
  172.     object.signature = createSignature(object);
  173.  
  174.     //add eindex
  175.     await createEIndex(object, data);
  176.     await updateWIndex(data, id, opts);
  177.    
  178.     const instance = new _model(object);
  179.     const resp = await instance.save(opts).catch(err => {
  180.       throw new PersonalDataStorageError(err);
  181.     });
  182.  
  183.     return resp._id;
  184.   }
  185.   throw new PersonalDataStorageError("Data is undefined");
  186. };
  187.  
  188. module.exports.update = async (id, data, opts = {}) => {
  189.   if (id && data){
  190.     const [ object ] = await _model.find({ _id: id }).exec().catch(err => {
  191.       throw new PersonalDataStorageError(err);
  192.     });
  193.  
  194.     if (!object) throw new PersonalDataStorageError("Record in personalDataStorage does not exists!");
  195.     await checkSignature(object);
  196.  
  197.     let resObject = {
  198.       _id: object._id,
  199.       ...updateOpenData(object, data),
  200.       ...encryptSecureFields(matchKeys(_secure_keys, data), data, object._id),
  201.       createdBy: data._author || "PersonalDataStorage",
  202.       updatedBy: data._author || "PersonalDataStorage"
  203.     };
  204.  
  205.     resObject.signature = createSignature(resObject);
  206.     opts.useFindAndModify = false;
  207.     const resp = await _model.findOneAndUpdate({ _id: id }, resObject, opts).catch(err =>{
  208.       throw new PersonalDataStorageError(err);
  209.     });
  210.  
  211.     return resp._id;
  212.   }
  213.   else throw new PersonalDataStorageError("id || data is undefined");
  214. };
  215.  
  216. module.exports.getDataByID = async (id) => {
  217.   const [ object ] = await _model.find({ _id: id }).exec().catch(err => {
  218.     throw new PersonalDataStorageError(err);
  219.   });
  220.  
  221.   if (!object) throw new PersonalDataStorageError("Data in personalDataStorage not exists by this id!");
  222.   await checkSignature(object);
  223.  
  224.   return {
  225.     ...keyValueOpenSchema(object),
  226.     ...decryptSecureFields(object),
  227.     createdAt: object.createdAt,
  228.     updatedAt: object.updatedAt
  229.   };
  230. };
  231.  
  232. module.exports.find = async (key, value) => {
  233.   if (_search[key] === undefined) {
  234.     const objects = await _model.find({ [key]: value }).exec().catch(err => {
  235.       throw new PersonalDataStorageError(err);
  236.     });
  237.  
  238.     let result = [];
  239.     objects.forEach(async object => {
  240.       if (!object) throw new PersonalDataStorageError(`Data in personalDataStorage not exists by ${key}`);
  241.       await checkSignature(object);
  242.      
  243.       result.push({
  244.         ...keyValueOpenSchema(object),
  245.         ...decryptSecureFields(object),
  246.         createdAt: object.createdAt,
  247.         updatedAt: object.updatedAt
  248.       });
  249.     });
  250.  
  251.     return result;
  252.   }
  253.   else if (_search[key] === "entire"){
  254.     let obj = {};
  255.     obj[`${key}_eindex`] = await createIndexForEntireSearch(value)
  256.  
  257.     const objects = await _model.find(obj).exec().catch(err => {
  258.       throw new PersonalDataStorageError(err);
  259.     });
  260.  
  261.     let result = [];
  262.     objects.forEach(async object => {
  263.       if (!object) throw new PersonalDataStorageError(`Data in personalDataStorage not exists by ${key}`);
  264.       await checkSignature(object);
  265.  
  266.       result.push({
  267.         ...keyValueOpenSchema(object),
  268.         ...decryptSecureFields(object),
  269.         createdAt: object.createdAt,
  270.         updatedAt: object.updatedAt
  271.       });
  272.     });
  273.  
  274.     result.forEach((resObj, index) => {
  275.       if (resObj[key] !== value) result.splice(index, 1);
  276.     });
  277.  
  278.     return result;
  279.   }
  280.   else if (_search[key] === "word"){
  281.     const arrId = await Search(value, key);
  282.     return arrId;
  283.   }
  284. };
  285.  
  286. module.exports.deleteById = async (id) => {
  287.   const [ object ] = await _model.find({ _id: id }).exec().catch(err => {
  288.     throw new PersonalDataStorageError(err);
  289.   });
  290.  
  291.   if (!object) return {};
  292.   await checkSignature(object);
  293.   await deleteWIndex(id);
  294.  
  295.   return _model.deleteOne({ _id: id });
  296. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top