Skip to content

Instantly share code, notes, and snippets.

@p15martin
Last active August 29, 2015 13:57
Show Gist options
  • Save p15martin/9358923 to your computer and use it in GitHub Desktop.
Save p15martin/9358923 to your computer and use it in GitHub Desktop.
This Gist is a simple spike, which demonstrates authentication with Concur and retrieval of the user's profile information. To use it sign up for a developer sandbox at Concur (https://developer.concur.com), once you have registered it will create a default app and display your API key.
/*jslint node:true */
var https = require('https'),
util = require('util'),
libxmljs = require("libxmljs"),
Q = require('q'),
concurHost = 'www.concursolutions.com';
function httpGet(httpOptions) {
'use strict';
var deferred = Q.defer(),
request = https.get(httpOptions, function (response) {
var result = '';
response.on('data', function (chunk) {
result += chunk;
});
response.on('end', function () {
deferred.resolve(result);
});
});
request.on('error', function (error) {
deferred.reject(error);
});
request.end();
return deferred.promise;
}
function getAuthToken(username, password, consumerKey) {
'use strict';
var deferred = Q.defer(),
loginId = util.format('%s:%s', username, password),
encodedLoginId = new Buffer(loginId || '').toString('base64'),
authString = util.format('Basic %s', encodedLoginId),
concurAuthPath = '/net2/oauth2/accesstoken.ashx',
httpHeaders = {
'X-ConsumerKey': consumerKey,
Authorization: authString
},
httpOptions = {
host: concurHost,
path: concurAuthPath,
headers: httpHeaders
};
httpGet(httpOptions)
.then(function (xmlToken) {
var xmlAccessToken = libxmljs.parseXml(xmlToken);
deferred.resolve(xmlAccessToken.get('//Token').text());
})
.fail(function (error) {
deferred.reject(error);
})
.done();
return deferred.promise;
}
function formatOAuthString(token) {
'use strict';
return util.format('OAuth %s', token);
}
function getUserInformation(token) {
'use strict';
var deferred = Q.defer(),
concurUserInformationPath = '/api/user/v1.0/User',
httpHeaders = {
Authorization: formatOAuthString(token)
},
httpOptions = {
host: concurHost,
path: concurUserInformationPath,
headers: httpHeaders
};
httpGet(httpOptions)
.then(function (result) {
deferred.resolve(result);
})
.fail(function (error) {
deferred.reject(error);
})
.done();
return deferred.promise;
}
function run(username, password, consumerKey) {
'use strict';
getAuthToken(username, password, consumerKey)
.then(getUserInformation)
.then(function (userInformation) {
console.log(userInformation);
})
.fail(function (error) {
console.log(error);
})
.done();
}
var args = process.argv.splice(2);
if (args.length !== 3) {
console.error('usage: node user-info.js [username] [password] [consumer_key]');
process.exit(1);
} else {
run(args[0], args[1], args[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment