UNPKG

@datenkraft/bb-base-api-ts-client

Version:

The Base API TS Client package enables you to work with other Backbone TS Client packages.

75 lines (74 loc) 2.46 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Auth = void 0; const simple_oauth2_1 = require("simple-oauth2"); const node_fetch_1 = __importDefault(require("node-fetch")); class Auth { constructor(config) { this._config = config; } getAccessToken() { if (this.config.useAuthToken && this.config.authToken) { return Promise.resolve(this.config.authToken); } else if (this.config.useExternalIdToken) { return this.requestAccessTokenWithTradeIn(); } else { return this.requestAccessTokenWithClient(); } } requestAccessTokenWithClient() { const oAuthClient = new simple_oauth2_1.ClientCredentials({ client: { id: this.config.clientId, secret: this.config.clientSecret, }, auth: { tokenHost: this.config.oAuthTokenHost, }, }); const httpOptions = process.env.NODE_TLS_REJECT_UNAUTHORIZED == '0' ? { rejectUnauthorized: false } : undefined; return oAuthClient .getToken({}, httpOptions) .then((token) => { return token.token.access_token; }) .catch((error) => { throw new Error(error); }); } requestAccessTokenWithTradeIn() { return (0, node_fetch_1.default)(this.config.authenticationApiUrl + this.config.tokenTradeInPath, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ idToken: this.config.externalIdToken }), }) .then((response) => { if (response.status != 200) { throw new Error('Error requesting Access Token with Trade-In: ' + response.statusText); } return response .text() .then((body) => { return JSON.parse(body).token; }) .catch((error) => { throw new Error(error); }); }) .catch((error) => { throw new Error(error); }); } get config() { return this._config; } } exports.Auth = Auth;