UNPKG

pi-msal-auth-lib

Version:

MSAL authentication library for React applications

56 lines (55 loc) 1.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useSmartAuth = void 0; var _react = require("react"); var _msalReact = require("@azure/msal-react"); const useSmartAuth = (options = {}) => { const { instance, accounts } = (0, _msalReact.useMsal)(); const [account, setAccount] = (0, _react.useState)(null); const [isLoading, setIsLoading] = (0, _react.useState)(false); const [error, setError] = (0, _react.useState)(null); (0, _react.useEffect)(() => { if (accounts.length > 0) { setAccount(accounts[0]); } }, [accounts]); const login = async () => { setIsLoading(true); try { await instance.loginRedirect({ scopes: options.scopes || ["User.Read"] }); } catch (err) { setError(err); throw err; } finally { setIsLoading(false); } }; const getToken = async () => { if (!account) throw new Error("No account found"); try { const response = await instance.acquireTokenSilent({ scopes: options.scopes || ["User.Read"], account: account }); return response.accessToken; } catch (error) { throw error; } }; return { account, isLoading, error, login, getToken, instance }; }; exports.useSmartAuth = useSmartAuth;