diff --git a/package.json b/package.json index 7223a76..8c14214 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "url": "https://github.com/NASA-AMMOS/aerie-gateway.git" }, "scripts": { - "build": "npm run clean && tsc", + "build": "npm run clean && tsc && cp ./src/packages/api-playground/pre-request-script dist/packages/api-playground", "clean": "rm -rf dist", "format": "prettier --write ./src", "lint": "eslint ./src --ext .js,.ts", diff --git a/src/packages/api-playground/api-playground.ts b/src/packages/api-playground/api-playground.ts index 64f8524..71b88b4 100644 --- a/src/packages/api-playground/api-playground.ts +++ b/src/packages/api-playground/api-playground.ts @@ -1,27 +1,13 @@ import { altairExpress } from 'altair-express-middleware'; import type { Express } from 'express'; import { getEnv } from '../../env.js'; +import { readFileSync } from 'fs'; export default (app: Express) => { const { GQL_API_URL: endpointURL, GQL_API_WS_URL: subscriptionsEndpoint } = getEnv(); const initialQuery = '{ plan { id name } }'; const initialHeaders = { Authorization: 'Bearer {{user}}', 'x-hasura-role': 'viewer' }; - const initialPreRequestScript = - ` - // Fetch a new token from the Gateway - const res = await altair.helpers.request( - 'POST', - '/auth/login', // AUTH ENDPOINT OF THE DEPLOYMENT - { - body: { "username": "", "password": ""}, // CREDENTIALS TO LOG IN AS - headers: {"Content-Type": "application/json"} - }); - if(res.success) { - const token = res.token; - await altair.helpers.setEnvironment("user", token); - } else { - altair.log(res); - }`; + const initialPreRequestScript = readFileSync('dist/packages/api-playground/pre-request-script').toString(); const initialSettings = { addQueryDepthLimit: 5, enableExperimental: true, diff --git a/src/packages/api-playground/pre-request-script b/src/packages/api-playground/pre-request-script new file mode 100644 index 0000000..e2edf17 --- /dev/null +++ b/src/packages/api-playground/pre-request-script @@ -0,0 +1,24 @@ +const nowInSeconds = () => Date.now() / 1000; +const tokenExpiry = await altair.storage.get("token_exp") || 0; + +if (nowInSeconds() >= Number(tokenExpiry)) { + // Fetch a new token from the Gateway + const res = await altair.helpers.request( + 'POST', + '/auth/login', // AUTH ENDPOINT OF THE DEPLOYMENT + { + body: { "username": "", "password": ""}, // CREDENTIALS TO LOG IN AS + headers: {"Content-Type": "application/json"} + }); + if(res.success) { + const token = res.token; + await altair.storage.set("token", token); + // Set JWT expiry + const atob = await altair.importModule('atob'); + const body = JSON.parse(atob(token.split('.')[1])); + await altair.storage.set("token_exp", body.exp); + } else { altair.log(res); } +} +// Set the token in the environment +const token = await altair.storage.get("token"); +altair.helpers.setEnvironment('user', token); \ No newline at end of file