Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/react app/msal/current account #1646

Merged
merged 4 commits into from
Jan 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/four-tools-tickle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@equinor/fusion-framework-module-msal': patch
---

re-export `AuthenticationResult` from `@azure/msal-browser`
9 changes: 9 additions & 0 deletions .changeset/odd-monkeys-camp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@equinor/fusion-framework-react-app': minor
---

Created namespace for MSAL:

- Created hooks for accessing current authenticated account
- Created hooks for acquiring token
- Created hooks for acquiring access token
5 changes: 5 additions & 0 deletions .changeset/orange-cherries-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@equinor/fusion-framework-cookbook-app-react-msal': major
---

created a cookbook for reading msal account and token
663 changes: 663 additions & 0 deletions cookbooks/app-react-msal/CHANGELOG.md

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions cookbooks/app-react-msal/app.manifest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineAppManifest, mergeManifests } from '@equinor/fusion-framework-cli';

export default defineAppManifest((env, { base }) => {
if (env.command === 'serve') {
return mergeManifests(base, {
key: 'msal',
});
}
return base;
});
24 changes: 24 additions & 0 deletions cookbooks/app-react-msal/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@equinor/fusion-framework-cookbook-app-react-msal",
"version": "0.0.0",
"description": "",
"private": true,
"type": "module",
"main": "src/index.ts",
"scripts": {
"build": "fusion-framework-cli app build",
"dev": "fusion-framework-cli app dev",
"docker": "cd .. && sh docker-script.sh app-react"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@equinor/fusion-framework-cli": "^9.3.0",
"@equinor/fusion-framework-react-app": "^4.1.3",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"typescript": "^5.1.3"
}
}
73 changes: 73 additions & 0 deletions cookbooks/app-react-msal/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useFramework } from '@equinor/fusion-framework-react-app/framework';
import {
useAccessToken,
useToken,
useCurrentAccount,
} from '@equinor/fusion-framework-react-app/msal';
import { useEffect, useMemo, useState } from 'react';

export const App = () => {
/**
* Retrieves the current user account.
* @returns The current user account.
*/
const user = useCurrentAccount();
const framework = useFramework();
/**
* This state variable is used to manage the scopes for MSAL authentication.
*/
const [scopes, setScopes] = useState<string[]>([]);
useEffect(() => {
/**
* get default scope from the framework service discovery module
*/
framework.modules.serviceDiscovery
.resolveService('portal')
.then((x) => x.defaultScopes)
.then(setScopes);
}, [framework]);

return (
<div
style={{
display: 'flex',
justifyContent: 'center',
flexFlow: 'column',
padding: '0 2rem',
}}
>
<div style={{ maxWidth: 'calc(100% - 4rem)', overflow: 'scroll' }}>
<div>
<h1>😎 Current user:</h1>
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
{scopes.length && <AccessToken scopes={scopes} />}
</div>
</div>
);
};

/**
* Component for rendering an access token.
* @param scopes - The scopes required for the access token.
*/
const AccessToken = ({ scopes }: { scopes: string[] }) => {
const { token } = useToken(useMemo(() => ({ scopes }), [scopes]));
const { token: accessToken } = useAccessToken(useMemo(() => ({ scopes }), [scopes]));
return (
<div>
<h2>🧩 Token:</h2>
<b>access token</b>
<br />
<code style={{ lineBreak: 'anywhere' }}>{accessToken}</code>
<br />
<br />
<b>token response</b>
<code>
<pre style={{ overflow: 'scroll' }}>{JSON.stringify(token, null, 4)}</pre>
</code>
</div>
);
};

export default App;
18 changes: 18 additions & 0 deletions cookbooks/app-react-msal/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { AppModuleInitiator } from '@equinor/fusion-framework-react-app';

export const configure: AppModuleInitiator = (configurator, env) => {
/** print render environment arguments */
console.log('configuring application', env);

/** callback when configurations is created */
configurator.onConfigured((config) => {
console.log('application config created', config);
});

/** callback when the application modules has initialized */
configurator.onInitialized((instance) => {
console.log('application config initialized', instance);
});
};

export default configure;
30 changes: 30 additions & 0 deletions cookbooks/app-react-msal/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { createElement } from 'react';
import { createRoot } from 'react-dom/client';

import { ComponentRenderArgs, makeComponent } from '@equinor/fusion-framework-react-app';

import configure from './config';
import App from './App';

/** create a render component */
const appComponent = createElement(App);

/** create React render root component */
const createApp = (args: ComponentRenderArgs) => makeComponent(appComponent, args, configure);

