UNPKG

@amplience/dc-cli

Version:
54 lines (53 loc) 2.26 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OAuth2Client = void 0; const HttpRequest_1 = require("../../http/HttpRequest"); const URL_1 = require("../../utils/URL"); class OAuth2Client { constructor(clientCredentials, { authUrl = 'https://auth.amplience.net' }, httpClient) { this.authUrl = authUrl; this.clientCredentials = clientCredentials; this.httpClient = httpClient; } async getToken() { if (this.inFlight != null) { return this.inFlight; } if (this.token != null && this.tokenExpires > Date.now()) { return this.token; } if (this.clientCredentials.client_id && this.clientCredentials.client_secret) { const payload = 'grant_type=client_credentials' + '&client_id=' + encodeURIComponent(this.clientCredentials.client_id) + '&client_secret=' + encodeURIComponent(this.clientCredentials.client_secret); const request = this.httpClient.request({ data: payload, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: HttpRequest_1.HttpMethod.POST, url: (0, URL_1.combineURLs)(this.authUrl, '/oauth/token') }); this.inFlight = request.then((response) => { if (typeof response.data !== 'object') { throw new Error('Unexpected response format from /oauth/token endpoint'); } if (response.status !== 200) { const responseText = response.data.error_description || JSON.stringify(response.data); throw new Error(`Authorization failed (${response.status}): ${responseText}`); } this.token = response.data; this.tokenExpires = Date.now() + this.token.expires_in * 1000; this.inFlight = undefined; return this.token; }); return this.inFlight; } else { throw new Error('Client credentials not set'); } } } exports.OAuth2Client = OAuth2Client;