1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| 'use strict';
var jsforce = require('jsforce'); var Promise = jsforce.Promise; var request = require('request');
var CONNECTION_CONFIG_PROPS = 'loginUrl,accessToken,instanceUrl,refreshToken,clientId,clientSecret,redirectUri,logLevel,version'.split( ',' );
function connect(options) { var conn; return Promise.resolve() .then(function() { if (options.connection) { console.log(' ** connection ** '); conn = jsforce.registry.getConnection(options.connection); if (!conn) { throw new Error('No connection named "' + options.connection + '" in registry'); } return null; } else if (options.refresh_token) { return LoginUsingRT( options.refresh_token, options.client_id, options.client_secret, options.loginUrl ); } else if (options.username && options.password) { var config = {}; CONNECTION_CONFIG_PROPS.forEach(function(prop) { if (options[prop]) { config[prop] = options[prop]; } }); conn = new jsforce.Connection(config); return conn.login(options.username, options.password); } else { return conn.identity().catch(function(err) { throw new Error( 'Credential to salesforce server is not found in options.\n' + 'Specify "username" and "password" in options, or give any other credentials.' ); }); } }) .then(function(result) { if (result != null) { if (options.refresh_token) { conn = new jsforce.Connection({ loginUrl: options.loginUrl, instanceUrl: result.instance_url, accessToken: result.access_token, version: '45.0' });
return conn; } } }) .then(function() { if (options.logger) { var logger = options.logger; return conn.identity().then(function(identity) { logger.log('Logged in as: ' + identity.username); return conn; }); } return conn; }); }
function LoginUsingRT(refresh_token, client_id, client_secret,loginUrl) { var SFoptions = { method: 'POST', url: loginUrl+'/services/oauth2/token', qs: { grant_type: 'refresh_token', refresh_token: refresh_token, client_id: client_id, client_secret: client_secret }, headers: { 'cache-control': 'no-cache' } };
return new Promise(function(resolve, reject) { request(SFoptions, function(error, response, body) { if (error) { reject(error); } else { resolve(JSON.parse(body)); } }); }); }
module.exports = connect;
|