UNPKG

pi-msal-auth-lib

Version:

MSAL authentication library for React applications

68 lines (67 loc) 1.68 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MsalAuthService = void 0; var _msalBrowser = require("@azure/msal-browser"); class MsalAuthService { constructor(config) { this.msalInstance = new _msalBrowser.PublicClientApplication(config); this.account = null; this.isInitialized = false; } async initialize() { if (!this.isInitialized) { await this.msalInstance.initialize(); const accounts = this.msalInstance.getAllAccounts(); if (accounts.length > 0) { this.account = accounts[0]; } this.isInitialized = true; // Mark as initialized } } async login(scopes = ["user.read"]) { try { const response = await this.msalInstance.loginPopup({ scopes }); this.account = response.account; return response; } catch (error) { throw error; } } async logout() { try { await this.msalInstance.logoutPopup(); this.account = null; } catch (error) { throw error; } } async acquireToken(scopes = ["user.read"]) { try { if (!this.account) { throw new Error("No active account"); } const silentRequest = { scopes, account: this.account }; try { return await this.msalInstance.acquireTokenSilent(silentRequest); } catch (error) { return await this.msalInstance.acquireTokenPopup(silentRequest); } } catch (error) { throw error; } } getAccount() { return this.account; } getAllAccounts() { return this.msalInstance.getAllAccounts(); } } exports.MsalAuthService = MsalAuthService;