Skip to content

Commit

Permalink
Merge pull request #374 from jasonall/master
Browse files Browse the repository at this point in the history
Adds usable auth, taking a dependency on the google-auth-library repo.
  • Loading branch information
tbetbetbe committed Mar 10, 2015
2 parents 2a71fd5 + f339a9b commit 32660eb
Show file tree
Hide file tree
Showing 18 changed files with 351 additions and 2,276 deletions.
4 changes: 3 additions & 1 deletion examples/compute.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ var headers = { 'Metadata-Flavor': 'Google' };
// This example can be run from a GCE VM in your project. The example fetches
// your project ID from the VM's metadata server, and then uses the Compute API
// to fetch the list of GCE zones in your project.

//
// See the defaultauth.js sample for an alternate way of fetching compute credentials.
//
google.options({ auth: new google.auth.Compute() });
request.get({ uri: uri, headers: headers }, function(error, response, project) {
if (!error && response.statusCode == 200) {
Expand Down
57 changes: 57 additions & 0 deletions examples/defaultauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var google = require('../lib/googleapis.js');
var compute = google.compute('v1');

/**
* The getApplicationDefault method creates the appropriate type of credential client for you,
* depending upon whether the client is running in Google App Engine, Google Compute Engine, a
* Managed VM, or on a local developer machine. This allows you to write one set of auth code that
* will work in all cases. It most situations, it is advisable to use the getApplicationDefault
* method rather than creating your own JWT or Compute client directly.
*
* Note: In order to run on a local developer machine, it is necessary to download a private key
* file to your machine, and to set a local environment variable pointing to the location of the
* file. Create a service account using the Google Developers Console using the section APIs & Auth.
* Select "Generate new JSON key" and download the resulting file. Once this is done, set the
* GOOGLE_APPLICATION_CREDENTIALS environment variable to point to the location of the .json file.
*
* See also:
* https://developers.google.com/accounts/docs/application-default-credentials
*/

// Get the appropriate type of credential client, depending upon the runtime environment.
google.auth.getApplicationDefault(function(err, authClient) {
if (err) {
res.send('Failed to get the default credentials: ' + String(err));
return;
}
// The createScopedRequired method returns true when running on GAE or a local developer
// machine. In that case, the desired scopes must be passed in manually. When the code is
// running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
// See https://cloud.google.com/compute/docs/authentication for more information.
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
// Scopes can be specified either as an array or as a single, space-delimited string.
authClient = authClient.createScoped(['https://www.googleapis.com/auth/compute']);
}
// Fetch the list of GCE zones within a project.
// NOTE: You must fill in your valid project ID before running this sample!
var projectId = 'fill in your project id here!';
compute.zones.list({ project: projectId, auth: authClient }, function(error, result) {
console.log(error, result);
});
});
2 changes: 2 additions & 0 deletions examples/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ var drive = google.drive('v2');
* https://github.com/joyent/node/issues/4050#issuecomment-8816304)
* so the private key must be extracted and converted to a passphrase-less
* RSA key: openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem
*
* See the defaultauth.js sample for an alternate way of fetching compute credentials.
*/
var authClient = new google.auth.JWT(
'service-account-email@developer.gserviceaccount.com',
Expand Down
44 changes: 5 additions & 39 deletions lib/auth/authclient.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,10 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
* This code has been moved to the google-auth-library repo, at
* https://github.com/google/google-auth-library-nodejs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var DefaultTransporter = require('../transporters.js');

function AuthClient() {
this.transporter = new DefaultTransporter();
}

/**
* Provides an alternative request
* implementations with auth credentials.
* Please update your references to point to the google-auth-library implementation,
* rather than this file.
*/
AuthClient.prototype.request = function() {
throw new Error('Not implemented yet.');
};

/**
* Sets auth credentials.
* @param {object} credentials Credentials.
*/
AuthClient.prototype.setCredentials = function(credentials) {
this.credentials = credentials;
};
module.exports = require('google-auth-library/lib/auth/authclient.js');

/**
* Export AuthClient.
*/
module.exports = AuthClient;
78 changes: 5 additions & 73 deletions lib/auth/computeclient.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,10 @@
/**
* Copyright 2013 Google Inc. All Rights Reserved.
* This code has been moved to the google-auth-library repo, at
* https://github.com/google/google-auth-library-nodejs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var Auth2Client = require('./oauth2client.js');
var util = require('util');

/**
* Google Compute Engine metadata server token endpoint.
* @private
*/
Compute.GOOGLE_OAUTH2_TOKEN_URL_ =
'http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token';

/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
* @constructor@constructor
* Please update your references to point to the google-auth-library implementation,
* rather than this file.
*/
function Compute() {
Compute.super_.call(this);
// Start with an expired refresh token, which will automatically be refreshed
// before the first API call is made.
this.credentials = {
refresh_token: 'compute-placeholder',
expiry_date: 1
};
}

/**
* Inherit from Auth2Client.
*/
util.inherits(Compute, Auth2Client);
module.exports = require('google-auth-library/lib/auth/computeclient.js');

/**
* Refreshes the access token.
* @param {object=} ignored_
* @param {function=} opt_callback Optional callback.
* @private
*/
Compute.prototype.refreshToken_ = function(ignored_, opt_callback) {
var uri = this.opts.tokenUrl || Compute.GOOGLE_OAUTH2_TOKEN_URL_;
// request for new token
this.transporter.request({
method: 'GET',
uri: uri,
json: true
}, function(err, tokens) {
if (!err && tokens && tokens.expires_in) {
tokens.expiry_date = ((new Date()).getTime() + (tokens.expires_in * 1000));
delete tokens.expires_in;
}
if (opt_callback) {
opt_callback(err, tokens);
}
});
};

/**
* Export Compute.
*/
module.exports = Compute;
104 changes: 5 additions & 99 deletions lib/auth/jwtclient.js
Original file line number Diff line number Diff line change
@@ -1,103 +1,9 @@
/**
* Copyright 2013 Google Inc. All Rights Reserved.
* This code has been moved to the google-auth-library repo, at
* https://github.com/google/google-auth-library-nodejs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var Auth2Client = require('./oauth2client.js');
var util = require('util');
var GAPI = require('gapitoken');

/**
* JWT service account credentials.
*
* Retrieve access token using gapitoken.
*
* @param {string=} email service account email address.
* @param {string=} keyFile path to private key file.
* @param {string=} key value of key
* @param {(string|array)=} scopes list of requested scopes or a single scope.
* @param {string=} subject impersonated account's email address.
* @constructor
*/
function JWT(email, keyFile, key, scopes, subject) {
JWT.super_.call(this);
this.email = email;
this.subject = subject;
this.keyFile = keyFile;
this.key = key;
this.scopes = scopes;
this.GAPI = GAPI;
}

/**
* Inherit from Auth2Client.
*/
util.inherits(JWT, Auth2Client);

/**
* Get the initial access token using gapitoken.
* @param {function=} opt_callback Optional callback.
* Please update your references to point to the google-auth-library implementation,
* rather than this file.
*/
JWT.prototype.authorize = function(opt_callback) {
var that = this;
that.gapi = new that.GAPI({
iss: that.email,
sub: that.subject,
scope: that.scopes instanceof Array ? that.scopes.join(' ') : that.scopes,
keyFile: that.keyFile,
key: that.key
}, function(err) {
if (err) {
if (opt_callback) {
opt_callback(err, null);
}
} else {
that.refreshToken_(null, function(err, result) {
if (!err) {
that.credentials = result;
that.credentials.refresh_token = 'jwt-placeholder';
}
if (opt_callback) {
opt_callback(err, result);
}
});
}
});
};

/**
* Refreshes the access token.
* @param {object=} ignored_
* @param {function=} opt_callback Optional callback.
* @private
*/
JWT.prototype.refreshToken_ = function(ignored_, opt_callback) {
var that = this;
that.gapi.getToken(function(err, token) {
if (opt_callback) {
opt_callback(err, {
access_token: token,
token_type: 'Bearer',
expiry_date: that.gapi.token_expires * 1000
});
}
});
};

/**
* Export Compute.
*/
module.exports = JWT;
module.exports = require('google-auth-library/lib/auth/jwtclient.js');
71 changes: 5 additions & 66 deletions lib/auth/loginticket.js
Original file line number Diff line number Diff line change
@@ -1,71 +1,10 @@
/**
* Copyright 2014 Google Inc. All Rights Reserved.
* This code has been moved to the google-auth-library repo, at
* https://github.com/google/google-auth-library-nodejs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var USER_ATTR = 'sub';

/**
* Create a simple class to extract user ID from an ID Token
*
* @param {string} env Envelope of the jwt
* @param {string} pay Payload of the jwt
* @constructor
*/
function LoginTicket(env, pay) {
var envelope = env;
var payload = pay;

this.getEnvelope = function() {
return envelope;
};

this.getPayload = function() {
return payload;
};
}

/**
* Create a simple class to extract user ID from an ID Token
*
* @return {string} The user ID
* Please update your references to point to the google-auth-library implementation,
* rather than this file.
*/
LoginTicket.prototype.getUserId = function() {
var payload = this.getPayload();
if (payload && payload[USER_ATTR]) {
return payload[USER_ATTR];
}

return null;
};

/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
*
* @return {Object} The envelope and payload
*/
LoginTicket.prototype.getAttributes = function() {
return {
'envelope': this.getEnvelope(),
'payload': this.getPayload()
};
};
module.exports = require('google-auth-library/lib/auth/loginticket.js');

/**
* Export LoginTicket.
*/
module.exports = LoginTicket;
Loading

0 comments on commit 32660eb

Please sign in to comment.