Skip to content

Commit 63bf232

Browse files
committed
If email and private key is not provided, try to retrieve token from the GCE metaserver. Fixes #3.
1 parent 9e880dc commit 63bf232

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

lib/common/connection.js

+22
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ var GAPIToken = require('gapitoken'),
1818
async = require('async'),
1919
req = require('request');
2020

21+
var metadataTokenUrl = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token';
22+
2123
/**
2224
* Token represents an access token
2325
* @param {string} accessToken Access token.
@@ -80,6 +82,26 @@ Connection.prototype.connect = function(callback) {
8082
*/
8183
Connection.prototype.fetchToken = function(callback) {
8284
var that = this;
85+
if (!this.email || !this.privateKey) {
86+
// We should be on GCE, try to retrieve token from
87+
// the metadata from server.
88+
req({
89+
method: 'get',
90+
uri: metadataTokenUrl,
91+
headers: {
92+
'X-Google-Metadata-Request': 'True'
93+
},
94+
json: true
95+
}, function(err, res, body) {
96+
if (err || !body.access_token) {
97+
// TODO: Provide better context about the error here.
98+
return callback(err);
99+
}
100+
var exp = new Date(body.token_expires * 1000);
101+
callback(null, new Token(body.access_token, exp));
102+
});
103+
return;
104+
}
83105
var gapi = new GAPIToken({
84106
iss: this.email,
85107
keyFile: this.privateKey,

0 commit comments

Comments
 (0)