Skip to content

Commit

Permalink
common: Avoid using require to read JSON file key.
Browse files Browse the repository at this point in the history
`require` is not working well with relative paths.
  • Loading branch information
rakyll committed Aug 7, 2014
1 parent fd60490 commit 7641028
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions lib/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@

'use strict';

var fs = require('fs');
var GAPIToken = require('gapitoken');
var req = require('request');
var path = require('path');
var pkg = require('../../package.json');
var util = require('./util');

Expand Down Expand Up @@ -53,12 +55,9 @@ Token.prototype.isExpired = function() {
* @param {Object} opts Options.
*/
function Connection(opts) {
var credentials = opts.keyFilename && require(opts.keyFilename) || {};
// client email for the service account
this.email = credentials.client_email;
// contains the contents of a pem file
this.privateKey = credentials.private_key;
this.opts = opts || {};

this.credentials = null;
this.scopes = opts.scopes || [];
this.token = null; // existing access token, if exists

Expand Down Expand Up @@ -92,7 +91,8 @@ Connection.prototype.connect = function(callback) {
* @param {Function} callback Callback function.
*/
Connection.prototype.fetchToken = function(callback) {
if (!this.email || !this.privateKey) {
var that = this;
if (!this.opts.keyFilename) {
// We should be on GCE, try to retrieve token from
// the metadata from server.
req({
Expand All @@ -112,9 +112,24 @@ Connection.prototype.fetchToken = function(callback) {
});
return;
}
if (!this.credentials) {
// read key file for once and cache the contents.
fs.readFile(this.opts.keyFilename, function(err, data) {
if (err) {
callback(err); return;
}
that.credentials = JSON.parse(data);
that.fetchServiceAccountToken_(callback);
});
return;
}
this.fetchServiceAccountToken_(callback);
};

Connection.prototype.fetchServiceAccountToken_ = function(callback) {
var gapi = new GAPIToken({
iss: this.email,
key: this.privateKey,
iss: this.credentials.client_email,
key: this.credentials.private_key,
scope: this.scopes.join(' ')
}, function(err) {
if (err) {
Expand Down

0 comments on commit 7641028

Please sign in to comment.