Skip to content

Instantly share code, notes, and snippets.

@timcash
Created August 29, 2014 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timcash/ec3a76708ef021102efb to your computer and use it in GitHub Desktop.
Save timcash/ec3a76708ef021102efb to your computer and use it in GitHub Desktop.
/**
* Copyright 2012 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 readline = require('readline');
var google = require('googleapis');
var OAuth2Client = google.auth.OAuth2;
var comp = google.compute('v1');
// Client ID and client secret are available at
// https://code.google.com/apis/console
var CLIENT_ID = 'my_client_id_for_web_application';
var CLIENT_SECRET = 'my_client_secret';
var REDIRECT_URL = 'http://localhost:8080/oauth2callback'; // I am just testing on locahost right now
var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getAccessToken(oauth2Client, callback) {
// generate consent page url
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // will return a refresh token
scope: 'https://www.googleapis.com/auth/compute' // can be a space-delimited string or an array of scopes
});
console.log('Visit the url: ', url);
rl.question('Enter the code here:', function(code) {
// request access token
oauth2Client.getToken(code, function(err, tokens) {
// set tokens to the client
// TODO: tokens should be set by OAuth2 client.
oauth2Client.setCredentials(tokens);
callback();
});
});
}
// retrieve an access token
getAccessToken(oauth2Client, function() {
// retrieve user profile
comp.instances.list({ project:"my_project_id", zone:"us-central1-b" }, function(err, data) {
if (err) {
console.log('An error occured', err);
return;
}
console.log(data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment