github.com/kyma-project/kyma-environment-broker@v0.0.1/testing/e2e/skr/lib/oauth.js (about)

     1  const axios = require('axios');
     2  const {
     3    getEnvOrThrow,
     4  } = require('../utils');
     5  
     6  /**
     7   * Class OAuthCredentials wraps the OAuth credentials
     8   */
     9  class OAuthCredentials {
    10    constructor(clientID, clientSecret) {
    11      this.clientID = clientID;
    12      this.clientSecret = clientSecret;
    13    }
    14  
    15    /**
    16       * Returns OAuthCredentials instance initialized from
    17       * the environment variables.
    18       *
    19       * It expects the environment variables that store the credentials
    20       * to be present and not empty.
    21       *
    22       * @param {string} clientIDEnv - client id environment variable name
    23       * @param {string} clientSecretEnv - client secret environment variable name
    24       * @return {OAuthCredentials}
    25       */
    26    static fromEnv(clientIDEnv, clientSecretEnv) {
    27      return new OAuthCredentials(
    28          getEnvOrThrow(clientIDEnv),
    29          getEnvOrThrow(clientSecretEnv),
    30      );
    31    }
    32  }
    33  
    34  /**
    35   * Class OAuthToken provides simple approach to obtain and maintain
    36   * the OAuth2 token.
    37   *
    38   * This is very naive implementation just for the
    39   * internal e2e SKR tests usage.
    40   */
    41  class OAuthToken {
    42    constructor(url, credentials) {
    43      this.url = url;
    44      this.credentials = credentials;
    45  
    46      this._token = undefined;
    47    }
    48  
    49    async getToken(scopes) {
    50      if (!this._token || this._token.expires_at < +new Date()) {
    51        const body = `grant_type=client_credentials&scope=${scopes.join(' ')}`;
    52        const params = {
    53          auth: {
    54            username: this.credentials.clientID,
    55            password: this.credentials.clientSecret,
    56          },
    57          headers: {
    58            'Content-Type': 'application/x-www-form-urlencoded',
    59          },
    60        };
    61  
    62        try {
    63          const resp = await axios.post(this.url, body, params);
    64          this._token = resp.data;
    65          this._token.expires_at = (+new Date() + this._token.expires_in * 1000);
    66        } catch (err) {
    67          const msg = `Error when requesting bearer token from ${this.url}`;
    68          if (err.response) {
    69            throw new Error(`${msg}: ${err.response.status} ${err.response.statusText}`);
    70          } else {
    71            throw new Error(`${msg}: ${err.toString()}`);
    72          }
    73        }
    74      }
    75  
    76      return this._token.access_token;
    77    }
    78  }
    79  
    80  module.exports = {
    81    OAuthCredentials,
    82    OAuthToken,
    83  };