@datenkraft/bb-base-api-ts-client
Version:
The Base API TS Client package enables you to work with other Backbone TS Client packages.
71 lines (70 loc) • 3.04 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
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 HttpError_1 = require("./HttpError");
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() {
return __awaiter(this, void 0, void 0, function* () {
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;
const token = yield oAuthClient.getToken({}, httpOptions);
return token.token.access_token;
});
}
requestAccessTokenWithTradeIn() {
return __awaiter(this, void 0, void 0, function* () {
const response = yield (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 }),
});
if (response.status != 200) {
throw new HttpError_1.HttpError(response.status, 'Error requesting Access Token with Trade-In: ' + response.statusText);
}
const body = yield response.text();
return JSON.parse(body).token;
});
}
get config() {
return this._config;
}
}
exports.Auth = Auth;