/** Render function */
export const renderApp = (el: HTMLElement, args: ComponentRenderArgs) => {
/** make render element */
const app = createApp(args);

/** create render root from provided element */
const root = createRoot(el);

/** render Application */
root.render(createElement(app));

/** Teardown */
return () => root.unmount();
};

export default renderApp;
22 changes: 22 additions & 0 deletions cookbooks/app-react-msal/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"jsx": "react-jsx",
},
"references": [
{
"path": "../../packages/react/app"
},
{
"path": "../../packages/cli"
},
],
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"lib"
]
}
2 changes: 2 additions & 0 deletions packages/modules/msal/src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export type { AuthenticationResult } from '@azure/msal-browser';

export { default, createAuthClient, AuthClientConfig } from './create-auth-client';

export { ConsoleLogger } from './log/console';
Expand Down
9 changes: 9 additions & 0 deletions packages/react/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
"import": "./dist/esm/http/index.js",
"types": "./dist/types/http/index.d.ts"
},
"./msal": {
"import": "./dist/esm/msal/index.js",
"types": "./dist/types/msal/index.d.ts"
},
"./navigation": {
"import": "./dist/esm/navigation/index.js",
"types": "./dist/types/navigation/index.d.ts"
Expand All @@ -44,6 +48,9 @@
"http": [
"dist/types/http/index.d.ts"
],
"msal": [
"dist/types/msal/index.d.ts"
],
"navigation": [
"dist/types/navigation/index.d.ts"
]
Expand Down Expand Up @@ -75,6 +82,7 @@
},
"devDependencies": {
"@equinor/fusion-framework-module-event": "workspace:^",
"@equinor/fusion-framework-module-msal": "workspace:^",
"@equinor/fusion-framework-react-module-bookmark": "workspace:^",
"@equinor/fusion-framework-react-module-context": "workspace:^",
"@types/react": "^18.2.20",
Expand All @@ -84,6 +92,7 @@
"typescript": "^5.1.3"
},
"peerDependencies": {
"@equinor/fusion-framework-module-msal": "workspace:^",
"@types/react": "^17.0.0 || ^18.0.0",
"react": "^17.0.0 || ^18.0.0",
"react-dom": "^17.0.0 || ^18.0.0"
Expand Down
3 changes: 3 additions & 0 deletions packages/react/app/src/msal/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { useCurrentAccount } from './useCurrentAccount';
export { useAccessToken } from './useAccessToken';
export { useToken } from './useToken';
15 changes: 15 additions & 0 deletions packages/react/app/src/msal/useAccessToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { AuthRequest } from '@equinor/fusion-framework-module-msal/client';
import { useToken } from './useToken';

/**
* Custom hook that retrieves an access token for the specified authentication request.
*
* @param req - The authentication request.
* @returns An object containing the access token, pending state, and error.
*/
export const useAccessToken = (
req: AuthRequest,
): { token?: string; pending: boolean; error: unknown } => {
const { token, error, pending } = useToken(req);
return { token: token?.accessToken, pending, error };
};
11 changes: 11 additions & 0 deletions packages/react/app/src/msal/useCurrentAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { AccountInfo } from '@equinor/fusion-framework-module-msal';
import useAppModule from '../useAppModule';

/**
* Retrieves the current account information from the MSAL provider.
* @returns The current account information or undefined if no account is available.
*/
export const useCurrentAccount = (): AccountInfo | undefined => {
const msalProvider = useAppModule('auth');
return msalProvider.defaultAccount;
};
29 changes: 29 additions & 0 deletions packages/react/app/src/msal/useToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { AuthRequest, AuthenticationResult } from '@equinor/fusion-framework-module-msal/client';
import useAppModule from '../useAppModule';
import { useEffect, useState } from 'react';

/**
* Custom hook for acquiring an authentication token using MSAL.
* @param req - The authentication request.
* @returns An object containing the acquired token, pending state, and error.
*/
export const useToken = (
req: AuthRequest,
): { token?: AuthenticationResult; pending: boolean; error: unknown } => {
const msalProvider = useAppModule('auth');
const [token, setToken] = useState<AuthenticationResult | undefined>(undefined);
const [pending, setPending] = useState<boolean>(false);
const [error, setError] = useState<unknown>(null);
useEffect(() => {
setPending(true);
setToken(undefined);
msalProvider
.acquireToken(req)
.then((token) => token && setToken(token))
.catch(setError)
.finally(() => setPending(false));
}, [msalProvider, req]);
return { token, pending, error };
};

export default useToken;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ [eslint] <prettier/prettier> reported by reviewdog 🐶
Insert

Suggested change
export default useToken;
export default useToken;

35 changes: 31 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading