Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use strict";
  2. /**
  3.  * Copyright 2014 IBM Corp. All Rights Reserved.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. Object.defineProperty(exports, "__esModule", { value: true });
  18. // new Buffer() is deprecated, replaced with Buffer.from() in node v4.5.0+ -
  19. // `buffer-from` uses the new api when possible but falls back to the old one otherwise
  20. var bufferFrom = require("buffer-from");
  21. var extend = require("extend");
  22. var request = require("request");
  23. var vcapServices = require("vcap_services");
  24. var v1_1 = require("../iam-token-manager/v1");
  25. var helper_1 = require("./helper");
  26. var requestwrapper_1 = require("./requestwrapper");
  27. function hasCredentials(obj) {
  28.     return (obj &&
  29.         ((obj.username && obj.password) ||
  30.             obj.api_key ||
  31.             obj.iam_access_token ||
  32.             obj.iam_apikey));
  33. }
  34. function hasBasicCredentials(obj) {
  35.     return obj && obj.username && obj.password && obj.username !== 'apikey';
  36. }
  37. var BaseService = /** @class */ (function () {
  38.     /**
  39.      * Internal base class that other services inherit from
  40.      * @param {UserOptions} options
  41.      * @param {string} [options.username] - required unless use_unauthenticated is set
  42.      * @param {string} [options.password] - required unless use_unauthenticated is set
  43.      * @param {boolean} [options.use_unauthenticated] - skip credential requirement
  44.      * @param {HeaderOptions} [options.headers]
  45.      * @param {boolean} [options.headers.X-Watson-Learning-Opt-Out=false] - opt-out of data collection
  46.      * @param {string} [options.url] - override default service base url
  47.      * @private
  48.      * @abstract
  49.      * @constructor
  50.      * @throws {Error}
  51.      * @returns {BaseService}
  52.      */
  53.     function BaseService(userOptions) {
  54.         if (!(this instanceof BaseService)) {
  55.             // it might be better to just create a new instance and return that..
  56.             // but that can't be done here, it has to be done in each individual service.
  57.             // So this is still a good failsafe even in that case.
  58.             throw new Error('the "new" keyword is required to create Watson service instances');
  59.         }
  60.         var options = extend({}, userOptions);
  61.         var _options = this.initCredentials(options);
  62.         // If url is not specified, visual recognition requires gateway-a for CF instances
  63.         // https://github.ibm.com/Watson/developer-experience/issues/4589
  64.         if (_options && this.name === 'watson_vision_combined' && !_options.url && _options.api_key && !_options.iam_apikey) {
  65.             _options.url = 'https://gateway-a.watsonplatform.net/visual-recognition/api';
  66.         }
  67.         if (options.url) {
  68.             _options.url = helper_1.stripTrailingSlash(options.url);
  69.         }
  70.         var serviceClass = this.constructor;
  71.         this._options = extend({ qs: {}, url: serviceClass.URL }, this.serviceDefaults, options, _options);
  72.         if (_options.iam_apikey || _options.iam_access_token) {
  73.             this.tokenManager = new v1_1.IamTokenManagerV1({
  74.                 iamApikey: _options.iam_apikey,
  75.                 iamAccessToken: _options.iam_access_token,
  76.                 iamUrl: _options.iam_url
  77.             });
  78.         }
  79.         else if (_options.username === 'apikey') {
  80.             this.tokenManager = new v1_1.IamTokenManagerV1({
  81.                 iamApikey: _options.password,
  82.                 iamUrl: _options.iam_url
  83.             });
  84.         }
  85.         else {
  86.             this.tokenManager = null;
  87.         }
  88.     }
  89.     /**
  90.      * Retrieve this service's credentials - useful for passing to the authorization service
  91.      *
  92.      * Only returns a URL when token auth is used.
  93.      *
  94.      * @returns {Credentials}
  95.      */
  96.     BaseService.prototype.getCredentials = function () {
  97.         var credentials = {};
  98.         if (this._options.username) {
  99.             credentials.username = this._options.username;
  100.         }
  101.         if (this._options.password) {
  102.             credentials.password = this._options.password;
  103.         }
  104.         if (this._options.api_key) {
  105.             credentials.api_key = this._options.api_key;
  106.         }
  107.         if (this._options.url) {
  108.             credentials.url = this._options.url;
  109.         }
  110.         if (this._options.iam_access_token) {
  111.             credentials.iam_access_token = this._options.iam_access_token;
  112.         }
  113.         if (this._options.iam_apikey) {
  114.             credentials.iam_apikey = this._options.iam_apikey;
  115.         }
  116.         if (this._options.iam_url) {
  117.             credentials.iam_url = this._options.iam_url;
  118.         }
  119.         return credentials;
  120.     };
  121.     /**
  122.      * Set an IAM access token to use when authenticating with the service.
  123.      * The access token should be valid and not yet expired.
  124.      *
  125.      * By using this method, you accept responsibility for managing the
  126.      * access token yourself. You must set a new access token before this
  127.      * one expires. Failing to do so will result in authentication errors
  128.      * after this token expires.
  129.      *
  130.      * @param {string} iam_access_token - A valid, non-expired IAM access token
  131.      * @returns {void}
  132.      */
  133.     BaseService.prototype.setAccessToken = function (iam_access_token) {
  134.         if (this.tokenManager) {
  135.             this.tokenManager.setAccessToken(iam_access_token);
  136.         }
  137.         else {
  138.             this.tokenManager = new v1_1.IamTokenManagerV1({
  139.                 iamAccessToken: iam_access_token
  140.             });
  141.         }
  142.     };
  143.     /**
  144.      * Guarantee that the next request you make will be IAM authenticated. This
  145.      * performs any requests necessary to get a valid IAM token so that if your
  146.      * next request involves a streaming operation, it will not be interrupted.
  147.      *
  148.      * @param {Function} callback - callback function to return flow of execution
  149.      *
  150.      * @returns {void}
  151.      */
  152.     BaseService.prototype.preAuthenticate = function (callback) {
  153.         if (Boolean(this.tokenManager)) {
  154.             return this.tokenManager.getToken(function (err, token) {
  155.                 if (err) {
  156.                     callback(err);
  157.                 }
  158.                 callback(null);
  159.             });
  160.         }
  161.         else {
  162.             callback(null);
  163.         }
  164.     };
  165.     /**
  166.      * Wrapper around `sendRequest` that determines whether or not IAM tokens
  167.      * are being used to authenticate the request. If so, the token is
  168.      * retrieved by the token manager.
  169.      *
  170.      * @param {Object} parameters - service request options passed in by user
  171.      * @param {Function} callback - callback function to pass the response back to
  172.      * @returns {ReadableStream|undefined}
  173.      */
  174.     BaseService.prototype.createRequest = function (parameters, callback) {
  175.         if (Boolean(this.tokenManager)) {
  176.             return this.tokenManager.getToken(function (err, accessToken) {
  177.                 if (err) {
  178.                     return callback(err);
  179.                 }
  180.                 parameters.defaultOptions.headers.Authorization =
  181.                     "Bearer " + accessToken;
  182.                 return requestwrapper_1.sendRequest(parameters, callback);
  183.             });
  184.         }
  185.         else {
  186.             return requestwrapper_1.sendRequest(parameters, callback);
  187.         }
  188.     };
  189.     /**
  190.      * @private
  191.      * @param {UserOptions} options
  192.      * @returns {BaseServiceOptions}
  193.      */
  194.     BaseService.prototype.initCredentials = function (options) {
  195.         var _options = {};
  196.         if (options.token) {
  197.             options.headers = options.headers || {};
  198.             options.headers['X-Watson-Authorization-Token'] = options.token;
  199.             _options = extend(_options, options);
  200.             return _options;
  201.         }
  202.         if (options.api_key || options.apikey) {
  203.             _options.api_key = options.api_key || options.apikey;
  204.         }
  205.         _options.jar = request.jar();
  206.         // Get credentials from environment properties or Bluemix,
  207.         // but prefer credentials provided programatically
  208.         _options = extend({}, this.getCredentialsFromBluemix(this.name), this.getCredentialsFromEnvironment(this.name), options, _options);
  209.         if (!_options.use_unauthenticated) {
  210.             if (!hasCredentials(_options)) {
  211.                 var errorMessage = 'Insufficient credentials provided in ' +
  212.                     'constructor argument. Refer to the documentation for the ' +
  213.                     'required parameters. Common examples are username/password, ' +
  214.                     'api_key, and iam_access_token.';
  215.                 throw new Error(errorMessage);
  216.             }
  217.             if (hasBasicCredentials(_options)) {
  218.                 // Calculate and add Authorization header to base options
  219.                 var encodedCredentials = bufferFrom(_options.username + ":" + _options.password).toString('base64');
  220.                 var authHeader = { Authorization: "Basic " + encodedCredentials };
  221.                 _options.headers = extend(authHeader, _options.headers);
  222.             }
  223.             else {
  224.                 _options.qs = extend({ api_key: _options.api_key }, _options.qs);
  225.             }
  226.         }
  227.         return _options;
  228.     };
  229.     /**
  230.      * Pulls credentials from env properties
  231.      *
  232.      * Property checked is uppercase service.name suffixed by _USERNAME and _PASSWORD
  233.      *
  234.      * For example, if service.name is speech_to_text,
  235.      * env properties are SPEECH_TO_TEXT_USERNAME and SPEECH_TO_TEXT_PASSWORD
  236.      *
  237.      * @private
  238.      * @param {string} name - the service snake case name
  239.      * @returns {Credentials}
  240.      */
  241.     BaseService.prototype.getCredentialsFromEnvironment = function (name) {
  242.         if (name === 'watson_vision_combined') {
  243.             return this.getCredentialsFromEnvironment('visual_recognition');
  244.         }
  245.         // Case handling for assistant - should look for assistant env variables before conversation
  246.         if (name === 'conversation' && (process.env["ASSISTANT_USERNAME"] || process.env["ASSISTANT_IAM_APIKEY"])) {
  247.             return this.getCredentialsFromEnvironment('assistant');
  248.         }
  249.         var _name = name.toUpperCase();
  250.         // https://github.com/watson-developer-cloud/node-sdk/issues/605
  251.         var nameWithUnderscore = _name.replace(/-/g, '_');
  252.         var username = process.env[_name + "_USERNAME"] || process.env[nameWithUnderscore + "_USERNAME"];
  253.         var password = process.env[_name + "_PASSWORD"] || process.env[nameWithUnderscore + "_PASSWORD"];
  254.         var apiKey = process.env[_name + "_API_KEY"] || process.env[nameWithUnderscore + "_API_KEY"];
  255.         var url = process.env[_name + "_URL"] || process.env[nameWithUnderscore + "_URL"];
  256.         var iamAccessToken = process.env[_name + "_IAM_ACCESS_TOKEN"] || process.env[nameWithUnderscore + "_IAM_ACCESS_TOKEN"];
  257.         var iamApiKey = process.env[_name + "_IAM_APIKEY"] || process.env[nameWithUnderscore + "_IAM_APIKEY"];
  258.         var iamUrl = process.env[_name + "_IAM_URL"] || process.env[nameWithUnderscore + "_IAM_URL"];
  259.         return {
  260.             username: username,
  261.             password: password,
  262.             api_key: apiKey,
  263.             url: url,
  264.             iam_access_token: iamAccessToken,
  265.             iam_apikey: iamApiKey,
  266.             iam_url: iamUrl
  267.         };
  268.     };
  269.     /**
  270.      * Pulls credentials from VCAP_SERVICES env property that bluemix sets
  271.      * @param {string} vcap_services_name
  272.      * @private
  273.      * @returns {Credentials}
  274.      */
  275.     BaseService.prototype.getCredentialsFromBluemix = function (vcapServicesName) {
  276.         var credentials;
  277.         var temp;
  278.         if (this.name === 'visual_recognition') {
  279.             temp = vcapServices.getCredentials('watson_vision_combined');
  280.         }
  281.         if (this.name === 'assistant') {
  282.             temp = vcapServices.getCredentials('conversation');
  283.         }
  284.         else {
  285.             temp = vcapServices.getCredentials(vcapServicesName);
  286.         }
  287.         // convert an iam apikey to use the identifier iam_apikey
  288.         if (temp.apikey && temp.iam_apikey_name) {
  289.             temp.iam_apikey = temp.apikey;
  290.             delete temp.apikey;
  291.         }
  292.         credentials = temp;
  293.         return credentials;
  294.     };
  295.     return BaseService;
  296. }());
  297. exports.BaseService = BaseService;
  298. //# sourceMappingURL=base_service.js.map
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement