|
const rp = require('request-promise-native') |
|
const url = require('url') |
|
// require('request-debug')(rp) |
|
|
|
// Point this to your API |
|
const API = 'api.system.domain.com' |
|
|
|
// fetch the API information, from which we can grab the authorization endpoint |
|
rp({ |
|
uri: 'https://' + API + '/v2/info', |
|
json: true |
|
}).then(function (data) { |
|
return data.authorization_endpoint |
|
}).then(function (loginApi) { |
|
// get an auth token, which we need to get an auth code |
|
// this requires your user & password |
|
rp({ |
|
uri: loginApi + '/oauth/token', |
|
method: 'POST', |
|
json: true, |
|
form: { |
|
'grant_type': 'password', |
|
// insert your user name & password below |
|
'username': 'your-user-name', |
|
'password': 'your-password' |
|
}, |
|
headers: { |
|
// this uses `cf` as the client and `` as the client secret |
|
// most CF installations have this client configured as it's what |
|
// the cf cli uses |
|
'Authorization': 'Basic ' + new Buffer('cf:').toString('base64') |
|
} |
|
}).then(function (data) { |
|
return [loginApi, data.access_token] |
|
}).then(function (data) { |
|
var loginApi = data[0] |
|
var accessToken = data[1] |
|
// request an auth code |
|
// we use the ssh-proxy client id as most CF envs will have this client |
|
// we set response type to code, so we get the auth code |
|
// we also add the bearer token as an authorization header, this is the |
|
// auth token we received from the previous HTTP request |
|
// we don't want to redirect as the Location header will contain our |
|
// newly minted auth code |
|
rp({ |
|
uri: loginApi + '/oauth/authorize', |
|
method: 'GET', |
|
json: true, |
|
qs: { |
|
client_id: 'ssh-proxy', |
|
grant_type: 'authorization_code', |
|
response_type: 'code' |
|
}, |
|
headers: { |
|
'Authorization': 'Bearer ' + accessToken |
|
}, |
|
followRedirect: false |
|
}).then(function (data) { |
|
console.log('Sorry, didn\'t get the expected response.') |
|
}).catch(function (err) { |
|
if (err.statusCode === 302) { |
|
var data = url.parse(err.response.headers.location, true) |
|
// just printing the auth code, but you can do whatever you want with it |
|
console.log('Access Code is ' + data.query.code) |
|
} |
|
}) |
|
}) |
|
}) |