Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add auto auth features #281

Merged
merged 6 commits into from
Feb 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 5 additions & 35 deletions examples/adc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2017, Google, Inc.
// Copyright 2018, Google, LLC.
// 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
Expand All @@ -13,12 +13,6 @@

'use strict';

/**
* This is an example of using the GoogleAuth object to acquire
* and use a client via Application Default Credentials. This is the
* easiest way to get started.
*/

/**
* Import the GoogleAuth library, and create a new GoogleAuth client.
*/
Expand All @@ -28,35 +22,11 @@ const { auth } = require('google-auth-library');
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
const adc = await getADC();
const url = `https://www.googleapis.com/dns/v1/projects/${adc.projectId}`;
const res = await adc.client.request({ url });
const client = await auth.getClient();
const projectId = await auth.getDefaultProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}

/**
* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
* this library will automatically choose the right client based on the environment.
*/
async function getADC() {
// Acquire a client and the projectId based on the environment. This method looks
// for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS environment variables.
const res = await auth.getApplicationDefault();
let client = res.credential;

// 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 (client.createScopedRequired && client.createScopedRequired()) {
// Scopes can be specified either as an array or as a single, space-delimited string.
const scopes = ['https://www.googleapis.com/auth/cloud-platform'];
client = client.createScoped(scopes);
}
return {
client: client,
projectId: res.projectId
};
}

main().catch(console.error);
34 changes: 34 additions & 0 deletions examples/authRequest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2018, Google, LLC.
// 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';

/**
* Import the GoogleAuth library, and create a new GoogleAuth client.
*/
const { auth } = require('google-auth-library');

This comment was marked as spam.

This comment was marked as spam.

const axios = require('axios');

/**
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
const client = await auth.getClient();
const projectId = await auth.getDefaultProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const opts = await auth.authorizeRequest();
const res = await axios.get(url, opts);
console.log(res.data);
}

main().catch(console.error);
35 changes: 35 additions & 0 deletions examples/creds.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2018, Google, LLC.
// 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';

/**
* Import the GoogleAuth library, and create a new GoogleAuth client.
*/
const { GoogleAuth } = require('google-auth-library');

/**
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
const credentials = require('jwt.keys.json');
const scopes = 'https://www.googleapis.com/auth/cloud-platform';
const auth = new GoogleAuth({ credentials, scopes });
const client = await auth.getClient();
const projectId = await auth.getDefaultProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}

main().catch(console.error);
36 changes: 36 additions & 0 deletions examples/keyfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2018, Google, LLC.
// 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';

/**
* Import the GoogleAuth library, and create a new GoogleAuth client.
*/
const { GoogleAuth } = require('google-auth-library');

/**
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
const auth = new GoogleAuth({
keyFilename: 'jwt.keys.json',
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const projectId = await auth.getDefaultProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}

main().catch(console.error);
69 changes: 69 additions & 0 deletions src/auth/envDetect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* Copyright 2018 Google LLC. 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 * as gcpMetadata from 'gcp-metadata';

export enum GCPEnv {
APP_ENGINE = 'APP_ENGINE',
KUBERNETES_ENGINE = 'KUBERNETES_ENGINE',
CLOUD_FUNCTIONS = 'CLOUD_FUNCTIONS',
COMPUTE_ENGINE = 'COMPUTE_ENGINE',
NONE = 'NONE'
}

let env: GCPEnv|undefined;

export function clear() {
env = undefined;
}

export async function getEnv() {
if (!env) {
if (isAppEngine()) {
env = GCPEnv.APP_ENGINE;
} else if (isCloudFunction()) {
env = GCPEnv.CLOUD_FUNCTIONS;
} else if (await isKubernetesEngine()) {
env = GCPEnv.KUBERNETES_ENGINE;
} else if (await isComputeEngine()) {
env = GCPEnv.COMPUTE_ENGINE;
} else {
env = GCPEnv.NONE;
}
}
return env;
}

function isAppEngine() {
return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);
}

function isCloudFunction() {
return !!process.env.FUNCTION_NAME;
}

async function isKubernetesEngine() {
try {
await gcpMetadata.instance('attributes/cluster-name');
return true;
} catch (e) {
return false;
}
}

async function isComputeEngine() {
return gcpMetadata.isAvailable();
}
Loading