Skip to content

Commit

Permalink
feat: account context
Browse files Browse the repository at this point in the history
  • Loading branch information
KotaHusky committed Mar 28, 2024
1 parent 420b2d0 commit 187c858
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 15 deletions.
1 change: 1 addition & 0 deletions libs/lib-msal-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './lib/msal-react';
export * from './lib/button-login/button-login';
export * from './lib/button-logout/button-logout';
export * from './lib/account-context/account-context';
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*
* Replace this with your own classes
*
* e.g.
* .container {
* }
*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { render } from '@testing-library/react';

import AccountContext from './account-context';

describe('AccountContext', () => {
it('should render successfully', () => {
const { baseElement } = render(<AccountContext />);
expect(baseElement).toBeTruthy();
});
});
42 changes: 42 additions & 0 deletions libs/lib-msal-react/src/lib/account-context/account-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { createContext, useContext, useEffect, useState } from 'react';
import { useMsal } from '@azure/msal-react';

type AccountState = {
username: string | null;
loading: boolean;
};

/**
* Provides a React context for managing authentication using MSAL.
* This component wraps your application and provides access to the MSAL instance and authentication state.
* It also handles authentication and token acquisition using MSAL.
* @see https://react.dev/learn/passing-data-deeply-with-context
*/
export const AccountContext = createContext<AccountState>({ username: null, loading: true });

// Create a provider component
export const AccountProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { inProgress, accounts } = useMsal();
const [account, setAccount] = useState<AccountState>({ username: null, loading: true });

useEffect(() => {
if (inProgress === 'none' && accounts.length > 0) {
setAccount({ username: accounts[0].username, loading: false });
}
}, [inProgress, accounts]);

return (
<AccountContext.Provider
value={account}
>
{children}
</AccountContext.Provider>
);
};

// Create a hook to use the context
export const useAccount = () => {
return useContext(AccountContext);
};
12 changes: 7 additions & 5 deletions libs/lib-msal-react/src/lib/msal-react.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
'use client';

import React from 'react';
import { Configuration, PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { AccountProvider } from './account-context/account-context';

// Define your MSAL configuration
// MSAL Configuration
const msalConfig: Configuration = {
auth: {
clientId: process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID || '',
Expand All @@ -25,7 +25,7 @@ try {
// Initialize MSAL instance with your configuration
msalInstance = new PublicClientApplication(msalConfig);
} catch (error) {
console.error("Failed to initialize MSAL", error);
console.error('Failed to initialize MSAL', error);
// Handle error here, e.g. by showing an error message to the user
}

Expand All @@ -39,7 +39,9 @@ export const MsalProviderComponent: React.FC<{ children: React.ReactNode }> = ({

return (
<div id="msal-provider">
<MsalProvider instance={msalInstance}>{children}</MsalProvider>
<MsalProvider instance={msalInstance}>
<AccountProvider>{children}</AccountProvider>
</MsalProvider>
</div>
);
};
};
14 changes: 4 additions & 10 deletions libs/ui/src/lib/header/header.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import { AuthenticatedTemplate, useMsal } from "@azure/msal-react";
import { useEffect, useState } from "react";
import { AuthenticatedTemplate } from "@azure/msal-react";
import { useContext } from "react";
import styles from './header.module.css';
import { AccountContext } from '@my-workspace/lib-msal-react'

/* eslint-disable-next-line */
export interface HeaderProps {}

export function Header(props: HeaderProps) {
const { accounts } = useMsal();
const [username, setUsername] = useState("");

useEffect(() => {
if (accounts.length > 0) {
setUsername(accounts[0].username);
}
}, [accounts]);
const { username } = useContext(AccountContext); // Use AccountContext

return (
<div className={styles['container']}>
Expand Down

0 comments on commit 187c858

Please sign in to comment.