Skip to content

Commit b43f3f0

Browse files
authored
Merge pull request #831 from watson-developer-cloud/load-creds-from-file
Load creds from file
2 parents 0354c5b + 9573a52 commit b43f3f0

File tree

9 files changed

+2441
-2231
lines changed

9 files changed

+2441
-2231
lines changed

README.md

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,55 @@ Watson services are migrating to token-based Identity and Access Management (IAM
8585
- In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance.
8686

8787
### Getting credentials
88+
8889
To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:
8990

90-
1. Go to the IBM Cloud [Dashboard](https://console.bluemix.net/dashboard/apps?category=ai) page.
91-
1. Either click an existing Watson service instance or click [**Create resource > AI**](https://console.bluemix.net/catalog/?category=ai) and create a service instance.
92-
1. Click **Show** to view your service credentials.
93-
1. Copy the `url` and either `apikey` or `username` and `password`.
91+
1. Go to the IBM Cloud [Dashboard](https://cloud.ibm.com/) page.
92+
2. Either click an existing Watson service instance in your [resource list](https://cloud.ibm.com/resources) or click [**Create resource > AI**](https://cloud.ibm.com/catalog?category=ai) and create a service instance.
93+
3. Click on the **Manage** item in the left nav bar of your service instance.
94+
95+
On this page, you should be able to see your credentials for accessing your service instance.
96+
97+
In your code, you can use these values in the service constructor or with a method call after instantiating your service.
98+
99+
### Supplying credentials
100+
101+
There are two ways to supply the credentials you found above to the SDK for authentication:
102+
103+
#### Credentials file (easier!)
104+
105+
With a credentials file, you just need to put the file in the right place and the SDK will do the work of parsing it and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance.
106+
107+
The file downloaded will be called `ibm-credentials.env`. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your `ibm-credentials.env` file in the following places (in order):
108+
109+
- Directory provided by the environment variable `IBM_CREDENTIALS_FILE`
110+
- Your system's home directory
111+
- Your current working directory (the directory Node is executed from)
112+
113+
As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following:
114+
115+
```js
116+
const DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
117+
const discovery = new DiscoveryV1({ version: '2019-02-01' });
118+
```
119+
120+
And that's it!
121+
122+
If you're using more than one service at a time in your code and get two different `ibm-credentials.env` files, just put the contents together in one `ibm-credentials.env` file and the SDK will handle assigning credentials to their appropriate services.
123+
124+
If you would like to configure the location/name of your credential file, you can set an environment variable called `IBM_CREDENTIALS_FILE`. **This will take precedence over the locations specified above.** Here's how you can do that:
125+
126+
```bash
127+
export IBM_CREDENTIALS_FILE="<path>"
128+
```
129+
130+
where `<path>` is something like `/home/user/Downloads/<file_name>.env`. If you just provide a path to a directory, the SDK will look for a file called `ibm-credentials.env` in that directory.
131+
132+
#### Manually
133+
134+
The SDK also supports setting credentials manually in your code. You will either use IAM credentials or Basic Authentication (username/password) credentials.
94135

95-
### IAM
136+
##### IAM
96137

97138
Some services use token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated.
98139

@@ -101,7 +142,7 @@ You supply either an IAM service **API key** or an **access token**:
101142
- Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
102143
- Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://console.bluemix.net/docs/services/watson/getting-started-iam.html). If you want to switch to API key, override your stored IAM credentials with an IAM API key.
103144

104-
#### Supplying the IAM API key
145+
###### Supplying the IAM API key
105146

106147
```js
107148
// in the constructor, letting the SDK manage the IAM token
@@ -113,7 +154,7 @@ const discovery = new DiscoveryV1({
113154
});
114155
```
115156

116-
#### Supplying the access token
157+
###### Supplying the access token
117158

118159
```js
119160
// in the constructor, assuming control of managing IAM token

examples/.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
NATURAL_LANGUAGE_UNDERSTANDING_USERNAME=username
2+
NATURAL_LANGUAGE_UNDERSTANDING_PASSWORD=password

lib/base_service.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import semver = require('semver');
2323
import vcapServices = require('vcap_services');
2424
import { IamTokenManagerV1 } from '../iam-token-manager/v1';
2525
import { stripTrailingSlash } from './helper';
26+
import { readCredentialsFile } from './read-credentials-file';
2627
import { sendRequest } from './requestwrapper';
2728

2829
// custom interfaces
@@ -308,7 +309,8 @@ export class BaseService {
308309
_options = extend(
309310
{},
310311
this.getCredentialsFromBluemix(this.name),
311-
this.getCredentialsFromEnvironment(this.name),
312+
this.getCredentialsFromEnvironment(process.env, this.name),
313+
this.getCredentialsFromEnvironment(readCredentialsFile(), this.name),
312314
options,
313315
_options
314316
);
@@ -352,24 +354,24 @@ export class BaseService {
352354
* @param {string} name - the service snake case name
353355
* @returns {Credentials}
354356
*/
355-
private getCredentialsFromEnvironment(name: string): Credentials {
357+
private getCredentialsFromEnvironment(envObj: any, name: string): Credentials {
356358
if (name === 'watson_vision_combined') {
357-
return this.getCredentialsFromEnvironment('visual_recognition');
359+
return this.getCredentialsFromEnvironment(envObj, 'visual_recognition');
358360
}
359361
// Case handling for assistant - should look for assistant env variables before conversation
360-
if (name === 'conversation' && (process.env[`ASSISTANT_USERNAME`] || process.env[`ASSISTANT_IAM_APIKEY`])) {
361-
return this.getCredentialsFromEnvironment('assistant');
362+
if (name === 'conversation' && (envObj[`ASSISTANT_USERNAME`] || envObj[`ASSISTANT_IAM_APIKEY`])) {
363+
return this.getCredentialsFromEnvironment(envObj, 'assistant');
362364
}
363365
const _name: string = name.toUpperCase();
364366
// https://github.com/watson-developer-cloud/node-sdk/issues/605
365367
const nameWithUnderscore: string = _name.replace(/-/g, '_');
366-
const username: string = process.env[`${_name}_USERNAME`] || process.env[`${nameWithUnderscore}_USERNAME`];
367-
const password: string = process.env[`${_name}_PASSWORD`] || process.env[`${nameWithUnderscore}_PASSWORD`];
368-
const apiKey: string = process.env[`${_name}_API_KEY`] || process.env[`${nameWithUnderscore}_API_KEY`];
369-
const url: string = process.env[`${_name}_URL`] || process.env[`${nameWithUnderscore}_URL`];
370-
const iamAccessToken: string = process.env[`${_name}_IAM_ACCESS_TOKEN`] || process.env[`${nameWithUnderscore}_IAM_ACCESS_TOKEN`];
371-
const iamApiKey: string = process.env[`${_name}_IAM_APIKEY`] || process.env[`${nameWithUnderscore}_IAM_APIKEY`];
372-
const iamUrl: string = process.env[`${_name}_IAM_URL`] || process.env[`${nameWithUnderscore}_IAM_URL`];
368+
const username: string = envObj[`${_name}_USERNAME`] || envObj[`${nameWithUnderscore}_USERNAME`];
369+
const password: string = envObj[`${_name}_PASSWORD`] || envObj[`${nameWithUnderscore}_PASSWORD`];
370+
const apiKey: string = envObj[`${_name}_API_KEY`] || envObj[`${nameWithUnderscore}_API_KEY`];
371+
const url: string = envObj[`${_name}_URL`] || envObj[`${nameWithUnderscore}_URL`];
372+
const iamAccessToken: string = envObj[`${_name}_IAM_ACCESS_TOKEN`] || envObj[`${nameWithUnderscore}_IAM_ACCESS_TOKEN`];
373+
const iamApiKey: string = envObj[`${_name}_IAM_APIKEY`] || envObj[`${nameWithUnderscore}_IAM_APIKEY`];
374+
const iamUrl: string = envObj[`${_name}_IAM_URL`] || envObj[`${nameWithUnderscore}_IAM_URL`];
373375

374376
return {
375377
username,

lib/read-credentials-file.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import dotenv = require('dotenv');
2+
import fs = require('fs');
3+
import os = require('os');
4+
import path = require('path');
5+
6+
const filename: string = 'ibm-credentials.env';
7+
8+
export function readCredentialsFile() {
9+
// first look for an env variable called IBM_CREDENTIALS_FILE
10+
// it should be the path to the file
11+
12+
const givenFilepath: string = process.env['IBM_CREDENTIALS_FILE'] || '';
13+
const homeDir: string = constructFilepath(os.homedir());
14+
const workingDir: string = constructFilepath(process.cwd());
15+
16+
let filepathToUse: string;
17+
18+
if (givenFilepath) {
19+
if (fileExistsAtPath(givenFilepath)) {
20+
// see if user gave a path to a file named something other than `ibm-credentials.env`
21+
filepathToUse = givenFilepath;
22+
} else if (fileExistsAtPath(constructFilepath(givenFilepath))) {
23+
// see if user gave a path to the directory where file is located
24+
filepathToUse = constructFilepath(givenFilepath);
25+
}
26+
} else if (fileExistsAtPath(homeDir)) {
27+
filepathToUse = homeDir;
28+
} else if (fileExistsAtPath(workingDir)) {
29+
filepathToUse = workingDir;
30+
} else {
31+
// file does not exist anywhere, will not be used
32+
return {};
33+
}
34+
35+
const credsFile = fs.readFileSync(filepathToUse);
36+
37+
return dotenv.parse(credsFile);
38+
}
39+
40+
export function fileExistsAtPath(filepath): boolean {
41+
return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile();
42+
}
43+
44+
export function constructFilepath(filepath): string {
45+
// ensure filepath includes the filename
46+
if (!filepath.endsWith(filename)) {
47+
filepath = path.join(filepath, filename);
48+
}
49+
50+
return filepath;
51+
}

0 commit comments

Comments
 (0)