UNPKG

@trap_stevo/legendarybuilderproreact-ui

Version:

The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton

184 lines (173 loc) 6.86 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; /* Created by Hassan Steven Compton. March 7, 2024. */ import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'; var AuthContext = /*#__PURE__*/createContext(); /** * AuthProvider provides user authentication encapsulation within an application; keeping track of user credentials and user authenticated state. * * @component * @param {React.ReactNode} children - The content wrapped by this component. * @param {boolean} [autoSignIn=false] - Determines whether to automatically sign in the user if session data is found in localStorage. * @param {number} [signedSessionTimeout=18000] - Session timeout in seconds. Default is 5 hours. * @param {boolean} [saveSessionCacheOnTimeout=false] - Determines whether to save session cache on timeout. * @param {Array} [keysToClearOnTimeout=[]] - List of keys to clear from session cache on timeout. * @returns {JSX.Element} The AuthProvider component encapsulating children with authentication context. */ export var AuthProvider = function AuthProvider(_ref) { var children = _ref.children, _ref$autoSignIn = _ref.autoSignIn, autoSignIn = _ref$autoSignIn === void 0 ? false : _ref$autoSignIn, _ref$signedSessionTim = _ref.signedSessionTimeout, signedSessionTimeout = _ref$signedSessionTim === void 0 ? 18000 : _ref$signedSessionTim, _ref$saveSessionCache = _ref.saveSessionCacheOnTimeout, saveSessionCacheOnTimeout = _ref$saveSessionCache === void 0 ? false : _ref$saveSessionCache, _ref$keysToClearOnTim = _ref.keysToClearOnTimeout, keysToClearOnTimeout = _ref$keysToClearOnTim === void 0 ? [] : _ref$keysToClearOnTim; /** * Initializes the current signed state from cache. * * @function * @name currentSignedState * @returns {Object} The current signed user and signed-in status. */ var currentSignedState = useCallback(function () { var savedUser = localStorage.getItem("SignedUserCredential"); var userSignedIn = localStorage.getItem("UserSignedIn"); return { currentSignedUser: savedUser ? JSON.parse(savedUser) : {}, currentSignedIn: userSignedIn ? JSON.parse(userSignedIn) : false }; }, []); /** * Responsible for the user's credentials. * * @type {Object} */ var _useState = useState(function () { return currentSignedState().currentSignedUser; }), _useState2 = _slicedToArray(_useState, 2), signedUser = _useState2[0], setSignedUser = _useState2[1]; /** * Allows for checking the user's authentication state. * * @type {boolean} */ var _useState3 = useState(function () { return currentSignedState().currentSignedIn; }), _useState4 = _slicedToArray(_useState3, 2), signedIn = _useState4[0], setSignedIn = _useState4[1]; /** * Synchronizes the current state to the cache. * * @function * @name syncStateToCache * @param {Object} user - The user's credentials. * @param {boolean} signedIn - The user's signed-in status. */ var syncStateToCache = useCallback(function (user, signedIn) { localStorage.setItem("SignedUserCredential", JSON.stringify(user)); localStorage.setItem("UserSignedIn", JSON.stringify(signedIn)); localStorage.setItem("SignedSessionStart", Date.now().toString()); }, []); /** * Signs in user. * * @function * @name signIn * @description Sets the user's authentication state to true. */ var signIn = useCallback(function () { setSignedIn(true); syncStateToCache(signedUser, true); return; }, [signedUser, syncStateToCache]); /** * Signs out user. * * @function * @name signOut * @param {boolean} [saveSessionCache=false] - Determines whether to clear the user's saved session cache on sign out. * @param {Array} [keysToClear=[]] - List of keys to clear from session cache on sign out. * @description Sets the user's authentication state to false. */ var signOut = useCallback(function () { var saveSessionCache = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var keysToClear = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; setSignedIn(false); setSignedUser({}); localStorage.removeItem("SignedUserCredential"); if (!saveSessionCache) { if (keysToClear.length > 0) { var sessionCache = JSON.parse(localStorage.getItem("HUDSessionCache")) || {}; keysToClear.forEach(function (key) { delete sessionCache[key]; }); localStorage.setItem("HUDSessionCache", JSON.stringify(sessionCache)); } else { localStorage.removeItem("HUDSessionCache"); } } localStorage.removeItem("SignedSessionStart"); localStorage.removeItem("UserSignedIn"); return; }, []); /** * Checks if the user authentication session timed out. * * @function * @name checkSignedSessionTimeout */ var checkSignedSessionTimeout = useCallback(function () { var sessionStart = parseInt(localStorage.getItem("SessionStart"), 10); if (sessionStart && Date.now() - sessionStart > signedSessionTimeout * 1000) { signOut(saveSessionCacheOnTimeout, keysToClearOnTimeout); } }, [signedSessionTimeout, signOut, saveSessionCacheOnTimeout, keysToClearOnTimeout]); useEffect(function () { if (autoSignIn) { var _currentSignedState = currentSignedState(), currentSignedUser = _currentSignedState.currentSignedUser, currentSignedIn = _currentSignedState.currentSignedIn; if (currentSignedUser && currentSignedIn) { setSignedUser(currentSignedUser); setSignedIn(currentSignedIn); } } var interval = setInterval(checkSignedSessionTimeout, 1000); return function () { return clearInterval(interval); }; }, [autoSignIn, currentSignedState, checkSignedSessionTimeout]); return /*#__PURE__*/React.createElement(AuthContext.Provider, { value: { signedUser: signedUser, setSignedUser: setSignedUser, signedIn: signedIn, signIn: signIn, signOut: signOut } }, children); }; /** * Allows access to the signed user's credentials and provides functions to checking the user's authentication state to signing a user out. * This component allows access to signedUser, setSignedUser, signedIn, signIn, signOut. * * @hook * @returns {Object} The authentication context including user state and auth functions. * @example * const { signedUser, signedIn, signIn, signOut } = useAuth(); */ export var useAuth = function useAuth() { var context = useContext(AuthContext); if (!context) { throw new Error('Must use within an AuthProvider'); } return context; };