@elastic.io/odata-library
Version:
Re-usable OData client library
62 lines (53 loc) • 2.07 kB
JavaScript
/* eslint-disable no-param-reassign, no-underscore-dangle */
const { promisify } = require('util');
const request = promisify(require('request'));
const debug = require('debug')('statelessAuthenticationRestClients');
const NoAuthRestClient = require('./NoAuthRestClient.js');
// eslint-disable-next-line max-len
module.exports = class OAuth2RestClient extends NoAuthRestClient {
async _fetchNewToken() {
debug('Fetching new token...');
const authTokenResponse = await request({
uri: this.cfg.authorizationServerTokenEndpointUrl,
method: 'POST',
json: true,
simple: false,
resolveWithFullResponse: true,
form: {
refresh_token: this.cfg.oauth2.refresh_token,
scope: this.cfg.oauth2.scope,
grant_type: 'refresh_token',
client_id: this.cfg.oauth2_field_client_id,
client_secret: this.cfg.oauth2_field_client_secret,
},
});
debug('New token fetched...');
if (authTokenResponse.statusCode >= 400) {
throw new Error(`Error in authentication. Status code: ${authTokenResponse.statusCode}`);
}
return authTokenResponse.body;
}
async _getValidToken() {
if (!this.cfg.oauth2) {
throw new Error('cfg.oauth2 can not be empty');
}
const tokenExpiryTime = new Date(this.cfg.oauth2.tokenExpiryTime);
const now = new Date();
if (now < tokenExpiryTime) {
debug('Previously valid token found.');
return this.cfg.oauth2.access_token;
}
const tokenRefreshStartTime = new Date();
this.cfg.oauth2 = await this._fetchNewToken();
this.cfg.oauth2.tokenExpiryTime = (new Date(tokenRefreshStartTime.getTime()
+ (this.cfg.oauth2.expires_in * 1000))).toISOString();
if (this.emitter && this.emitter.emit) {
this.emitter.emit('updateKeys', this.cfg.oauth2);
}
return this.cfg.oauth2.access_token;
}
async _addAuthenticationToRequestOptions(requestOptions) {
const accessToken = await this._getValidToken();
requestOptions.headers.Authorization = `Bearer ${accessToken}`;
}
};