This repository has been archived on 2022-10-07. You can view files and clone it, but cannot push or open issues or pull requests.
skynet-webportal/packages/health-check/src/utils.js

118 lines
3.5 KiB
JavaScript
Raw Normal View History

const got = require("got");
2020-09-10 12:03:56 +00:00
/**
* Get the time between start and now in milliseconds
*/
2020-09-09 12:53:05 +00:00
function calculateElapsedTime(start) {
2020-09-09 12:25:00 +00:00
const diff = process.hrtime(start);
return Math.round((diff[0] * 1e9 + diff[1]) / 1e6); // msec
}
2020-09-10 12:03:56 +00:00
/**
* Get the ISO string with yesterday's date set (- 24 hours)
*/
function getYesterdayISOString() {
const date = new Date();
date.setDate(date.getDate() - 1);
return date.toISOString();
}
/**
* Get response from response object if available
*/
function getResponseContent(response) {
try {
2021-04-27 16:30:51 +00:00
return JSON.parse(response?.body || response?.text);
} catch {
2021-04-27 16:30:51 +00:00
return response?.body || response?.text;
}
}
2020-10-10 14:04:13 +00:00
/**
* Ensures that the object serializes to JSON properly
*/
function ensureValidJSON(object) {
const replacer = (key, value) => (value === undefined ? "--undefined--" : value);
const stringified = JSON.stringify(object, replacer);
return JSON.parse(stringified);
}
/**
* Authenticate with given credentials and return auth cookie
* Creates new account if username does not exist
* Only authenticates when portal is set to authenticated users only mode
*/
function getAuthCookie() {
// cache auth promise so only one actual request will be made
if (getAuthCookie.cache) return getAuthCookie.cache;
// do not authenticate if it is not necessary
if (!["authenticated", "subscription"].includes(process.env.ACCOUNTS_LIMIT_ACCESS)) return {};
const email = process.env.ACCOUNTS_TEST_USER_EMAIL;
const password = process.env.ACCOUNTS_TEST_USER_PASSWORD;
if (!email) throw new Error("ACCOUNTS_TEST_USER_EMAIL cannot be empty");
if (!password) throw new Error("ACCOUNTS_TEST_USER_PASSWORD cannot be empty");
async function authenticate() {
try {
// authenticate with given test user credentials
const response = await got.post(`${process.env.SKYNET_DASHBOARD_URL}/api/login`, {
json: { email, password },
});
// extract set-cookie from successful authentication request
const cookies = response.headers["set-cookie"];
2022-01-14 10:32:24 +00:00
// throw meaningful error when set-cookie header is missing
if (!cookies) throw new Error(`Auth successful (code ${response.statusCode}) but 'set-cookie' header is missing`);
// find the skynet-jwt cookie
const jwtcookie = cookies.find((cookie) => cookie.startsWith("skynet-jwt"));
2022-01-14 10:32:24 +00:00
// throw meaningful error when skynet-jwt cookie is missing
if (!jwtcookie) throw new Error(`Header 'set-cookie' found but 'skynet-jwt' cookie is missing`);
// extract just the cookie value (no set-cookie props) from set-cookie
return jwtcookie.match(/skynet-jwt=[^;]+;/)[0];
} catch (error) {
// 401 means that service worked but user could not have been authenticated
if (error.response && error.response.statusCode === 401) {
// sign up with the given credentials
await got.post(`${process.env.SKYNET_DASHBOARD_URL}/api/user`, {
json: { email, password },
});
// retry authentication
return authenticate();
}
2022-01-14 09:54:24 +00:00
// rethrow unhandled exception
throw error;
}
}
return (getAuthCookie.cache = authenticate());
}
2022-01-17 12:54:12 +00:00
/**
* isPortalModuleEnabled returns true if the given module is enabled
*/
function isPortalModuleEnabled(module) {
2022-01-17 13:04:55 +00:00
return process.env.PORTAL_MODULES && process.env.PORTAL_MODULES.indexOf(module) !== -1;
2022-01-17 12:54:12 +00:00
}
module.exports = {
calculateElapsedTime,
getYesterdayISOString,
getResponseContent,
2020-10-10 14:04:13 +00:00
ensureValidJSON,
getAuthCookie,
2022-01-17 12:54:12 +00:00
isPortalModuleEnabled,
};