Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- createESLPackage: function (req, res) {
- // Copié de requestSignatories
- var docId = req.body.doc_id;
- var users = req.body.selected;
- var self = this;
- var fileG = null;
- var usersG = null;
- var clientdocusign = null;
- var userExtToCreate = [];
- var userExtKnown = [];
- var uids = [];
- // Fin de copie
- // Copié de https://www.esignlive.com/blog/esignlive-how-to-creating-a-simple-node-js-web-application/
- var request = require('request');
- var formidable = require('formidable');
- var http = require('http');
- var token;
- var packageid;
- var api_key = 'Z1A2Rzl4ZzJSdklIOlpSRk9LenVrUzhZMw=='; // clef Lionel
- // Fin de copie
- var jsonPayload = {
- "roles": [
- {
- "id": "Signer1",
- "type": "SIGNER",
- "signers": [
- {
- "firstName": "lionel",
- "lastName": "jamaigne",
- "email": "lionel.jam@docunify.com",
- "id": "Signer1"
- }
- ]
- },
- {
- "id": "Sender1",
- "type": "SIGNER",
- "signers": [
- {
- "firstName": "Haris",
- "lastName": "Haidary",
- "email": "sender@example.com",
- "id": "Sender1"
- }
- ]
- }
- ],
- "documents": [
- {
- "fields": [
- {
- "value": "lionel",
- "name": "first_name"
- },
- {
- "value": "jamaigne",
- "name": "last_name"
- },
- {
- "value": "rue du truc",
- "name": "address"
- },
- {
- "value": "martelange",
- "name": "city"
- },
- {
- "value": "8832",
- "name": "zip"
- },
- {
- "value": "saipas",
- "name": "state"
- },
- {
- "value": "belgique",
- "name": "country"
- },
- {
- "value": "32499463127",
- "name": "phone_number"
- },
- {
- "value": "lionel.jamaigne@docunify.com",
- "name": "email"
- },
- {
- "value": "docunify sa",
- "name": "company"
- },
- {
- "value": "44",
- "name": "policy_number"
- }
- ],
- "name": "Sample Contract",
- "id": "contract",
- "extract": true
- }
- ],
- "name": "NodeJS Example",
- "type": "PACKAGE",
- "status": "DRAFT"
- };
- // Je cherche un document sur base de l'id client
- Q.fcall(function () {
- var query = {
- _id: docId,
- type: 'Upload',
- idClient: req.params._idclient,
- safe: false
- };
- return self.model.findOne(query).exec();
- })
- // Je récupère le document
- .then(function (document) {
- console.log('get users');
- if (!document) {
- throw new Error(res.i18n('Document not found'));
- }
- if (document.contentType != 'application/pdf') {
- throw new Error('Only pdf');
- }
- if (!utils.checkPermissionsFolders(req.userInfo.clients, document.idClient, document.folderId)) {
- throw new Error(res.i18n('Not authorized'));
- }
- if (document.signatories.length > 0) {
- throw new Error(res.i18n('Already request for signatories'));
- }
- fileG = document;
- var query = User.find({
- _id: {
- $in: users
- },
- active: true,
- clients: {
- $elemMatch: {
- _id: document.idClient,
- active: true
- }
- }
- });
- query.select('_id firstname lastname email notifications mobile prefix phoneType language');
- return query.exec();
- })
- // Je recupère les utilisateurs
- .then(function (users) {
- console.log('get users 2');
- var userClientEmail = [];
- var already = [];
- usersG = users;
- usersG.forEach(function (user) {
- userClientEmail.push(user.email);
- });
- if (req.body.extuser_select.length > 0) {
- req.body.extuser_select.forEach(function (user) {
- if (userClientEmail.indexOf(user.email) === -1 && already.indexOf(user.email) === -1) {
- already.push(user.email);
- if (user.known) {
- userExtKnown.push(user.email);
- } else {
- userExtToCreate.push(user);
- }
- }
- });
- }
- return Q.fcall(function () {
- return null
- });
- })
- .then(function () {
- console.log('get externals known');
- var prom = Q.fcall(function () {
- return []
- });
- if (userExtKnown.length > 0) {
- var q = Q.defer();
- User.find({
- email: {
- $in: userExtKnown
- }
- }, function (err, users) {
- q.resolve(users);
- })
- prom = q.promise;
- }
- return prom;
- })
- .then(function (users) {
- console.log('get externals unknown');
- users.forEach(function (user) {
- user.external = true;
- usersG.push(user);
- });
- var all_promises = [];
- if (userExtToCreate.length > 0 && userExtToCreate.length < 10) {
- userExtToCreate.forEach(function (user) {
- var q = Q.defer();
- authy.register_user(user.email, user.phone.replace(/[^0-9]/g, ''), user.phoneprefix.replace(/[^0-9]/g, ''), function (err, res) {
- if (err) throw new Error(err);
- user.authyId = res.user.id;
- return q.resolve(user);
- });
- all_promises.push(q.promise);
- });
- return Q.all(all_promises);
- } else {
- return Q.fcall(function () {
- return []
- });
- }
- })
- .then(function (users) {
- var all_promises = [];
- if (users.length > 0 && users.length < 10) {
- console.log('create users');
- users.forEach(function (user) {
- var q = Q.defer();
- var toCreate = {
- firstname: user.firstname,
- lastname: user.name,
- email: user.email.toLowerCase(),
- prefix: user.phoneprefix.replace(/[^0-9]/g, ''),
- mobile: user.phone.replace(/[^0-9]/g, ''),
- phoneType: user.phoneType,
- createdby: req.userInfo._id,
- firstActivation: true,
- tokenActivation: crypto.randomBytes(32).toString('hex').slice(0, 20),
- password: utils.genPassword(),
- active: false,
- clients: [],
- authyId: user.authyId
- };
- User.create(toCreate, function (err, newuser) {
- q.resolve(newuser);
- });
- all_promises.push(q.promise);
- });
- return Q.all(all_promises);
- } else {
- return Q.fcall(function () {
- return []
- });
- }
- })
- .then(function (users) {
- console.log('users');
- users.forEach(function (user) {
- user.external = true;
- user.newuser = true;
- usersG.push(user);
- });
- var q = Q.defer();
- gfs.findOne({
- _id: fileG.fileId
- }, function (err, file) {
- if (err) throw new Error(res.i18n('Doc not found'));
- if (!file) throw new Error(res.i18n('File not found'));
- return q.resolve(file);
- });
- return q.promise;
- })
- .then(function (file) {
- console.log('get file');
- var cipher = crypto.createDecipher('aes-256-cbc', file.metadata.privateKey + config.secrets.salt_token);
- var stream = gfs.createReadStream({
- _id: fileG.fileId
- }).pipe(cipher);
- var buffers = [];
- var q = Q.defer();
- stream.on('data', function (buffer) {
- buffers.push(buffer);
- });
- stream.on('end', function () {
- var buffer = Buffer.concat(buffers);
- q.resolve(buffer);
- });
- return [q.promise, file];
- })
- .spread(function(document, fichier){
- console.log('creation du package');
- var options =
- {
- method: 'POST',
- url: 'https://sandbox.esignlive.com/api/packages',
- headers: {
- accept: 'application/json; esl-api-version=11.0',
- authorization: 'Basic ' + api_key,
- 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
- },
- formData: {
- file: {
- value: document,
- options: {filename: fichier.filename, contentType: null}
- },
- payload: JSON.stringify(jsonPayload)
- }
- };
- console.log('je fais la requete1');
- request(options, function (error, response, body)
- {
- if (error) throw new Error(error);
- var tmp = JSON.parse(body);
- packageid = tmp['id'];
- console.log('1the package id is: ' + packageid);
- });
- console.log('je renvoie null');
- return Q.fcall(function () {
- return null
- });
- })
- .then(function(){
- var options =
- {
- method: 'POST',
- url: 'https://sandbox.esignlive.com/api/signerAuthenticationTokens',
- headers:
- {
- 'content-type': 'application/json',
- accept: 'application/json',
- authorization: 'Basic ' + api_key},
- body: {
- packageId: packageid,
- signerId: 'Signer1'
- },
- json: true
- };
- console.log('je fais la requete2');
- request(options, function (error, response, body) {
- if (error) throw new Error(error);
- console.log('body: ' + body);
- token = body['value'];
- console.log('2the package id is: ' + packageid);
- console.log("The session token is: " + token);
- });
- })
- .catch(function (error) {
- res.handleError(error.message);
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement