Skip to content

Commit 9573a52

Browse files
committed
docs: add documentation in the readme for reading credentials file
1 parent ce02aa8 commit 9573a52

5 files changed

Lines changed: 81 additions & 26 deletions

File tree

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/read-credentials-file.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,19 @@ export function readCredentialsFile() {
1010
// it should be the path to the file
1111

1212
const givenFilepath: string = process.env['IBM_CREDENTIALS_FILE'] || '';
13-
const homeDir: string = os.homedir();
14-
const workingDir: string = process.cwd();
13+
const homeDir: string = constructFilepath(os.homedir());
14+
const workingDir: string = constructFilepath(process.cwd());
1515

1616
let filepathToUse: string;
1717

18-
if (givenFilepath && fileExistsAtPath(givenFilepath)) {
19-
filepathToUse = givenFilepath;
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+
}
2026
} else if (fileExistsAtPath(homeDir)) {
2127
filepathToUse = homeDir;
2228
} else if (fileExistsAtPath(workingDir)) {
@@ -26,14 +32,13 @@ export function readCredentialsFile() {
2632
return {};
2733
}
2834

29-
const credsFile = fs.readFileSync(constructFilepath(filepathToUse));
35+
const credsFile = fs.readFileSync(filepathToUse);
3036

3137
return dotenv.parse(credsFile);
3238
}
3339

3440
export function fileExistsAtPath(filepath): boolean {
35-
filepath = constructFilepath(filepath);
36-
return fs.existsSync(filepath);
41+
return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile();
3742
}
3843

3944
export function constructFilepath(filepath): string {

test/unit/baseService.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ describe('BaseService', function() {
166166
});
167167

168168
it('should prefer hard-coded credentials over ibm credentials file', function() {
169-
process.env.IBM_CREDENTIALS_FILE = __dirname + '../resources/ibm-credentials.env';
169+
process.env.IBM_CREDENTIALS_FILE = __dirname + '/../resources/ibm-credentials.env';
170170
const instance = new TestService({ username: 'user', password: 'pass' });
171171
const actual = instance.getCredentials();
172172
const expected = {

test/unit/readCredentialsFile.test.js

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
'use strict';
22

33
const readCredentialsFunctions = require('../../lib/read-credentials-file');
4+
const constructFilepath = readCredentialsFunctions.constructFilepath;
5+
const fileExistsAtPath = readCredentialsFunctions.fileExistsAtPath;
6+
const readCredentialsFile = readCredentialsFunctions.readCredentialsFile;
47

58
describe('read ibm credentials file', () => {
6-
const locationOfActualFile = __dirname + '/../resources/ibm-credentials.env';
9+
const locationOfActualFile = __dirname + '/../resources';
710
process.env.IBM_CREDENTIALS_FILE = locationOfActualFile;
811

912
describe('construct filepath', () => {
1013
const expectedPath = '/path/to/file/ibm-credentials.env';
11-
const constructFilepath = readCredentialsFunctions.constructFilepath;
1214

1315
it('should build filepath from absolute path', () => {
1416
const path = constructFilepath('/path/to/file/');
@@ -24,22 +26,21 @@ describe('read ibm credentials file', () => {
2426
const path = constructFilepath(expectedPath);
2527
expect(path).toBe(expectedPath);
2628
});
27-
28-
it('should append filename to existing filename', () => {
29-
const path = constructFilepath('/path/to/file/wrong-file.env');
30-
expect(path).toBe('/path/to/file/wrong-file.env/ibm-credentials.env');
31-
});
3229
});
3330

3431
describe('file exists at path', () => {
35-
const fileExistsAtPath = readCredentialsFunctions.fileExistsAtPath;
3632
it('should return true if the file exists at the given path', () => {
37-
const path = locationOfActualFile;
33+
const path = constructFilepath(locationOfActualFile);
3834
expect(fileExistsAtPath(path)).toBe(true);
3935
});
4036

37+
it('should return false if path is correct but is not a file', () => {
38+
const path = locationOfActualFile;
39+
expect(fileExistsAtPath(path)).toBe(false);
40+
});
41+
4142
it('should return false if the file does not exist at the given path', () => {
42-
const path = process.cwd();
43+
const path = constructFilepath(process.cwd());
4344
expect(fileExistsAtPath(path)).toBe(false);
4445
});
4546

@@ -50,13 +51,19 @@ describe('read ibm credentials file', () => {
5051
});
5152

5253
describe('read credentials file', () => {
53-
const readCredentialsFile = readCredentialsFunctions.readCredentialsFile;
5454
it('should return credentials as an object if file exists', () => {
5555
const obj = readCredentialsFile();
5656
expect(obj.TEST_USERNAME).toBe('123456789');
5757
expect(obj.TEST_PASSWORD).toBe('abcd');
5858
});
5959

60+
it('should return credentials as an object for alternate filename', () => {
61+
process.env['IBM_CREDENTIALS_FILE'] = __dirname + '/../../examples/.env.example';
62+
const obj = readCredentialsFile();
63+
expect(obj.NATURAL_LANGUAGE_UNDERSTANDING_USERNAME).toBe('username');
64+
expect(obj.NATURAL_LANGUAGE_UNDERSTANDING_PASSWORD).toBe('password');
65+
});
66+
6067
it('should return empty object if file is not found', () => {
6168
delete process.env['IBM_CREDENTIALS_FILE'];
6269
const obj = readCredentialsFile();

0 commit comments

Comments
 (0)