UNPKG

@studyportals/sp-hs-misc

Version:

Miscellaneous code used in HouseStark's projects

190 lines 7.24 kB
import { CognitoUser, CognitoUserPool, CognitoRefreshToken } from 'amazon-cognito-identity-js'; import { CognitoIdentityProviderClient } from "@aws-sdk/client-cognito-identity-provider"; import Cookies from 'js-cookie'; /** * @deprecated Use @studyportals/client-internal-platform-sso */ class UserSessionCookieManager { get intervalDuration() { return this._intervalDuration; } get cognitoClientId() { return this._cognitoClientId; } get cognitoPoolId() { return this._cognitoPoolId; } get cognitoIdentityServiceProvider() { return (this._cognitoIdentityServiceProvider = this._cognitoIdentityServiceProvider || new CognitoIdentityProviderClient()); } get earlyRefreshPeriod() { return UserSessionCookieManager.EARLY_REFRESH_PERIOD_IN_MS; } get cookieDomain() { return this._cookieDomain; } constructor(cognitoClientId, cognitoPoolId, domain) { this._cognitoClientId = cognitoClientId; this._cognitoPoolId = cognitoPoolId; this._cookieDomain = domain; } getUsername() { return this.getCookie(UserSessionCookieManager.COOKIE_USERNAME); } setUsername(value) { this.setCookie(UserSessionCookieManager.COOKIE_USERNAME, value); } getRefreshToken() { return this.getCookie(UserSessionCookieManager.COOKIE_REFRESH_TOKEN); } setRefreshToken(value) { this.setCookie(UserSessionCookieManager.COOKIE_REFRESH_TOKEN, value); } getCreationTime() { return new Date(+this.getCookie(UserSessionCookieManager.COOKIE_CREATION_TIME)); } setCreationTime(date) { this.setCookie(UserSessionCookieManager.COOKIE_CREATION_TIME, String(date.getTime())); } getAvailabilityLength() { return +this.getCookie(UserSessionCookieManager.COOKIE_AVAILABILITY_LENGTH); } setAvailabilityLength(value) { this.setCookie(UserSessionCookieManager.COOKIE_AVAILABILITY_LENGTH, String(value)); } getIdToken() { return this.getCookie(UserSessionCookieManager.COOKIE_ID_TOKEN); } setIdToken(value) { this.setCookie(UserSessionCookieManager.COOKIE_ID_TOKEN, value); } updateCookie(idToken, availabilityLength) { this.setCreationTime(this.getCurrentTime()); this.setAvailabilityLength(availabilityLength); this.setIdToken(idToken); } setCookie(name, value) { Cookies.set(name, value, { domain: `.${this.cookieDomain}` }); } getCookie(name) { return Cookies.get(name); } getAuthorization() { return this.getIdToken(); } keepAlive() { if (!this.isSessionSetup()) { throw new Error("Set-up the session before attempting to install the manager"); } this.generateIntervalDuration(); this.refreshSessionIfNeeded(); this.setInterval(this.refreshSessionIfNeeded, this.intervalDuration); } setupFromSuccessfulAuthentication(authenticationResult) { this.setUsername(authenticationResult.userIdentifier); this.setRefreshToken(authenticationResult.refreshToken); this.updateCookie(authenticationResult.idToken, authenticationResult.idTokenAvailabilityInMs); } setupFromSuccessfulAuthenticationAndKeepAlive(authenticationResult) { this.setupFromSuccessfulAuthentication(authenticationResult); this.keepAlive(); } isSessionSetup() { if (!this.getCookie(UserSessionCookieManager.COOKIE_USERNAME) || !this.getCookie(UserSessionCookieManager.COOKIE_REFRESH_TOKEN) || !this.getCookie(UserSessionCookieManager.COOKIE_CREATION_TIME) || !this.getCookie(UserSessionCookieManager.COOKIE_AVAILABILITY_LENGTH) || !this.getCookie(UserSessionCookieManager.COOKIE_ID_TOKEN)) { return false; } return true; } isSessionSetupAndNotExpired() { return this.isSessionSetup() && !this.sessionExpired(); } keepAliveIfSetup() { if (true === this.isSessionSetup()) { this.keepAlive(); } } keepAliveIfSetupAndNotExpired() { if (true === this.isSessionSetupAndNotExpired()) { this.keepAlive(); } } destroy() { const unixEpoch = new Date(1970, 1, 1); this.setUsername(""); this.setRefreshToken(""); this.setCreationTime(unixEpoch); this.setAvailabilityLength(0); this.setIdToken(""); } sessionExpired() { if (this.getExpirationTime() <= this.getCurrentTime()) { return true; } return false; } getExpirationTime() { return new Date(this.getCreationTime().getTime() + this.getAvailabilityLength() - this.earlyRefreshPeriod); } generateIntervalDuration() { const minValue = 10 * 60 * 1000; /* 10 minutes, in ms */ const maxValue = 29 * 60 * 1000; /* 29 minutes, in ms */ // // To generate a random value between a specified range (a, b), // using an random number generator (RNG) with an uniform // distribution on (0, 1), the following formula is used: // // (b - a) * RNG() + a // this._intervalDuration = Math.floor((maxValue - minValue) * Math.random() + minValue); } mustRefresh() { return (this.getExpirationTime().getTime() - this.getCurrentTime().getTime() - this.intervalDuration) < 0; } refreshSession() { const userPool = this.createCognitoUserPool(this.cognitoPoolId, this.cognitoClientId); const user = this.createCognitoUser(this.getUsername(), userPool); const refreshToken = this.createCognitoRefreshToken(this.getRefreshToken()); user.refreshSession(refreshToken, (err, data) => { if (err) { throw err; } this.updateCookie(data.getIdToken().getJwtToken(), 3600000); }); } refreshSessionIfNeeded() { if (true === this.mustRefresh()) { this.refreshSession(); } } createCognitoUserPool(userPoolId, clientId) { return new CognitoUserPool({ UserPoolId: userPoolId, ClientId: clientId }); } createCognitoUser(username, pool) { return new CognitoUser({ Username: username, Pool: pool }); } createCognitoRefreshToken(refreshToken) { return new CognitoRefreshToken({ RefreshToken: refreshToken }); } setInterval(callback, ms) { const self = this; setInterval(() => { console.log("Session refresh attempt"); callback.call(self); }, ms); } getCurrentTime() { return new Date(); } } UserSessionCookieManager.COOKIE_USERNAME = 'hs-sso-usr'; UserSessionCookieManager.COOKIE_REFRESH_TOKEN = 'hs-sso-token-refresh'; UserSessionCookieManager.COOKIE_CREATION_TIME = 'hs-sso-token-id-crt'; UserSessionCookieManager.COOKIE_AVAILABILITY_LENGTH = 'hs-sso-token-id-av'; UserSessionCookieManager.COOKIE_ID_TOKEN = 'hs-sso-token-id'; UserSessionCookieManager.EARLY_REFRESH_PERIOD_IN_MS = 10000; export { UserSessionCookieManager }; //# sourceMappingURL=user-session-cookie-manager.class.js.map