UNPKG

@controlplane/cli

Version:

Control Plane Corporation CLI

62 lines 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeAuthorizationHeader = void 0; const axios = require("axios"); const jwt = require("jwt-decode"); const time_1 = require("../util/time"); const logger_1 = require("../util/logger"); const MIN_REMAINING = 10 * 60; async function makeAuthorizationHeader(profile) { if (profile.request.token) { logger_1.logger.info('Using static token from the request/profile'); // service account or impersonation maybe let token = profile.request.token; // Add 'Bearer ' if it doesn't exists in the token if (!profile.request.token.startsWith('Bearer ')) { token = `Bearer ${token}`; } // Return the token return token; } const auth = profile.authInfo; if (!auth) { throw new Error(`\nYour profile is not logged in.\n\nLog in by running: cpln profile update ${profile.name} --login`); } let token; try { token = jwt(auth.accessToken); } catch (e) { await updateAccessToken(profile); return `Bearer ${auth.accessToken}`; } const expires = token.exp; const ttl = expires - (0, time_1.unixNow)(); if (ttl >= MIN_REMAINING) { logger_1.logger.info(`Reusing still-valid accessToken. Expiring in ${ttl}s.`); } else { logger_1.logger.info('Refreshing token'); await updateAccessToken(profile); } return `Bearer ${auth.accessToken}`; } exports.makeAuthorizationHeader = makeAuthorizationHeader; async function updateAccessToken(profile) { var _a; const discoveryRes = await axios.default.get(profile.request.endpoint + '/discovery'); const firebase = discoveryRes.data.firebase; const tokenRefreshUrl = 'https://securetoken.googleapis.com/v1/token?key='; const req = { refresh_token: (_a = profile.authInfo) === null || _a === void 0 ? void 0 : _a.refreshToken, grant_type: 'refresh_token', }; try { const response = await axios.default.post(tokenRefreshUrl + firebase.apiKey, req); profile.authInfo.accessToken = response.data.access_token; } catch (e) { throw new Error(`\nYour session has expired.\n\nLog in again by running: cpln profile update ${profile.name} --login`); } } //# sourceMappingURL=auth.js.map