@shane32/msoauth
Version:
A React library for Azure AD authentication with PKCE (Proof Key for Code Exchange) flow support. This library provides a secure and easy-to-use solution for implementing Azure AD authentication in React applications, with support for both API and Microso
54 lines (53 loc) • 2.84 kB
JavaScript
import React, { useEffect, useState, useMemo } from "react";
import AuthContext from "./AuthContext";
import AuthManagersContext from "./AuthManagersContext";
import ProxyAuthManager from "./ProxyAuthManager";
/**
* Provider component for multiple auth managers
* Uses a ProxyAuthManager to handle provider selection when no provider is active
*/
function MultiAuthProvider(_a) {
var authManagers = _a.authManagers, children = _a.children;
// Create the proxy manager
var proxyAuthManager = useMemo(function () { return new ProxyAuthManager(authManagers); }, [authManagers]);
// Helper to create a new map of auth managers by ID
var createAuthManagersMap = React.useCallback(function () {
var map = new Map();
authManagers.forEach(function (manager) {
map.set(manager.id, manager);
});
return map;
}, [authManagers]);
// Compute the current auth manager
var getCurrentAuthManager = React.useCallback(function () { return authManagers.find(function (provider) { return provider.isAuthenticated(); }) || proxyAuthManager; }, [authManagers, proxyAuthManager]);
// Create a wrapper object that changes on each auth state change to trigger context updates
var _b = useState(function () { return ({
authManager: getCurrentAuthManager(),
}); }), contextValue = _b[0], setContextValue = _b[1];
// Create a map that changes on each auth state change to trigger context updates
var _c = useState(function () { return createAuthManagersMap(); }), authManagersMap = _c[0], setAuthManagersMap = _c[1];
useEffect(function () {
var handleAuthChange = function () {
// Create new objects to trigger context updates across the app
setContextValue({ authManager: getCurrentAuthManager() });
setAuthManagersMap(createAuthManagersMap());
};
// Subscribe to auth events for all providers
authManagers.forEach(function (provider) {
provider.addEventListener("login", handleAuthChange);
provider.addEventListener("logout", handleAuthChange);
});
// Try to auto-login with the proxy manager
proxyAuthManager.autoLogin().then(handleAuthChange);
// Cleanup subscriptions
return function () {
authManagers.forEach(function (provider) {
provider.removeEventListener("login", handleAuthChange);
provider.removeEventListener("logout", handleAuthChange);
});
};
}, [authManagers, proxyAuthManager, getCurrentAuthManager, createAuthManagersMap]);
return (React.createElement(AuthManagersContext.Provider, { value: authManagersMap },
React.createElement(AuthContext.Provider, { value: contextValue }, children)));
}
export default MultiAuthProvider;