UNPKG

@grouparoo/core

Version:
55 lines (54 loc) 2.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.oAuthAccessTokenGetter = void 0; require("isomorphic-fetch"); const actionhero_1 = require("actionhero"); const EXPIRATION_BUFFER_MS = 60000; // 1 minute class oAuthAccessTokenGetter { constructor(providerName, refreshToken) { this.providerName = providerName; this.refreshToken = refreshToken; } isAccessTokenExpired() { return (!this.accessToken || !this.expirationDate || this.expirationDate - Date.now() <= EXPIRATION_BUFFER_MS); } async requestAccessToken() { var _a, _b; try { for (let retries = 3; retries > 0 && this.isAccessTokenExpired(); retries--) { const url = `${actionhero_1.config.oAuth.host}/api/v1/oauth/${this.providerName}/client/refresh`; const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refreshToken: this.refreshToken }), }); if (!response.ok) { const authErrorResponse = await response.json(); if ((_a = authErrorResponse.error) === null || _a === void 0 ? void 0 : _a.message) { (0, actionhero_1.log)((_b = authErrorResponse.error) === null || _b === void 0 ? void 0 : _b.message, "error"); } // Try again continue; } const { token, expirationSeconds = 0, } = await response.json(); this.accessToken = token; this.expirationDate = Date.now() + expirationSeconds * 1000; } } catch (e) { throw e; } if (this.isAccessTokenExpired()) { throw new Error(`Failed to get auth for ${this.providerName}. Please reauthorize ${this.providerName} App.`); } } async getAccessToken() { if (this.isAccessTokenExpired()) { await this.requestAccessToken(); } return this.accessToken; } } exports.oAuthAccessTokenGetter = oAuthAccessTokenGetter;