Skip to content

Commit

Permalink
Merge pull request #755 from watson-developer-cloud/fix-multi-auth-bug
Browse files Browse the repository at this point in the history
fix: if basic and iam creds given, use iam and dont set basic auth he…
  • Loading branch information
anweshan authored Jul 24, 2018
2 parents 3c6882c + e91e7b3 commit 1e2d28d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
26 changes: 16 additions & 10 deletions lib/base_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ function hasBasicCredentials(obj: any): boolean {
return obj && obj.username && obj.password && obj.username !== 'apikey';
}

function hasIamCredentials(obj: any): boolean {
return obj && (obj.iam_apikey || obj.iam_access_token);
}

export class BaseService {
static URL: string;
name: string;
Expand Down Expand Up @@ -125,7 +129,7 @@ export class BaseService {
options,
_options
);
if (_options.iam_apikey || _options.iam_access_token) {
if (hasIamCredentials(_options)) {
this.tokenManager = new IamTokenManagerV1({
iamApikey: _options.iam_apikey,
iamAccessToken: _options.iam_access_token,
Expand Down Expand Up @@ -276,15 +280,17 @@ export class BaseService {
'api_key, and iam_access_token.';
throw new Error(errorMessage);
}
if (hasBasicCredentials(_options)) {
// Calculate and add Authorization header to base options
const encodedCredentials = bufferFrom(
`${_options.username}:${_options.password}`
).toString('base64');
const authHeader = { Authorization: `Basic ${encodedCredentials}` };
_options.headers = extend(authHeader, _options.headers);
} else {
_options.qs = extend({ api_key: _options.api_key }, _options.qs);
if (!hasIamCredentials(_options) && _options.username !== 'apikey') {
if (hasBasicCredentials(_options)) {
// Calculate and add Authorization header to base options
const encodedCredentials = bufferFrom(
`${_options.username}:${_options.password}`
).toString('base64');
const authHeader = { Authorization: `Basic ${encodedCredentials}` };
_options.headers = extend(authHeader, _options.headers);
} else {
_options.qs = extend({ api_key: _options.api_key }, _options.qs);
}
}
}
return _options;
Expand Down
12 changes: 12 additions & 0 deletions test/unit/test.base_service.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,4 +242,16 @@ describe('BaseService', function() {
assert.equal(instance.tokenManager.iamApikey, apikey);
assert.equal(instance._options.headers, undefined);
});

it('should not create a basic auth header if iam creds are given', function() {
const apikey = 'abcd-1234';
const instance = new TestService({
iam_apikey: apikey,
username: 'notarealuser',
password: 'badpassword1',
});
assert.notEqual(instance.tokenManager, null);
assert.equal(instance.tokenManager.iamApikey, apikey);
assert.equal(instance._options.headers, undefined);
});
});

0 comments on commit 1e2d28d

Please sign in to comment.