Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. createESLPackage: function (req, res) {
  2.         // Copié de requestSignatories
  3.         var docId = req.body.doc_id;
  4.         var users = req.body.selected;
  5.         var self = this;
  6.         var fileG = null;
  7.         var usersG = null;
  8.         var clientdocusign = null;
  9.         var userExtToCreate = [];
  10.         var userExtKnown = [];
  11.         var uids = [];
  12.         // Fin de copie
  13.  
  14.         // Copié de https://www.esignlive.com/blog/esignlive-how-to-creating-a-simple-node-js-web-application/
  15.         var request = require('request');
  16.         var formidable = require('formidable');
  17.         var http = require('http');
  18.         var token;
  19.         var packageid;
  20.         var api_key = 'Z1A2Rzl4ZzJSdklIOlpSRk9LenVrUzhZMw=='; // clef Lionel
  21.         // Fin de copie
  22.  
  23.         var jsonPayload = {
  24.             "roles": [
  25.                 {
  26.                     "id": "Signer1",
  27.                     "type": "SIGNER",
  28.                     "signers": [
  29.                         {
  30.                             "firstName": "lionel",
  31.                             "lastName": "jamaigne",
  32.                             "email": "lionel.jam@docunify.com",
  33.                             "id": "Signer1"
  34.                         }
  35.                     ]
  36.                 },
  37.                 {
  38.                     "id": "Sender1",
  39.                     "type": "SIGNER",
  40.                     "signers": [
  41.                         {
  42.                             "firstName": "Haris",
  43.                             "lastName": "Haidary",
  44.                             "email": "sender@example.com",
  45.                             "id": "Sender1"
  46.                         }
  47.                     ]
  48.                 }
  49.             ],
  50.             "documents": [
  51.                 {
  52.                     "fields": [
  53.                         {
  54.                             "value": "lionel",
  55.                             "name": "first_name"
  56.                         },
  57.                         {
  58.                             "value": "jamaigne",
  59.                             "name": "last_name"
  60.                         },
  61.                         {
  62.                             "value": "rue du truc",
  63.                             "name": "address"
  64.                         },
  65.                         {
  66.                             "value": "martelange",
  67.                             "name": "city"
  68.                         },
  69.                         {
  70.                             "value": "8832",
  71.                             "name": "zip"
  72.                         },
  73.                         {
  74.                             "value": "saipas",
  75.                             "name": "state"
  76.                         },
  77.                         {
  78.                             "value": "belgique",
  79.                             "name": "country"
  80.                         },
  81.                         {
  82.                             "value": "32499463127",
  83.                             "name": "phone_number"
  84.                         },
  85.                         {
  86.                             "value": "lionel.jamaigne@docunify.com",
  87.                             "name": "email"
  88.                         },
  89.                         {
  90.                             "value": "docunify sa",
  91.                             "name": "company"
  92.                         },
  93.                         {
  94.                             "value": "44",
  95.                             "name": "policy_number"
  96.                         }
  97.                     ],
  98.                     "name": "Sample Contract",
  99.                     "id": "contract",
  100.                     "extract": true
  101.                 }
  102.             ],
  103.             "name": "NodeJS Example",
  104.             "type": "PACKAGE",
  105.             "status": "DRAFT"
  106.         };
  107.  
  108.         // Je cherche un document sur base de l'id client
  109.         Q.fcall(function () {
  110.             var query = {
  111.                 _id: docId,
  112.                 type: 'Upload',
  113.                 idClient: req.params._idclient,
  114.                 safe: false
  115.             };
  116.             return self.model.findOne(query).exec();
  117.         })
  118.             // Je récupère le document
  119.             .then(function (document) {
  120.                 console.log('get users');
  121.                 if (!document) {
  122.                     throw new Error(res.i18n('Document not found'));
  123.                 }
  124.                 if (document.contentType != 'application/pdf') {
  125.                     throw new Error('Only pdf');
  126.                 }
  127.                 if (!utils.checkPermissionsFolders(req.userInfo.clients, document.idClient, document.folderId)) {
  128.                     throw new Error(res.i18n('Not authorized'));
  129.                 }
  130.                 if (document.signatories.length > 0) {
  131.                     throw new Error(res.i18n('Already request for signatories'));
  132.                 }
  133.                 fileG = document;
  134.                 var query = User.find({
  135.                     _id: {
  136.                         $in: users
  137.                     },
  138.                     active: true,
  139.                     clients: {
  140.                         $elemMatch: {
  141.                             _id: document.idClient,
  142.                             active: true
  143.                         }
  144.                     }
  145.                 });
  146.                 query.select('_id firstname lastname email notifications mobile prefix phoneType language');
  147.                 return query.exec();
  148.             })
  149.             // Je recupère les utilisateurs
  150.             .then(function (users) {
  151.                 console.log('get users 2');
  152.                 var userClientEmail = [];
  153.                 var already = [];
  154.  
  155.                 usersG = users;
  156.                 usersG.forEach(function (user) {
  157.                     userClientEmail.push(user.email);
  158.                 });
  159.                 if (req.body.extuser_select.length > 0) {
  160.                     req.body.extuser_select.forEach(function (user) {
  161.                         if (userClientEmail.indexOf(user.email) === -1 && already.indexOf(user.email) === -1) {
  162.                             already.push(user.email);
  163.                             if (user.known) {
  164.                                 userExtKnown.push(user.email);
  165.                             } else {
  166.                                 userExtToCreate.push(user);
  167.                             }
  168.                         }
  169.                     });
  170.                 }
  171.                 return Q.fcall(function () {
  172.                     return null
  173.                 });
  174.             })
  175.  
  176.             .then(function () {
  177.                 console.log('get externals known');
  178.                 var prom = Q.fcall(function () {
  179.                     return []
  180.                 });
  181.  
  182.                 if (userExtKnown.length > 0) {
  183.                     var q = Q.defer();
  184.                     User.find({
  185.                         email: {
  186.                             $in: userExtKnown
  187.                         }
  188.                     }, function (err, users) {
  189.                         q.resolve(users);
  190.  
  191.                     })
  192.                     prom = q.promise;
  193.                 }
  194.                 return prom;
  195.             })
  196.  
  197.             .then(function (users) {
  198.                 console.log('get externals unknown');
  199.                 users.forEach(function (user) {
  200.                     user.external = true;
  201.                     usersG.push(user);
  202.                 });
  203.                 var all_promises = [];
  204.                 if (userExtToCreate.length > 0 && userExtToCreate.length < 10) {
  205.                     userExtToCreate.forEach(function (user) {
  206.                         var q = Q.defer();
  207.                         authy.register_user(user.email, user.phone.replace(/[^0-9]/g, ''), user.phoneprefix.replace(/[^0-9]/g, ''), function (err, res) {
  208.                             if (err) throw new Error(err);
  209.                             user.authyId = res.user.id;
  210.                             return q.resolve(user);
  211.                         });
  212.                         all_promises.push(q.promise);
  213.                     });
  214.                     return Q.all(all_promises);
  215.                 } else {
  216.                     return Q.fcall(function () {
  217.                         return []
  218.                     });
  219.                 }
  220.  
  221.             })
  222.  
  223.             .then(function (users) {
  224.                 var all_promises = [];
  225.                 if (users.length > 0 && users.length < 10) {
  226.                     console.log('create users');
  227.                     users.forEach(function (user) {
  228.                         var q = Q.defer();
  229.                         var toCreate = {
  230.                             firstname: user.firstname,
  231.                             lastname: user.name,
  232.                             email: user.email.toLowerCase(),
  233.                             prefix: user.phoneprefix.replace(/[^0-9]/g, ''),
  234.                             mobile: user.phone.replace(/[^0-9]/g, ''),
  235.                             phoneType: user.phoneType,
  236.                             createdby: req.userInfo._id,
  237.                             firstActivation: true,
  238.                             tokenActivation: crypto.randomBytes(32).toString('hex').slice(0, 20),
  239.                             password: utils.genPassword(),
  240.                             active: false,
  241.                             clients: [],
  242.                             authyId: user.authyId
  243.                         };
  244.                         User.create(toCreate, function (err, newuser) {
  245.                             q.resolve(newuser);
  246.                         });
  247.                         all_promises.push(q.promise);
  248.                     });
  249.                     return Q.all(all_promises);
  250.                 } else {
  251.                     return Q.fcall(function () {
  252.                         return []
  253.                     });
  254.                 }
  255.  
  256.             })
  257.  
  258.             .then(function (users) {
  259.                 console.log('users');
  260.                 users.forEach(function (user) {
  261.                     user.external = true;
  262.                     user.newuser = true;
  263.                     usersG.push(user);
  264.                 });
  265.                 var q = Q.defer();
  266.  
  267.                 gfs.findOne({
  268.                     _id: fileG.fileId
  269.                 }, function (err, file) {
  270.                     if (err) throw new Error(res.i18n('Doc not found'));
  271.                     if (!file) throw new Error(res.i18n('File not found'));
  272.                     return q.resolve(file);
  273.                 });
  274.                 return q.promise;
  275.             })
  276.  
  277.             .then(function (file) {
  278.                 console.log('get file');
  279.                 var cipher = crypto.createDecipher('aes-256-cbc', file.metadata.privateKey + config.secrets.salt_token);
  280.                 var stream = gfs.createReadStream({
  281.                     _id: fileG.fileId
  282.                 }).pipe(cipher);
  283.  
  284.                 var buffers = [];
  285.                 var q = Q.defer();
  286.                 stream.on('data', function (buffer) {
  287.                     buffers.push(buffer);
  288.                 });
  289.                 stream.on('end', function () {
  290.                     var buffer = Buffer.concat(buffers);
  291.                     q.resolve(buffer);
  292.                 });
  293.                 return [q.promise, file];
  294.             })
  295.  
  296.             .spread(function(document, fichier){
  297.                 console.log('creation du package');
  298.  
  299.                 var options =
  300.                         {
  301.                             method: 'POST',
  302.                             url: 'https://sandbox.esignlive.com/api/packages',
  303.                             headers: {
  304.                                 accept: 'application/json; esl-api-version=11.0',
  305.                                 authorization: 'Basic ' + api_key,
  306.                                 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
  307.                             },
  308.                             formData: {
  309.                                 file: {
  310.                                     value: document,
  311.                                     options: {filename: fichier.filename, contentType: null}
  312.                                 },
  313.                                 payload: JSON.stringify(jsonPayload)
  314.                             }
  315.                     };
  316.                 console.log('je fais la requete1');
  317.                 request(options, function (error, response, body)
  318.                 {
  319.                     if (error) throw new Error(error);
  320.  
  321.                     var tmp = JSON.parse(body);
  322.                     packageid = tmp['id'];
  323.                     console.log('1the package id is: ' + packageid);
  324.  
  325.                 });
  326.                 console.log('je renvoie null');
  327.                 return Q.fcall(function () {
  328.                     return null
  329.                 });
  330.             })
  331.  
  332.             .then(function(){
  333.                 var options =
  334.                     {
  335.                         method: 'POST',
  336.                         url: 'https://sandbox.esignlive.com/api/signerAuthenticationTokens',
  337.                         headers:
  338.                             {
  339.                                 'content-type': 'application/json',
  340.                                 accept: 'application/json',
  341.                                 authorization: 'Basic ' + api_key},
  342.                         body: {
  343.                             packageId: packageid,
  344.                             signerId: 'Signer1'
  345.                         },
  346.                         json: true
  347.                     };
  348.                 console.log('je fais la requete2');
  349.                 request(options, function (error, response, body) {
  350.                     if (error) throw new Error(error);
  351.                     console.log('body: ' + body);
  352.                     token = body['value'];
  353.                     console.log('2the package id is: ' + packageid);
  354.                     console.log("The session token is: " + token);
  355.                 });
  356.             })
  357.  
  358.             .catch(function (error) {
  359.                 res.handleError(error.message);
  360.             })
  361.  
  362.  
  363.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement