Skip to content

Commit

Permalink
refactor(auth)!: pulling in updated idempotent google-auth-library (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
bcoe committed Jul 29, 2019
1 parent 86074f3 commit 168ad6b
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 54 deletions.
14 changes: 8 additions & 6 deletions README.md
Expand Up @@ -239,16 +239,17 @@ const compute = google.compute('v1');
async function main () {
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
// environment variables.
const auth = await google.auth.getClient({
const auth = new google.auth.GoogleAuth({
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: ['https://www.googleapis.com/auth/compute']
});
const authClient = await auth.getClient();

// obtain the current project Id
const project = await google.auth.getProjectId();
const project = await auth.getProjectId();

// Fetch the list of GCE zones within a project.
const res = await compute.zones.list({ project, auth });
const res = await compute.zones.list({ project, auth: authClient });
console.log(res.data);
}

Expand Down Expand Up @@ -440,18 +441,19 @@ async function main() {

// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
// environment variables.
const client = await google.auth.getClient({
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
const authClient = await auth.getClient();

const projectId = await google.auth.getProjectId();
const projectId = await auth.getProjectId();

const request = {
projectId,
datasetId: '<YOUR_DATASET_ID>',

// This is a "request-level" option
auth: client
auth: authClient
};

const res = await bigquery.datasets.delete(request);
Expand Down
4 changes: 2 additions & 2 deletions package.json
@@ -1,8 +1,8 @@
{
"license": "Apache-2.0",
"dependencies": {
"google-auth-library": "^4.0.0",
"googleapis-common": "^2.0.2"
"google-auth-library": "^5.1.0",
"googleapis-common": "^3.0.0"
},
"files": [
"build/src",
Expand Down
4 changes: 2 additions & 2 deletions samples/defaultauth.js
Expand Up @@ -36,13 +36,13 @@ const compute = google.compute('v1');
// Get the appropriate type of credential client, depending upon the runtime environment.
async function main() {
// The `getClient` method will choose a service based authentication model
const auth = await google.auth.getClient({
const auth = new google.auth.GoogleAuth({
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: ['https://www.googleapis.com/auth/compute'],
});

// Obtain the current project Id
const project = await google.auth.getProjectId();
const project = await auth.getProjectId();

// Get the list of available compute zones for your project
const res = await compute.zones.list({project, auth});
Expand Down
63 changes: 32 additions & 31 deletions samples/drive/download.js
Expand Up @@ -26,37 +26,38 @@ const drive = google.drive({
});

async function runSample(fileId) {
return new Promise(async (resolve, reject) => {
const filePath = path.join(os.tmpdir(), uuid.v4());
console.log(`writing to ${filePath}`);
const dest = fs.createWriteStream(filePath);
let progress = 0;
// For converting document formats, and for downloading template
// documents, see the method drive.files.export():
// https://developers.google.com/drive/api/v3/manage-downloads
const res = await drive.files.get(
{fileId, alt: 'media'},
{responseType: 'stream'}
);
res.data
.on('end', () => {
console.log('Done downloading file.');
resolve(filePath);
})
.on('error', err => {
console.error('Error downloading file.');
reject(err);
})
.on('data', d => {
progress += d.length;
if (process.stdout.isTTY) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Downloaded ${progress} bytes`);
}
})
.pipe(dest);
});
// For converting document formats, and for downloading template
// documents, see the method drive.files.export():
// https://developers.google.com/drive/api/v3/manage-downloads
return drive.files
.get({fileId, alt: 'media'}, {responseType: 'stream'})
.then(res => {
return new Promise((resolve, reject) => {
const filePath = path.join(os.tmpdir(), uuid.v4());
console.log(`writing to ${filePath}`);
const dest = fs.createWriteStream(filePath);
let progress = 0;

res.data
.on('end', () => {
console.log('Done downloading file.');
resolve(filePath);
})
.on('error', err => {
console.error('Error downloading file.');
reject(err);
})
.on('data', d => {
progress += d.length;
if (process.stdout.isTTY) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Downloaded ${progress} bytes`);
}
})
.pipe(dest);
});
});
}

// if invoked directly (not tests), authenticate and run the samples
Expand Down
3 changes: 2 additions & 1 deletion samples/jwt.js
Expand Up @@ -27,10 +27,11 @@ const path = require('path');
*/
async function runSample() {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const client = await google.auth.getClient({
const auth = new google.auth.GoogleAuth({
keyFile: path.join(__dirname, 'jwt.keys.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly',
});
const client = await auth.getClient();

// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
Expand Down
2 changes: 1 addition & 1 deletion samples/oauth2.js
Expand Up @@ -65,7 +65,7 @@ async function authenticate(scopes) {
res.end('Authentication successful! Please return to the console.');
server.destroy();
const {tokens} = await oauth2Client.getToken(qs.get('code'));
oauth2Client.credentials = tokens;
oauth2Client.credentials = tokens; // eslint-disable-line require-atomic-updates
resolve(oauth2Client);
}
} catch (e) {
Expand Down
15 changes: 4 additions & 11 deletions src/googleapis.ts
Expand Up @@ -11,24 +11,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import {Compute, GoogleAuth, JWT, OAuth2Client} from 'google-auth-library';
import * as apis from './apis';

import {
AuthPlus,
APIEndpoint,
Discovery,
Endpoint,
GlobalOptions,
} from 'googleapis-common';

import * as apis from './apis';

export class AuthPlus extends GoogleAuth {
// tslint:disable-next-line: variable-name
JWT = JWT;
// tslint:disable-next-line: variable-name
Compute = Compute;
// tslint:disable-next-line: variable-name
OAuth2 = OAuth2Client;
}
export {AuthPlus};

export class GoogleApis extends apis.GeneratedAPIs {
private _discovery = new Discovery({debug: false, includePrivate: false});
Expand Down
74 changes: 74 additions & 0 deletions system-test/auth.test.ts
@@ -0,0 +1,74 @@
/**
* Copyright 2019 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.
*/

import {expect} from 'chai';
import {google} from '../src';
const compute = google.compute('v1');

describe('google.auth', async () => {
describe('google.auth.getClient', async () => {
it('allows client to be configured using historical API', async () => {
const authClient = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const projectId = await google.auth.getProjectId();
const result = await compute.instances.aggregatedList({
auth: authClient,
project: projectId,
});
const vms = result.data;
expect(vms.kind).to.be.a('string');
});

it('uses projectId from cached client', async () => {
const authClient = await google.auth.getClient({
projectId: 'foo-project-id',
});
const projectId = await google.auth.getProjectId();
expect(projectId).to.equal('foo-project-id');
});

it('uses the last configured client settings', async () => {
let authClient = await google.auth.getClient();
authClient = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const projectId = await google.auth.getProjectId();
const result = await compute.instances.aggregatedList({
auth: authClient,
project: projectId,
});
const vms = result.data;
expect(vms.kind).to.be.a('string');
});
});

describe('new google.auth.GoogleAuth', async () => {
it('allows client to be configured using historical API', async () => {
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const authClient = await auth.getClient();
const projectId = await google.auth.getProjectId();
const result = await compute.instances.aggregatedList({
auth: authClient,
project: projectId,
});
const vms = result.data;
expect(vms.kind).to.be.a('string');
});
});
});

0 comments on commit 168ad6b

Please sign in to comment.