@aws-northstar/ui
Version:
NorthStar Design System v2
36 lines (35 loc) • 1.25 kB
JavaScript
// Session storage key for cached credentials
const STORAGE_KEY = 'northstar.sigv4fetch.session';
// Credential expiration grace time before considering credentials as expired
const OFFSET_MILLIS = 30 * 1000; // 30 seconds
/**
* Returns cached credentials from session storage (if available and they have not expired)
*/
export const getCachedCredentials = () => {
const rawCachedCredentials = window.sessionStorage.getItem(STORAGE_KEY);
if (rawCachedCredentials) {
try {
const cachedCredentials = JSON.parse(rawCachedCredentials);
const now = Date.now();
if (cachedCredentials.expiration && cachedCredentials.expiration > now + OFFSET_MILLIS) {
return {
...cachedCredentials,
expiration: new Date(cachedCredentials.expiration),
};
}
}
catch {
// Credentials can't be read
}
}
return undefined;
};
/**
* Write credentials to the session storage cache
*/
export const setCachedCredentials = (credentials) => {
window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify({
...credentials,
expiration: credentials.expiration?.getTime(),
}));
};