UNPKG

@brionmario-experimental/asgardeo-auth-spa

Version:

Asgardeo Auth SPA SDK to be used in Single-Page Applications.

201 lines 8.49 kB
/** * Copyright (c) 2020-2024, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { AsgardeoAuthClient, SIGN_OUT_SUCCESS_PARAM, SIGN_OUT_URL } from "@asgardeo/auth-js"; import { ERROR, ERROR_DESCRIPTION, INITIALIZED_SILENT_SIGN_IN, PROMPT_NONE_REQUEST_SENT, SILENT_SIGN_IN_STATE, STATE_QUERY } from "../constants"; export class SPAUtils { // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } static removeAuthorizationCode() { const url = location.href; history.pushState({}, document.title, url.replace(/\?code=.*$/, "")); } static getPKCE(pkceKey) { var _a; return (_a = sessionStorage.getItem(pkceKey)) !== null && _a !== void 0 ? _a : ""; } static setPKCE(pkceKey, pkce) { sessionStorage.setItem(pkceKey, pkce); } static setSignOutURL(url, clientID, instanceID) { sessionStorage.setItem(`${SIGN_OUT_URL}-instance_${instanceID}-${clientID}`, url); } static getSignOutURL(clientID, instanceID) { var _a; return (_a = sessionStorage.getItem(`${SIGN_OUT_URL}-instance_${instanceID}-${clientID}`)) !== null && _a !== void 0 ? _a : ""; } static removePKCE(pkceKey) { sessionStorage.removeItem(pkceKey); } /** * This method is used to discontinue the execution of the `signIn` method if `callOnlyOnRedirect` is true and * the method is not called on being redirected from the authorization server. * * This method can be used to allow the `signIn` method to be called only * on being redirected from the authorization server. * * @param callOnlyOnRedirect {boolean} - True if the method should only be called on redirect. * @param authorizationCode {string} - Authorization code. * * @returns {boolean} - True if the method should be called. */ static canContinueSignIn(callOnlyOnRedirect, authorizationCode) { if (callOnlyOnRedirect && !SPAUtils.hasErrorInURL() && !SPAUtils.hasAuthSearchParamsInURL() && !authorizationCode) { return false; } return true; } /** * Specifies if `trySilentSignIn` has been called. * * @returns {boolean} True if the `trySilentSignIn` method has been called once. */ static isInitializedSilentSignIn() { return SPAUtils.isSilentStatePresentInURL(); } /** * Specifies if the `signIn` method has been called. * * @returns {boolean} True if the `signIn` has been called. */ static wasSignInCalled() { if (SPAUtils.hasErrorInURL() || SPAUtils.hasAuthSearchParamsInURL()) { if (!this.isSilentStatePresentInURL()) { return true; } } return false; } static wasSilentSignInCalled() { const silentSignIsInitialized = sessionStorage.getItem(INITIALIZED_SILENT_SIGN_IN); const isSilentSignInInitialized = silentSignIsInitialized ? JSON.parse(silentSignIsInitialized) : null; return Boolean(isSilentSignInInitialized); } static isSignOutSuccessful() { return __awaiter(this, void 0, void 0, function* () { if (AsgardeoAuthClient.isSignOutSuccessful(window.location.href)) { const newUrl = window.location.href.split("?")[0]; history.pushState({}, document.title, newUrl); yield AsgardeoAuthClient.clearUserSessionData(); return true; } return false; }); } static didSignOutFail() { if (AsgardeoAuthClient.didSignOutFail(window.location.href)) { const url = new URL(window.location.href); const error = url.searchParams.get(ERROR); const description = url.searchParams.get(ERROR_DESCRIPTION); const newUrl = window.location.href.split("?")[0]; history.pushState({}, document.title, newUrl); return { description: description !== null && description !== void 0 ? description : "", error: error !== null && error !== void 0 ? error : "" }; } return false; } /** * Checks if the URL the user agent is redirected to after an authorization request has the state parameter. * * @returns {boolean} True if there is a session-check state or a silent sign-in state. */ static isSilentStatePresentInURL() { var _a; const state = new URL(window.location.href).searchParams.get("state"); return (_a = state === null || state === void 0 ? void 0 : state.includes(SILENT_SIGN_IN_STATE)) !== null && _a !== void 0 ? _a : false; } /** * Util function to test if `code` and `session_state` are available in the URL as search params. * @since 0.2.0 * * @param params - Search params. * @return {boolean} */ static hasAuthSearchParamsInURL(params = window.location.search) { const AUTH_CODE_REGEXP = /[?&]code=[^&]+/; return AUTH_CODE_REGEXP.test(params); } /** * Util function to check if the URL contains an error. * * @param url - URL to be checked. * * @returns {boolean} - True if the URL contains an error. */ static hasErrorInURL(url = window.location.href) { const urlObject = new URL(url); return (!!urlObject.searchParams.get(ERROR) && urlObject.searchParams.get(STATE_QUERY) !== SIGN_OUT_SUCCESS_PARAM); } /** * Checks if a prompt none can be sent by checking if a request has already been sent. * * @since 0.2.3 * * @returns {boolean} - True if a prompt none request has not been sent. */ static canSendPromptNoneRequest() { const promptNoneRequestSentRaw = sessionStorage.getItem(PROMPT_NONE_REQUEST_SENT); const promptNoneRequestSent = promptNoneRequestSentRaw ? JSON.parse(promptNoneRequestSentRaw) : null; return !promptNoneRequestSent; } /** * Sets the status of prompt none request. * * @since 0.2.3 * * @param canSend {boolean} - True if a prompt none request can be sent. */ static setPromptNoneRequestSent(canSend) { sessionStorage.setItem(PROMPT_NONE_REQUEST_SENT, JSON.stringify(canSend)); } /** * Waits for a specified amount of time to give the user agent enough time to redirect. * * @param time {number} - Time in seconds. */ static waitTillPageRedirect(time) { return __awaiter(this, void 0, void 0, function* () { const timeToWait = time !== null && time !== void 0 ? time : 3000; yield new Promise((resolve) => setTimeout(resolve, timeToWait * 1000)); }); } } /** * Waits for a condition before executing the rest of the code in non-blocking manner. * * @param condition {() => boolean} - Condition to be checked. * @param timeout {number} - Time in miliseconds. */ SPAUtils.until = (condition, timeout = 500) => { const poll = (done) => (condition() ? done() : setTimeout(() => poll(done), timeout)); return new Promise(poll); }; //# sourceMappingURL=spa-utils.js.map