UNPKG

bagman

Version:

js/ts client for Bagman

59 lines (58 loc) 2.86 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SecurityContext = void 0; class SecurityContext { constructor({ apiKey, authorizer }) { if (!apiKey && !authorizer) { throw new Error("Please supply either API Key or Authorizer Config"); } ; this.apiKey = apiKey; this.authorizer = authorizer; } resolve(resolver) { return __awaiter(this, void 0, void 0, function* () { if (resolver instanceof Function) return resolver(); return resolver; }); } isAuthorized() { return !!this.apiKey || !!this.apiToken; } token() { if (!this.isAuthorized()) throw new Error("Please authorize client or provide API Key."); // priorize api token // authorized means either of them exists. return this.apiToken || this.apiKey; } authorize() { return __awaiter(this, void 0, void 0, function* () { if (!this.authorizer) throw new Error("No Authorizer Config is Provided."); const { scheme = "https", port = 80, method = 'GET', host, path, extraHeaders, extraParams, body } = this.authorizer; const params = extraParams && (yield this.resolve(extraParams)); const url = new URL(`${path}${params ? `?${new URLSearchParams(params).toString()}` : ''}`, `${scheme}://${host}:${port}`); if (body && method === 'GET') { throw new Error(`Couldn't supply body to a GET Authorize Request. Please check your Authorizer Config.`); } const response = yield fetch(url, Object.assign({ method, headers: Object.assign({}, (extraHeaders && (yield this.resolve(extraHeaders)))) }, (body && { body: yield this.resolve(body) }))); if (response.status < 200 || response.status > 299) { throw new Error("Authorization Failed. Please check config or authorizer endpoint."); } const { token } = yield response.json(); this.apiToken = token; }); } } exports.SecurityContext = SecurityContext;